Skip to contentSkip to conversation

6.12.120-rc1 review

PATCH In review Greg Kroah-Hartman 3 participants 821 messages Nov 25 Page 5 of 7

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

PATCH 462/816 dmaengine: ste_dma40: Recover coalesced cyclic callbacks

In reply to Greg Kroah-Hartman

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

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

From: Linus Walleij <[email protected]>

[ Upstream commit db28400d92cd97005065dad230b8a5d72ab121cb ]

DMA40 has one terminal-count status bit per channel, so cyclic period interrupts can coalesce.

Use the memory-side pointer displacement to queue the minimum observable number of callbacks. If sampling fails, queue one callback and invalidate the saved position; the next successful sample resynchronizes without recounting it.

The pointer is modulo the cyclic buffer: a displacement of d periods can mean d plus n complete iterations of the buffer. Report d, so the driver could have missed n iterations of the buffer; DMA40 has no counter to recover them. For an unchanged pointer, report one callback rather than risk a spurious full-buffer burst.

This condition has not been seen in practice and is only a product of review comments that the buffer can miss interrupts.

The preceding cyclic-residue fix ensures that every cyclic period fits in one LLI, so each boundary corresponds to one client callback.

Fixes 0c842b551063 ("dma40: cyclic xfer support")
Assisted-by LLM
---
 drivers/dma/ste_dma40.c | 69 ++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 68 insertions(+), 1 deletion(-)
drivers/dma/ste_dma40.c +68 -1
index 53e56b4be3fca..2c83eb05faa16 100644
@@ -374,11 +374,14 @@ struct d40_lli_pool {
  * @cyclic_dma_addr: Start address of the cyclic buffer.
  * @cyclic_buf_len: Length of the cyclic buffer.
  * @cyclic_residue: Last valid cyclic residue sample.
+ * @cyclic_period_len: Length of one cyclic period.
+ * @cyclic_callback_pos: Position after the callbacks already queued.
  * @txd: DMA engine struct. Used for among other things for communication
  * during a transfer.
  * @node: List entry.
  * @is_in_client_list: true if the client owns this descriptor.
  * @cyclic: true if this is a cyclic job
+ * @cyclic_callback_pos_valid: Whether cyclic_callback_pos is reliable.
  *
  * This descriptor is used for both logical and physical transfers.
  */
@@ -395,12 +398,15 @@ struct d40_desc {
 	dma_addr_t			 cyclic_dma_addr;
 	size_t				 cyclic_buf_len;
 	size_t				 cyclic_residue;
+	size_t				 cyclic_period_len;
+	size_t				 cyclic_callback_pos;
 
 	struct dma_async_tx_descriptor	 txd;
 	struct list_head		 node;
 
 	bool				 is_in_client_list;
 	bool				 cyclic;
+	bool				 cyclic_callback_pos_valid;
 };
 
 /**
@@ -1479,6 +1485,61 @@ static bool d40_cyclic_offset(struct d40_chan *d40c, struct d40_desc *d40d,
 	return false;
 }
 
+static unsigned int d40_cyclic_periods_elapsed(struct d40_chan *d40c,
+					       struct d40_desc *d40d)
+{
+	size_t current_pos;
+	size_t delta;
+	size_t offset;
+	unsigned int periods;
+
+	if (!d40d->cyclic_period_len)
+		return 1;
+
+	if (!d40_cyclic_offset(d40c, d40d, &offset)) {
+		d40d->cyclic_callback_pos_valid = false;
+		return 1;
+	}
+
+	current_pos = rounddown(offset, d40d->cyclic_period_len);
+	if (!d40_residue(d40c) && current_pos != offset)
+		current_pos += d40d->cyclic_period_len;
+	if (current_pos == d40d->cyclic_buf_len)
+		current_pos = 0;
+
+	if (!d40d->cyclic_callback_pos_valid) {
+		/*
+		 * The previous interrupt was reported without a pointer
+		 * sample. Resynchronize without using the stale position,
+		 * which would count that callback again.
+		 */
+		d40d->cyclic_callback_pos = current_pos;
+		d40d->cyclic_callback_pos_valid = true;
+		return 1;
+	}
+
+	/*
+	 * The pointer wraps with the cyclic buffer, so its displacement is
+	 * only the minimum number of elapsed periods. Complete buffer laps
+	 * are not observable.
+	 */
+	delta = (current_pos + d40d->cyclic_buf_len -
+		 d40d->cyclic_callback_pos) % d40d->cyclic_buf_len;
+	periods = delta / d40d->cyclic_period_len;
+	if (!periods) {
+		/*
+		 * The TC status is a single latched bit. An unchanged pointer
+		 * cannot distinguish a complete lap from a repeated interrupt,
+		 * so do not amplify it into a buffer's worth of callbacks.
+		 */
+		periods = 1;
+	}
+
+	d40d->cyclic_callback_pos = current_pos;
+
+	return periods;
+}
+
 static bool d40_tx_is_linked(struct d40_chan *d40c)
 {
 	bool is_link;
@@ -1626,6 +1687,7 @@ static struct d40_desc *d40_queue_start(struct d40_chan *d40c)
 static void dma_tc_handle(struct d40_chan *d40c)
 {
 	struct d40_desc *d40d;
+	unsigned int callbacks = 1;
 
 	/* Get first active entry from list */
 	d40d = d40_first_active_get(d40c);
@@ -1650,6 +1712,8 @@ static void dma_tc_handle(struct d40_chan *d40c)
 			if (d40d->lli_current == d40d->lli_len)
 				d40d->lli_current = 0;
 		}
+
+		callbacks = d40_cyclic_periods_elapsed(d40c, d40d);
 	} else {
 		d40_lcla_free_all(d40c, d40d);
 
@@ -1670,7 +1734,7 @@ static void dma_tc_handle(struct d40_chan *d40c)
 		}
 	}
 
-	d40c->pending_tx++;
+	d40c->pending_tx += callbacks;
 	tasklet_schedule(&d40c->tasklet);
 
 }
@@ -2744,6 +2808,9 @@ dma40_prep_dma_cyclic(struct dma_chan *chan, dma_addr_t dma_addr,
 		desc->cyclic_dma_addr = buf_addr;
 		desc->cyclic_buf_len = buf_len;
 		desc->cyclic_residue = buf_len;
+		desc->cyclic_period_len = period_len;
+		desc->cyclic_callback_pos = 0;
+		desc->cyclic_callback_pos_valid = true;
 	}
 
 	kfree(sg);
Signature · 1 line
2.53.0
author maintainer
#467 lore raw

PATCH 463/816 proc: report SIGEV_NONE in /proc/pid/timers if target task has died

In reply to Greg Kroah-Hartman

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

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

From: Andrei Vagin <[email protected]>

[ Upstream commit 0a27f795030ce6a2c71525b0544e3b13bba8828e ]

When a posix timer is created targeting a specific thread (using SIGEV_SIGNAL | SIGEV_THREAD_ID), it takes a reference to the target struct pid in timer->it_pid. If the target thread subsequently terminates, its numeric tid is freed and can be recycled for an unrelated task. However, the timer holds its reference to the original struct pid.

show_timer() in /proc/[pid]/timers previously called pid_nr_ns() directly on timer->it_pid without checking whether any task remained attached to that struct pid. As a result:

1. It reported the stale tid, which could mistakenly refer to a recycled pid.

2. In the kernel, expired signals for dead target threads are dropped by posixtimer_send_sigqueue() because posixtimer_get_target() returns NULL, so the timer functionally acts as SIGEV_NONE.

3. Checkpoint/restore tools (CRIU) parsing /proc/[pid]/timers would try to restore a timer with SIGEV_SIGNAL | SIGEV_THREAD_ID targeting a non-existent or unrelated thread.

Check pid_has_task(timer->it_pid, timer->it_pid_type) in show_timer(). If the target task has died, override notify to SIGEV_NONE and report PID 0 (e.g., 'notify: none/pid.0').

Fixes 57b8015e07a7 ("posix-timers: Show sigevent info in proc file")
Cc Thomas Gleixner <[email protected]>
[ sashal: Replaced the missing it_pid_type field with (notify & SIGEV_THREAD_ID) ? PIDTYPE_PID : PIDTYPE_TGID and adapted to the local show_timer() layout, without the guard() lock or posixtimer_valid(). ]
---
 fs/proc/base.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
fs/proc/base.c +9 -1
index 427fb5abb07c7..0f58fe8697c4e 100644
@@ -2527,6 +2527,7 @@ static int show_timer(struct seq_file *m, void *v)
 	struct k_itimer *timer;
 	struct timers_private *tp = m->private;
 	int notify;
+	pid_t nr = 0;
 	static const char * const nstr[] = {
 		[SIGEV_SIGNAL] = "signal",
 		[SIGEV_NONE] = "none",
@@ -2536,6 +2537,13 @@ static int show_timer(struct seq_file *m, void *v)
 	timer = hlist_entry((struct hlist_node *)v, struct k_itimer, list);
 	notify = timer->it_sigev_notify;
 
+	if (timer->it_pid &&
+	    pid_has_task(timer->it_pid,
+			 (notify & SIGEV_THREAD_ID) ? PIDTYPE_PID : PIDTYPE_TGID))
+		nr = pid_nr_ns(timer->it_pid, tp->ns);
+	else
+		notify = SIGEV_NONE;
+
 	seq_printf(m, "ID: %d\n", timer->it_id);
 	seq_printf(m, "signal: %d/%px\n",
 		   timer->sigq->info.si_signo,
@@ -2543,7 +2551,7 @@ static int show_timer(struct seq_file *m, void *v)
 	seq_printf(m, "notify: %s/%s.%d\n",
 		   nstr[notify & ~SIGEV_THREAD_ID],
 		   (notify & SIGEV_THREAD_ID) ? "tid" : "pid",
-		   pid_nr_ns(timer->it_pid, tp->ns));
+		   nr);
 	seq_printf(m, "ClockID: %d\n", timer->it_clock);
 
 	return 0;
Signature · 1 line
2.53.0
author maintainer
#468 lore raw

PATCH 464/816 wifi: mt76: mt7996: validate TLV length in mt7996_mcu_ie_countdown()

In reply to Greg Kroah-Hartman

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

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

From: Aamir Ahmed <[email protected]>

[ Upstream commit e75897e6cb8b900d095acf6fbff1ffb026c86c35 ]

mt7996_mcu_ie_countdown() iterates over TLV entries in the countdown event but only checks for a non-zero tlv->len. A malformed event with a TLV length smaller than the 4-byte TLV header advances the cursor by less than a header size, causing misaligned reads on subsequent iterations. A TLV whose declared length exceeds the remaining buffer is also not caught, so the cursor can overshoot the end. The band field of the event header is also read without checking that the event is long enough to contain it.

This is the same class of bug fixed for mt7925 in commit fc7801b7f11d ("wifi: mt76: mt7925: fix infinite loop in UNI event TLV parsing").

Fix by checking that the event contains the header before reading the band, and that each TLV is large enough to contain the countdown notify payload and does not exceed the remaining buffer.

Fixes 98686cd21624 ("wifi: mt76: mt7996: add driver for MediaTek Wi-Fi 7 (802.11be) devices")
Assisted-by Claude (Anthropic)
[ sashal: Added bounds checks in the countdown TLV parser, using a literal 4 for the payload size because the countdown notify struct doesn't exist in this tree. ]
---
 drivers/net/wireless/mediatek/mt76/mt7996/mcu.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
drivers/net/wireless/mediatek/mt76/mt7996/mcu.c +10 -2
index a8a0737635d27..edb825675408c 100644
@@ -450,6 +450,9 @@ mt7996_mcu_ie_countdown(struct mt7996_dev *dev, struct sk_buff *skb)
 	struct header *hdr = (struct header *)data;
 	struct tlv *tlv = (struct tlv *)(data + 4);
 
+	if (skb->len < sizeof(*rxd) + sizeof(*hdr))
+		return;
+
 	if (hdr->band >= ARRAY_SIZE(dev->mt76.phys))
 		return;
 
@@ -458,7 +461,12 @@ mt7996_mcu_ie_countdown(struct mt7996_dev *dev, struct sk_buff *skb)
 
 	tail = skb->data + skb->len;
 	data += sizeof(struct header);
-	while (data + sizeof(struct tlv) < tail && le16_to_cpu(tlv->len)) {
+	while (data + sizeof(struct tlv) <= tail) {
+		u16 tag_len = le16_to_cpu(tlv->len);
+
+		if (tag_len < sizeof(*tlv) + 4 || data + tag_len > tail)
+			break;
+
 		switch (le16_to_cpu(tlv->tag)) {
 		case UNI_EVENT_IE_COUNTDOWN_CSA:
 			ieee80211_iterate_active_interfaces_atomic(mphy->hw,
@@ -472,7 +480,7 @@ mt7996_mcu_ie_countdown(struct mt7996_dev *dev, struct sk_buff *skb)
 			break;
 		}
 
-		data += le16_to_cpu(tlv->len);
+		data += tag_len;
 		tlv = (struct tlv *)data;
 	}
 }
Signature · 1 line
2.53.0
author maintainer
#469 lore raw

PATCH 465/816 wifi: mt76: mt7996: enable the SKU power limit table

In reply to Greg Kroah-Hartman

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

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

From: Felix Fietkau <[email protected]>

[ Upstream commit 267424ac63aa65fb28b7f3cff1e1a7d0098c4d6f ]

mt7996_mcu_set_txpower_sku() uploads the per-rate power limit table, but the firmware applies it only after the driver enables the SKU power limit. mt7915 does that in mt7915_mcu_set_sku_en(); mt7996 never does, so the radio keeps the EEPROM target power and the configured tx power has no effect.

Add the power control command and enable the table per band in mt7996_run(), as the MediaTek vendor driver does.

The backoff table stays disabled. This driver does not build the per-path limits; it pads that part of the message with zeros.

Fixes f75e4779d215 ("wifi: mt76: mt7996: add txpower setting support")
[ sashal: Changed the return ret; in mt7996_run() to goto out;, and dropped the missing sniffer-mode and rdd_resume_tx context from the mcu.c and mt7996.h hunks. ]
---
 .../net/wireless/mediatek/mt76/mt7996/main.c  |  5 +++
 .../net/wireless/mediatek/mt76/mt7996/mcu.c   | 34 +++++++++++++++++++
 .../net/wireless/mediatek/mt76/mt7996/mcu.h   | 23 +++++++++++++
 .../wireless/mediatek/mt76/mt7996/mt7996.h    |  1 +
 4 files changed, 63 insertions(+)
drivers/net/wireless/mediatek/mt76/mt7996/main.c +5 -0
index bdb5e82d9f4e7..1074b677ebd81 100644
@@ -67,6 +67,11 @@ int mt7996_run(struct ieee80211_hw *hw)
 	if (ret)
 		goto out;
 
+	ret = mt7996_mcu_set_tx_power_ctrl(phy, UNI_TXPOWER_SKU_POWER_LIMIT_CTRL,
+					   true);
+	if (ret)
+		goto out;
+
 	set_bit(MT76_STATE_RUNNING, &phy->mt76->state);
 
 	ieee80211_queue_delayed_work(hw, &phy->mt76->mac_work,
drivers/net/wireless/mediatek/mt76/mt7996/mcu.c +34 -0
index edb825675408c..67fa3db3171f8 100644
@@ -4566,6 +4566,40 @@ int mt7996_mcu_wed_rro_reset_sessions(struct mt7996_dev *dev, u16 id)
 				 sizeof(req), true);
 }
 
+int mt7996_mcu_set_tx_power_ctrl(struct mt7996_phy *phy, u8 power_ctrl_id, u8 data)
+{
+	struct mt7996_dev *dev = phy->dev;
+	struct tx_power_ctrl req = {
+		.tag = cpu_to_le16(power_ctrl_id),
+		.len = cpu_to_le16(sizeof(req) - 4),
+		.power_ctrl_id = power_ctrl_id,
+		.band_idx = phy->mt76->band_idx,
+	};
+
+	switch (power_ctrl_id) {
+	case UNI_TXPOWER_SKU_POWER_LIMIT_CTRL:
+		req.sku_enable = !!data;
+		break;
+	case UNI_TXPOWER_PERCENTAGE_CTRL:
+		req.percentage_ctrl_enable = !!data;
+		break;
+	case UNI_TXPOWER_PERCENTAGE_DROP_CTRL:
+		req.power_drop_level = data;
+		break;
+	case UNI_TXPOWER_BACKOFF_POWER_LIMIT_CTRL:
+		req.bf_backoff_enable = !!data;
+		break;
+	case UNI_TXPOWER_ATE_MODE_CTRL:
+		req.ate_mode_enable = !!data;
+		break;
+	default:
+		return -EINVAL;
+	}
+
+	return mt76_mcu_send_msg(&dev->mt76, MCU_WM_UNI_CMD(TXPOWER),
+				 &req, sizeof(req), false);
+}
+
 int mt7996_mcu_set_txpower_sku(struct mt7996_phy *phy)
 {
 #define TX_POWER_LIMIT_TABLE_RATE	0
drivers/net/wireless/mediatek/mt76/mt7996/mcu.h +23 -0
index dd5b168c71f06..d56fdabd959af 100644
@@ -892,8 +892,31 @@ enum {
 	UNI_CMD_THERMAL_PROTECT_DUTY_CONFIG,
 };
 
+struct tx_power_ctrl {
+	u8 _rsv[4];
+
+	__le16 tag;
+	__le16 len;
+
+	u8 power_ctrl_id;
+	union {
+		bool sku_enable;
+		bool ate_mode_enable;
+		bool percentage_ctrl_enable;
+		bool bf_backoff_enable;
+		u8 power_drop_level;
+	};
+	u8 band_idx;
+	u8 rsv[1];
+} __packed;
+
 enum {
+	UNI_TXPOWER_SKU_POWER_LIMIT_CTRL = 0,
+	UNI_TXPOWER_PERCENTAGE_CTRL = 1,
+	UNI_TXPOWER_PERCENTAGE_DROP_CTRL = 2,
+	UNI_TXPOWER_BACKOFF_POWER_LIMIT_CTRL = 3,
 	UNI_TXPOWER_POWER_LIMIT_TABLE_CTRL = 4,
+	UNI_TXPOWER_ATE_MODE_CTRL = 6,
 };
 
 enum {
drivers/net/wireless/mediatek/mt76/mt7996/mt7996.h +1 -0
index 29e7289c3a169..6f7a10d6659e2 100644
@@ -496,6 +496,7 @@ int mt7996_mcu_get_temperature(struct mt7996_phy *phy);
 int mt7996_mcu_set_thermal_throttling(struct mt7996_phy *phy, u8 state);
 int mt7996_mcu_set_thermal_protect(struct mt7996_phy *phy, bool enable);
 int mt7996_mcu_set_txpower_sku(struct mt7996_phy *phy);
+int mt7996_mcu_set_tx_power_ctrl(struct mt7996_phy *phy, u8 power_ctrl_id, u8 data);
 int mt7996_mcu_rdd_cmd(struct mt7996_dev *dev, int cmd, u8 index,
 		       u8 rx_sel, u8 val);
 int mt7996_mcu_rdd_background_enable(struct mt7996_phy *phy,
Signature · 1 line
2.53.0
author maintainer
#470 lore raw

PATCH 466/816 wifi: mt76: mt7996: fix the hw-queues debugfs queue requests

In reply to Greg Kroah-Hartman

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

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

From: Felix Fietkau <[email protected]>

[ Upstream commit ef28298ab88bd7ba8d805fb8dfaaacd9246d5fbf ]

The hw-queues debugfs file builds its own queue requests, and these do not match the register map of the MediaTek vendor driver:

- The port ID goes to bits 11:10 of the PLE queue control register, but the field is at bits 17:16. Bits 11:10 are part of the WLAN index, so each request reads port 0 and, for a station, the WLAN index with bit 11 set.
- The head and tail frame IDs, the packet count and the page counters are read as 12-bit fields, but they have 13 bits.
- The PSE queues are read from the PLE empty and queue control registers, with bit positions that do not match the PSE queue map.
- The station queues of MT7992 and MT7990 with a WLAN index from 512 to 543 are read from register 16, but these chips keep that group in the extension register at index 32.
- The file iterates the stations of the same ieee80211_hw once for each band, so it shows each station queue up to three times.
- mt7996_hw_queue_read() takes the private data of the file as a struct mt7996_phy, but it is a struct mt7996_dev. The dev member of the phy then aliases mt76.phy.dev of the device, which points back to the device, so the file works by chance.

A queue request also writes the queue control register 0 and then reads the result from the queue control registers 2 and 3, without a lock. When the global and a per-station hw-queues file are read at the same time, one reader can get the result of the request of the other.

Describe the PLE and PSE queues in tables with the field layout of the vendor register map, and send all queue requests through one helper, which holds a spinlock from the write of the request to the read of its result. A spinlock is needed because the station requests are sent from ieee80211_iterate_stations_atomic(). Iterate the stations once.

Fixes 98686cd21624 ("wifi: mt76: mt7996: add driver for MediaTek Wi-Fi 7 (802.11be) devices")
[ sashal: Adapted the station and hw-queues handlers to the pre-MLO code: no link loop, inputs from msta->vif and msta->wcid, and the per-phy private data and single-hw iteration kept. ]
---
 .../wireless/mediatek/mt76/mt7996/debugfs.c   | 298 ++++++++++++------
 .../net/wireless/mediatek/mt76/mt7996/regs.h  |  28 ++
 2 files changed, 224 insertions(+), 102 deletions(-)
drivers/net/wireless/mediatek/mt76/mt7996/debugfs.c +196 -102
index 62c03d088925c..c627a86a5d517 100644
@@ -13,13 +13,6 @@
 
 /** global debugfs **/
 
-struct hw_queue_map {
-	const char *name;
-	u8 index;
-	u8 pid;
-	u8 qid;
-};
-
 static int
 mt7996_implicit_txbf_set(void *data, u64 val)
 {
@@ -566,35 +559,176 @@ mt7996_tx_stats_show(struct seq_file *file, void *data)
 
 DEFINE_SHOW_ATTRIBUTE(mt7996_tx_stats);
 
+enum {
+	MT_QUEUE_PORT_HIF,
+	MT_QUEUE_PORT_CPU,
+	MT_QUEUE_PORT_LMAC,
+	MT_QUEUE_PORT_PLE_CTRL,
+};
+
+struct mt7996_hw_queue {
+	const char *name;
+	u8 pid;
+	u8 qid;
+	u8 tgid;
+};
+
+#define MT7996_HW_QUEUE(_name, _pid, _qid, _tgid)	\
+	{ .name = _name, .pid = MT_QUEUE_PORT_##_pid, .qid = _qid, .tgid = _tgid }
+
+static const struct mt7996_hw_queue mt7996_ple_queues[32] = {
+	[0] = MT7996_HW_QUEUE("CPU Q0", CPU, 0, 0),
+	[1] = MT7996_HW_QUEUE("CPU Q1", CPU, 1, 0),
+	[2] = MT7996_HW_QUEUE("CPU Q2", CPU, 2, 0),
+	[3] = MT7996_HW_QUEUE("CPU Q3", CPU, 3, 0),
+	[4] = MT7996_HW_QUEUE("ALTX Q0", LMAC, 0x10, 0),
+	[5] = MT7996_HW_QUEUE("BMC Q0", LMAC, 0x11, 0),
+	[6] = MT7996_HW_QUEUE("BCN Q0", LMAC, 0x12, 0),
+	[7] = MT7996_HW_QUEUE("PSMP Q0", LMAC, 0x13, 0),
+	[8] = MT7996_HW_QUEUE("ALTX Q1", LMAC, 0x10, 1),
+	[9] = MT7996_HW_QUEUE("BMC Q1", LMAC, 0x11, 1),
+	[10] = MT7996_HW_QUEUE("BCN Q1", LMAC, 0x12, 1),
+	[11] = MT7996_HW_QUEUE("PSMP Q1", LMAC, 0x13, 1),
+	[12] = MT7996_HW_QUEUE("ALTX Q2", LMAC, 0x1c, 2),
+	[13] = MT7996_HW_QUEUE("BMC Q2", LMAC, 0x1d, 2),
+	[14] = MT7996_HW_QUEUE("BCN Q2", LMAC, 0x1e, 2),
+	[15] = MT7996_HW_QUEUE("PSMP Q2", LMAC, 0x1f, 2),
+	[16] = MT7996_HW_QUEUE("NAF Q", LMAC, 0x18, 0),
+	[17] = MT7996_HW_QUEUE("NBCN Q", LMAC, 0x19, 0),
+	[20] = MT7996_HW_QUEUE("FIXFID Q", LMAC, 0x1a, 0),
+	[28] = MT7996_HW_QUEUE("RLS4 Q", PLE_CTRL, 0x7c, 0),
+	[29] = MT7996_HW_QUEUE("RLS3 Q", PLE_CTRL, 0x7d, 0),
+	[30] = MT7996_HW_QUEUE("RLS2 Q", PLE_CTRL, 0x7e, 0),
+	[31] = MT7996_HW_QUEUE("RLS Q", PLE_CTRL, 0x7f, 0),
+};
+
+static const struct mt7996_hw_queue mt7996_pse_queues[32] = {
+	[0] = MT7996_HW_QUEUE("CPU Q0", CPU, 0, 0),
+	[1] = MT7996_HW_QUEUE("CPU Q1", CPU, 1, 0),
+	[2] = MT7996_HW_QUEUE("CPU Q2", CPU, 2, 0),
+	[3] = MT7996_HW_QUEUE("CPU Q3", CPU, 3, 0),
+	[16] = MT7996_HW_QUEUE("LMAC Q", LMAC, 0, 0),
+	[17] = MT7996_HW_QUEUE("MDP TX Q0", LMAC, 1, 0),
+	[18] = MT7996_HW_QUEUE("MDP RX Q", LMAC, 2, 0),
+	[19] = MT7996_HW_QUEUE("SEC TX Q0", LMAC, 3, 0),
+	[20] = MT7996_HW_QUEUE("SEC RX Q", LMAC, 4, 0),
+	[21] = MT7996_HW_QUEUE("SFD PARK Q", LMAC, 5, 0),
+	[22] = MT7996_HW_QUEUE("MDP TXIOC Q0", LMAC, 6, 0),
+	[23] = MT7996_HW_QUEUE("MDP RXIOC Q0", LMAC, 7, 0),
+	[24] = MT7996_HW_QUEUE("MDP TX Q1", LMAC, 0x11, 0),
+	[25] = MT7996_HW_QUEUE("SEC TX Q1", LMAC, 0x13, 0),
+	[26] = MT7996_HW_QUEUE("MDP TXIOC Q1", LMAC, 0x16, 0),
+	[27] = MT7996_HW_QUEUE("MDP RXIOC Q1", LMAC, 0x17, 0),
+	[28] = MT7996_HW_QUEUE("CPU Q4", CPU, 4, 0),
+	[31] = MT7996_HW_QUEUE("RLS Q", PLE_CTRL, 0x1f, 0),
+};
+
+static const struct mt7996_hw_queue mt7996_pse_queues_1[32] = {
+	[0] = MT7996_HW_QUEUE("MDP TDPIOC Q0", LMAC, 0x08, 0),
+	[1] = MT7996_HW_QUEUE("MDP RDPIOC Q0", LMAC, 0x09, 0),
+	[2] = MT7996_HW_QUEUE("MDP TDPIOC Q1", LMAC, 0x18, 0),
+	[3] = MT7996_HW_QUEUE("MDP RDPIOC Q1", LMAC, 0x19, 0),
+	[4] = MT7996_HW_QUEUE("MDP TDPIOC Q2", LMAC, 0x28, 0),
+	[5] = MT7996_HW_QUEUE("MDP RDPIOC Q2", LMAC, 0x29, 0),
+	[7] = MT7996_HW_QUEUE("MDP RDPIOC Q3", LMAC, 0x39, 0),
+	[8] = MT7996_HW_QUEUE("MDP TX Q2", LMAC, 0x21, 0),
+	[9] = MT7996_HW_QUEUE("SEC TX Q2", LMAC, 0x23, 0),
+	[10] = MT7996_HW_QUEUE("MDP TXIOC Q2", LMAC, 0x26, 0),
+	[11] = MT7996_HW_QUEUE("MDP RXIOC Q2", LMAC, 0x27, 0),
+	[15] = MT7996_HW_QUEUE("MDP RXIOC Q3", LMAC, 0x37, 0),
+	[16] = MT7996_HW_QUEUE("HIF Q0", HIF, 0, 0),
+	[17] = MT7996_HW_QUEUE("HIF Q1", HIF, 1, 0),
+	[18] = MT7996_HW_QUEUE("HIF Q2", HIF, 2, 0),
+	[19] = MT7996_HW_QUEUE("HIF Q3", HIF, 3, 0),
+	[20] = MT7996_HW_QUEUE("HIF Q4", HIF, 4, 0),
+	[21] = MT7996_HW_QUEUE("HIF Q5", HIF, 5, 0),
+	[22] = MT7996_HW_QUEUE("HIF Q6", HIF, 6, 0),
+	[23] = MT7996_HW_QUEUE("HIF Q7", HIF, 7, 0),
+	[24] = MT7996_HW_QUEUE("HIF Q8", HIF, 8, 0),
+	[25] = MT7996_HW_QUEUE("HIF Q9", HIF, 9, 0),
+	[26] = MT7996_HW_QUEUE("HIF Q10", HIF, 10, 0),
+	[27] = MT7996_HW_QUEUE("HIF Q11", HIF, 11, 0),
+	[28] = MT7996_HW_QUEUE("HIF Q12", HIF, 12, 0),
+	[29] = MT7996_HW_QUEUE("HIF Q13", HIF, 13, 0),
+};
+
 static void
-mt7996_hw_queue_read(struct seq_file *s, u32 size,
-		     const struct hw_queue_map *map)
+mt7996_fl_queue_show(struct seq_file *s, struct mt7996_dev *dev, bool pse,
+		     const struct mt7996_hw_queue *q, u16 wlan_idx)
 {
-	struct mt7996_phy *phy = s->private;
-	struct mt7996_dev *dev = phy->dev;
-	u32 i, val;
+	static DEFINE_SPINLOCK(lock);
+	u32 val, fid, num;
+
+	val = MT_FL_Q0_CTRL_EXECUTE |
+	      u32_encode_bits(q->qid, MT_FL_Q0_CTRL_QID) |
+	      u32_encode_bits(q->tgid, MT_FL_Q0_CTRL_TGID) |
+	      u32_encode_bits(q->pid, MT_FL_Q0_CTRL_PID) |
+	      u32_encode_bits(wlan_idx, MT_FL_Q0_CTRL_WLAN_IDX);
+
+	spin_lock(&lock);
+	mt76_wr(dev, pse ? MT_PSE_FL_Q0_CTRL : MT_FL_Q0_CTRL, val);
+	fid = mt76_rr(dev, pse ? MT_PSE_FL_Q2_CTRL : MT_FL_Q2_CTRL);
+	num = mt76_rr(dev, pse ? MT_PSE_FL_Q3_CTRL : MT_FL_Q3_CTRL);
+	spin_unlock(&lock);
+
+	seq_printf(s, "tail/head fid 0x%04x/0x%04x, packets %u",
+		   u32_get_bits(fid, MT_FL_Q2_CTRL_TAIL_FID),
+		   u32_get_bits(fid, MT_FL_Q2_CTRL_HEAD_FID),
+		   u32_get_bits(num, MT_FL_Q3_CTRL_PKT_NUM));
+}
 
-	val = mt76_rr(dev, MT_FL_Q_EMPTY);
-	for (i = 0; i < size; i++) {
-		u32 ctrl, head, tail, queued;
+static void
+mt7996_fl_queues_show(struct seq_file *s, struct mt7996_dev *dev, bool pse,
+		      const struct mt7996_hw_queue *queues, unsigned long empty)
+{
+	unsigned int i;
 
-		if (val & BIT(map[i].index))
+	for_each_clear_bit(i, &empty, 32) {
+		if (!queues[i].name)
 			continue;
 
-		ctrl = BIT(31) | (map[i].pid << 10) | ((u32)map[i].qid << 24);
-		mt76_wr(dev, MT_FL_Q0_CTRL, ctrl);
+		seq_printf(s, "\t%s: ", queues[i].name);
+		mt7996_fl_queue_show(s, dev, pse, &queues[i], 0);
+		seq_puts(s, "\n");
+	}
+}
 
-		head = mt76_get_field(dev, MT_FL_Q2_CTRL,
-				      GENMASK(11, 0));
-		tail = mt76_get_field(dev, MT_FL_Q2_CTRL,
-				      GENMASK(27, 16));
-		queued = mt76_get_field(dev, MT_FL_Q3_CTRL,
-					GENMASK(11, 0));
+static void
+mt7996_freepg_show(struct seq_file *s, u32 cnt, u32 head_tail)
+{
+	seq_printf(s, "\tfree pages 0x%04x, free for all 0x%04x, head/tail 0x%04x/0x%04x\n",
+		   u32_get_bits(cnt, MT_FREEPG_CNT_FREE),
+		   u32_get_bits(cnt, MT_FREEPG_CNT_FFA),
+		   u32_get_bits(head_tail, MT_FREEPG_HEAD_TAIL_HEAD),
+		   u32_get_bits(head_tail, MT_FREEPG_HEAD_TAIL_TAIL));
+}
 
-		seq_printf(s, "\t%s: ", map[i].name);
-		seq_printf(s, "queued:0x%03x head:0x%03x tail:0x%03x\n",
-			   queued, head, tail);
-	}
+static void
+mt7996_pg_group_show(struct seq_file *s, const char *name, u32 group, u32 info)
+{
+	seq_printf(s, "\t%s group: max/min quota 0x%04x/0x%04x, used/reserved 0x%04x/0x%04x\n",
+		   name, u32_get_bits(group, MT_PG_GROUP_MAX_QUOTA),
+		   u32_get_bits(group, MT_PG_GROUP_MIN_QUOTA),
+		   u32_get_bits(info, MT_PG_INFO_SRC_CNT),
+		   u32_get_bits(info, MT_PG_INFO_RSV_CNT));
+}
+
+static unsigned int
+mt7996_ple_sta_cr_num(struct mt7996_dev *dev)
+{
+	return is_mt7996(&dev->mt76) ? 34 : 17;
+}
+
+static unsigned int
+mt7996_ple_sta_cr(struct mt7996_dev *dev, unsigned int n)
+{
+	/* MT7992 and MT7990 keep the last station group in the
+	 * extension register that follows the first 32 groups
+	 */
+	if (!is_mt7996(&dev->mt76) && n == mt7996_ple_sta_cr_num(dev) - 1)
+		return 32;
+
+	return n;
 }
 
 static void
@@ -603,92 +737,52 @@ mt7996_sta_hw_queue_read(void *data, struct ieee80211_sta *sta)
 	struct mt7996_sta *msta = (struct mt7996_sta *)sta->drv_priv;
 	struct mt7996_dev *dev = msta->vif->phy->dev;
 	struct seq_file *s = data;
+	unsigned int cr;
+	u16 wlan_idx;
 	u8 ac;
 
-	for (ac = 0; ac < 4; ac++) {
-		u32 qlen, ctrl, val;
-		u32 idx = msta->wcid.idx >> 5;
-		u8 offs = msta->wcid.idx & GENMASK(4, 0);
-
-		ctrl = BIT(31) | BIT(11) | (ac << 24);
-		val = mt76_rr(dev, MT_PLE_AC_QEMPTY(ac, idx));
+	wlan_idx = msta->wcid.idx;
+	cr = mt7996_ple_sta_cr(dev, wlan_idx / 32);
+	for (ac = 0; ac < IEEE80211_NUM_ACS; ac++) {
+		struct mt7996_hw_queue q = {
+			.pid = MT_QUEUE_PORT_LMAC,
+			.qid = ac,
+		};
 
-		if (val & BIT(offs))
+		if (mt76_rr(dev, MT_PLE_AC_QEMPTY(ac, cr)) &
+		    BIT(wlan_idx % 32))
 			continue;
 
-		mt76_wr(dev, MT_FL_Q0_CTRL, ctrl | msta->wcid.idx);
-		qlen = mt76_get_field(dev, MT_FL_Q3_CTRL,
-				      GENMASK(11, 0));
-		seq_printf(s, "\tSTA %pM wcid %d: AC%d%d queued:%d\n",
-			   sta->addr, msta->wcid.idx,
-			   msta->vif->mt76.wmm_idx, ac, qlen);
+		seq_printf(s, "\tSTA %pM wcid %u AC%u%u: ", sta->addr,
+			   wlan_idx, msta->vif->mt76.wmm_idx, ac);
+		mt7996_fl_queue_show(s, dev, false, &q, wlan_idx);
+		seq_puts(s, "\n");
 	}
 }
 
 static int
-mt7996_hw_queues_show(struct seq_file *file, void *data)
+mt7996_hw_queues_show(struct seq_file *s, void *data)
 {
-	struct mt7996_phy *phy = file->private;
+	struct mt7996_phy *phy = s->private;
 	struct mt7996_dev *dev = phy->dev;
-	static const struct hw_queue_map ple_queue_map[] = {
-		{ "CPU_Q0",  0,  1, MT_CTX0	      },
-		{ "CPU_Q1",  1,  1, MT_CTX0 + 1	      },
-		{ "CPU_Q2",  2,  1, MT_CTX0 + 2	      },
-		{ "CPU_Q3",  3,  1, MT_CTX0 + 3	      },
-		{ "ALTX_Q0", 8,  2, MT_LMAC_ALTX0     },
-		{ "BMC_Q0",  9,  2, MT_LMAC_BMC0      },
-		{ "BCN_Q0",  10, 2, MT_LMAC_BCN0      },
-		{ "PSMP_Q0", 11, 2, MT_LMAC_PSMP0     },
-		{ "ALTX_Q1", 12, 2, MT_LMAC_ALTX0 + 4 },
-		{ "BMC_Q1",  13, 2, MT_LMAC_BMC0  + 4 },
-		{ "BCN_Q1",  14, 2, MT_LMAC_BCN0  + 4 },
-		{ "PSMP_Q1", 15, 2, MT_LMAC_PSMP0 + 4 },
-	};
-	static const struct hw_queue_map pse_queue_map[] = {
-		{ "CPU Q0",  0,  1, MT_CTX0	      },
-		{ "CPU Q1",  1,  1, MT_CTX0 + 1	      },
-		{ "CPU Q2",  2,  1, MT_CTX0 + 2	      },
-		{ "CPU Q3",  3,  1, MT_CTX0 + 3	      },
-		{ "HIF_Q0",  8,  0, MT_HIF0	      },
-		{ "HIF_Q1",  9,  0, MT_HIF0 + 1	      },
-		{ "HIF_Q2",  10, 0, MT_HIF0 + 2	      },
-		{ "HIF_Q3",  11, 0, MT_HIF0 + 3	      },
-		{ "HIF_Q4",  12, 0, MT_HIF0 + 4	      },
-		{ "HIF_Q5",  13, 0, MT_HIF0 + 5	      },
-		{ "LMAC_Q",  16, 2, 0		      },
-		{ "MDP_TXQ", 17, 2, 1		      },
-		{ "MDP_RXQ", 18, 2, 2		      },
-		{ "SEC_TXQ", 19, 2, 3		      },
-		{ "SEC_RXQ", 20, 2, 4		      },
-	};
-	u32 val, head, tail;
-
-	/* ple queue */
-	val = mt76_rr(dev, MT_PLE_FREEPG_CNT);
-	head = mt76_get_field(dev, MT_PLE_FREEPG_HEAD_TAIL, GENMASK(11, 0));
-	tail = mt76_get_field(dev, MT_PLE_FREEPG_HEAD_TAIL, GENMASK(27, 16));
-	seq_puts(file, "PLE page info:\n");
-	seq_printf(file,
-		   "\tTotal free page: 0x%08x head: 0x%03x tail: 0x%03x\n",
-		   val, head, tail);
-
-	val = mt76_rr(dev, MT_PLE_PG_HIF_GROUP);
-	head = mt76_get_field(dev, MT_PLE_HIF_PG_INFO, GENMASK(11, 0));
-	tail = mt76_get_field(dev, MT_PLE_HIF_PG_INFO, GENMASK(27, 16));
-	seq_printf(file, "\tHIF free page: 0x%03x res: 0x%03x used: 0x%03x\n",
-		   val, head, tail);
-
-	seq_puts(file, "PLE non-empty queue info:\n");
-	mt7996_hw_queue_read(file, ARRAY_SIZE(ple_queue_map),
-			     &ple_queue_map[0]);
-
-	/* iterate per-sta ple queue */
+
+	seq_puts(s, "PLE page info:\n");
+	mt7996_freepg_show(s, mt76_rr(dev, MT_PLE_FREEPG_CNT),
+			   mt76_rr(dev, MT_PLE_FREEPG_HEAD_TAIL));
+	mt7996_pg_group_show(s, "HIF", mt76_rr(dev, MT_PLE_PG_HIF_GROUP),
+			     mt76_rr(dev, MT_PLE_HIF_PG_INFO));
+
+	seq_puts(s, "PLE non-empty queue info:\n");
+	mt7996_fl_queues_show(s, dev, false, mt7996_ple_queues,
+			      mt76_rr(dev, MT_FL_Q_EMPTY));
 	ieee80211_iterate_stations_atomic(phy->mt76->hw,
-					  mt7996_sta_hw_queue_read, file);
-	/* pse queue */
-	seq_puts(file, "PSE non-empty queue info:\n");
-	mt7996_hw_queue_read(file, ARRAY_SIZE(pse_queue_map),
-			     &pse_queue_map[0]);
+					  mt7996_sta_hw_queue_read, s);
+
+	seq_puts(s, "PSE non-empty queue info:\n");
+	mt7996_fl_queues_show(s, dev, true, mt7996_pse_queues,
+			      mt76_rr(dev, MT_PSE_QUEUE_EMPTY));
+	mt7996_fl_queues_show(s, dev, true, mt7996_pse_queues_1,
+			      mt76_rr(dev, MT_PSE_QUEUE_EMPTY_1));
 
 	return 0;
 }
drivers/net/wireless/mediatek/mt76/mt7996/regs.h +28 -0
index 5e0342dce630c..88dcb83ceb11e 100644
@@ -121,6 +121,15 @@ enum offs_rev {
 #define MT_FL_Q2_CTRL				MT_PLE(0x3e8)
 #define MT_FL_Q3_CTRL				MT_PLE(0x3ec)
 
+#define MT_FL_Q0_CTRL_EXECUTE			BIT(31)
+#define MT_FL_Q0_CTRL_QID			GENMASK(30, 24)
+#define MT_FL_Q0_CTRL_TGID			GENMASK(21, 20)
+#define MT_FL_Q0_CTRL_PID			GENMASK(17, 16)
+#define MT_FL_Q0_CTRL_WLAN_IDX			GENMASK(11, 0)
+#define MT_FL_Q2_CTRL_TAIL_FID			GENMASK(28, 16)
+#define MT_FL_Q2_CTRL_HEAD_FID			GENMASK(12, 0)
+#define MT_FL_Q3_CTRL_PKT_NUM			GENMASK(12, 0)
+
 #define MT_PLE_FREEPG_CNT			MT_PLE(0x3a0)
 #define MT_PLE_FREEPG_HEAD_TAIL			MT_PLE(0x3a4)
 #define MT_PLE_PG_HIF_GROUP			MT_PLE(0x00c)
@@ -129,6 +138,25 @@ enum offs_rev {
 #define MT_PLE_AC_QEMPTY(ac, n)			MT_PLE(0x600 + 0x100 * (ac) + ((n) << 2))
 #define MT_PLE_AMSDU_PACK_MSDU_CNT(n)		MT_PLE(0x10e0 + ((n) << 2))
 
+#define MT_FREEPG_CNT_FFA			GENMASK(28, 16)
+#define MT_FREEPG_CNT_FREE			GENMASK(12, 0)
+#define MT_FREEPG_HEAD_TAIL_TAIL		GENMASK(28, 16)
+#define MT_FREEPG_HEAD_TAIL_HEAD		GENMASK(12, 0)
+#define MT_PG_GROUP_MAX_QUOTA			GENMASK(28, 16)
+#define MT_PG_GROUP_MIN_QUOTA			GENMASK(12, 0)
+#define MT_PG_INFO_SRC_CNT			GENMASK(28, 16)
+#define MT_PG_INFO_RSV_CNT			GENMASK(12, 0)
+
+/* PSE */
+#define MT_PSE_BASE				0x820c8000
+#define MT_PSE(ofs)				(MT_PSE_BASE + (ofs))
+
+#define MT_PSE_QUEUE_EMPTY			MT_PSE(0x0b0)
+#define MT_PSE_QUEUE_EMPTY_1			MT_PSE(0x0bc)
+#define MT_PSE_FL_Q0_CTRL			MT_PSE(0x1b0)
+#define MT_PSE_FL_Q2_CTRL			MT_PSE(0x1b8)
+#define MT_PSE_FL_Q3_CTRL			MT_PSE(0x1bc)
+
 /* WF MDP TOP */
 #define MT_MDP_BASE				0x820cc000
 #define MT_MDP(ofs)				(MT_MDP_BASE + (ofs))
Signature · 1 line
2.53.0
author maintainer
#471 lore raw

PATCH 467/816 wifi: mt76: mt7921: fix of_node reference leaks in regd update

In reply to Greg Kroah-Hartman

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

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

From: Felix Fietkau <[email protected]>

[ Upstream commit 2f209a8dca88507bc094de370e582adefc55723e ]

mt7921_regd_channel_update() and __mt7921_mcu_set_clc() never release the nodes returned by mt76_find_power_limits_node(), of_get_child_by_name() and mt76_find_channel_node(). Each regulatory domain change and each CLC update on a device with DT power limits leaks these references.

Release every node after use. This relies on mt76_find_power_limits_node() also returning a reference for the fallback node, which it does since commit 3a62c9f7ec3d ("wifi: mt76:
Fix of_node reference leak in mt76_get_rate_power_limits()").

Fixes 09382d8f8641 ("wifi: mt76: mt7921: update the channel usage when the regd domain changed")
[ sashal: Moved the mt7921_regd_channel_update() hunks from regd.c (absent here) into init.c, and omitted the 5GHz !sband goto hunk because init.c has no such check. ]
---
 .../net/wireless/mediatek/mt76/mt7921/init.c  | 26 ++++++++++++++++---
 .../net/wireless/mediatek/mt76/mt7921/mcu.c   |  7 ++++-
 2 files changed, 29 insertions(+), 4 deletions(-)
drivers/net/wireless/mediatek/mt76/mt7921/init.c +23 -3
index 276dfb9c26e0d..016ad2c284166 100644
@@ -60,6 +60,21 @@ static int mt7921_thermal_init(struct mt792x_phy *phy)
 	return PTR_ERR_OR_ZERO(hwmon);
 }
 
+static bool
+mt7921_regd_dt_has_channel(struct device_node *band_np,
+			   struct ieee80211_channel *ch)
+{
+	struct device_node *chan_np;
+
+	if (!band_np)
+		return false;
+
+	chan_np = mt76_find_channel_node(band_np, ch);
+	of_node_put(chan_np);
+
+	return !!chan_np;
+}
+
 static void
 mt7921_regd_channel_update(struct wiphy *wiphy, struct mt792x_dev *dev)
 {
@@ -79,7 +94,7 @@ mt7921_regd_channel_update(struct wiphy *wiphy, struct mt792x_dev *dev)
 		ch = &sband->channels[i];
 		cfreq = ch->center_freq;
 
-		if (np && (!band_np || !mt76_find_channel_node(band_np, ch))) {
+		if (np && !mt7921_regd_dt_has_channel(band_np, ch)) {
 			ch->flags |= IEEE80211_CHAN_DISABLED;
 			continue;
 		}
@@ -88,17 +103,18 @@ mt7921_regd_channel_update(struct wiphy *wiphy, struct mt792x_dev *dev)
 		if (IS_UNII_INVALID(0, 5845, 5925))
 			ch->flags |= IEEE80211_CHAN_DISABLED;
 	}
+	of_node_put(band_np);
 
 	sband = wiphy->bands[NL80211_BAND_6GHZ];
 	if (!sband)
-		return;
+		goto out;
 
 	band_np = np ? of_get_child_by_name(np, "txpower-6g") : NULL;
 	for (i = 0; i < sband->n_channels; i++) {
 		ch = &sband->channels[i];
 		cfreq = ch->center_freq;
 
-		if (np && (!band_np || !mt76_find_channel_node(band_np, ch))) {
+		if (np && !mt7921_regd_dt_has_channel(band_np, ch)) {
 			ch->flags |= IEEE80211_CHAN_DISABLED;
 			continue;
 		}
@@ -110,6 +126,10 @@ mt7921_regd_channel_update(struct wiphy *wiphy, struct mt792x_dev *dev)
 		    IS_UNII_INVALID(4, 6875, 7125))
 			ch->flags |= IEEE80211_CHAN_DISABLED;
 	}
+	of_node_put(band_np);
+
+out:
+	of_node_put(np);
 }
 
 void mt7921_regd_update(struct mt792x_dev *dev)
drivers/net/wireless/mediatek/mt76/mt7921/mcu.c +6 -1
index e533f1a3e0cba..0e547a5d020c1 100644
@@ -3,6 +3,7 @@
 
 #include <linux/fs.h>
 #include <linux/firmware.h>
+#include <linux/of.h>
 #include "mt7921.h"
 #include "mcu.h"
 #include "../mt76_connac2_mac.h"
@@ -1352,6 +1353,7 @@ int __mt7921_mcu_set_clc(struct mt792x_dev *dev, u8 *alpha2,
 		.acpi_conf = mt792x_acpi_get_flags(&dev->phy),
 		.mtcl_conf = mt792x_acpi_get_mtcl_conf(&dev->phy, alpha2),
 	};
+	struct device_node *np;
 	int ret, valid_cnt = 0;
 	u32 buf_len = 0;
 	u8 *pos;
@@ -1361,8 +1363,11 @@ int __mt7921_mcu_set_clc(struct mt792x_dev *dev, u8 *alpha2,
 
 	if (dev->phy.chip_cap & MT792x_CHIP_CAP_CLC_EVT_EN)
 		req.cap |= CLC_CAP_EVT_EN;
-	if (mt76_find_power_limits_node(&dev->mt76))
+
+	np = mt76_find_power_limits_node(&dev->mt76);
+	if (np)
 		req.cap |= CLC_CAP_DTS_EN;
+	of_node_put(np);
 
 	buf_len = le32_to_cpu(clc->len) - sizeof(*clc);
 	pos = clc->data;
Signature · 1 line
2.53.0
author maintainer
#472 lore raw

PATCH 468/816 drm/amd/display: declare amdgpu_dm_atomic_state_template as an event class

In reply to Greg Kroah-Hartman

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

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

From: Melissa Wen <[email protected]>

[ Upstream commit 6c4f8c5cc00326f6c709bff0d640d504c90862ca ]

Don't create an amdgpu_dm_atomic_state_template event since this is just a template. Declare the template as an event class that will be used by actual event tracers.

Fixes e8a982355f96 ("drm/amd/display: Add tracepoint for amdgpu_dm")
[ sashal: Replaced struct drm_atomic_commit with the older struct drm_atomic_state in the TP_PROTO and the state field of the event class, because the type has not been renamed in this tree. ]
---
 .../amd/display/amdgpu_dm/amdgpu_dm_trace.h   | 56 +++++++++----------
 1 file changed, 26 insertions(+), 30 deletions(-)
drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_trace.h +26 -30
index 113b04678dd37..2f97613a647fb 100644
@@ -310,36 +310,32 @@ DEFINE_EVENT(amdgpu_dm_plane_state_template, amdgpu_dm_atomic_update_cursor,
 	     TP_PROTO(const struct drm_plane_state *state),
 	     TP_ARGS(state));
 
-TRACE_EVENT(amdgpu_dm_atomic_state_template,
-	    TP_PROTO(const struct drm_atomic_state *state),
-	    TP_ARGS(state),
-
-	    TP_STRUCT__entry(
-			     __field(const struct drm_atomic_state *, state)
-			     __field(bool, allow_modeset)
-			     __field(bool, legacy_cursor_update)
-			     __field(bool, async_update)
-			     __field(bool, duplicated)
-			     __field(int, num_connector)
-			     __field(int, num_private_objs)
-	    ),
-
-	    TP_fast_assign(
-			   __entry->state = state;
-			   __entry->allow_modeset = state->allow_modeset;
-			   __entry->legacy_cursor_update = state->legacy_cursor_update;
-			   __entry->async_update = state->async_update;
-			   __entry->duplicated = state->duplicated;
-			   __entry->num_connector = state->num_connector;
-			   __entry->num_private_objs = state->num_private_objs;
-	    ),
-
-	    TP_printk("state=%p allow_modeset=%d legacy_cursor_update=%d "
-		      "async_update=%d duplicated=%d num_connector=%d "
-		      "num_private_objs=%d",
-		      __entry->state, __entry->allow_modeset, __entry->legacy_cursor_update,
-		      __entry->async_update, __entry->duplicated, __entry->num_connector,
-		      __entry->num_private_objs)
+DECLARE_EVENT_CLASS(amdgpu_dm_atomic_state_template,
+		    TP_PROTO(const struct drm_atomic_state *state),
+		    TP_ARGS(state),
+		    TP_STRUCT__entry(__field(const struct drm_atomic_state *, state)
+				     __field(bool, allow_modeset)
+				     __field(bool, legacy_cursor_update)
+				     __field(bool, async_update)
+				     __field(bool, duplicated)
+				     __field(int, num_connector)
+				     __field(int, num_private_objs)
+		    ),
+		    TP_fast_assign(__entry->state = state;
+				   __entry->allow_modeset = state->allow_modeset;
+				   __entry->legacy_cursor_update = state->legacy_cursor_update;
+				   __entry->async_update = state->async_update;
+				   __entry->duplicated = state->duplicated;
+				   __entry->num_connector = state->num_connector;
+				   __entry->num_private_objs = state->num_private_objs;
+		    ),
+		    TP_printk("state=%p allow_modeset=%d legacy_cursor_update=%d "
+			      "async_update=%d duplicated=%d num_connector=%d "
+			      "num_private_objs=%d",
+			      __entry->state, __entry->allow_modeset,
+			      __entry->legacy_cursor_update, __entry->async_update,
+			      __entry->duplicated, __entry->num_connector,
+			      __entry->num_private_objs)
 );
 
 DEFINE_EVENT(amdgpu_dm_atomic_state_template, amdgpu_dm_atomic_commit_tail_begin,
Signature · 1 line
2.53.0
author maintainer
#473 lore raw

PATCH 469/816 fs/ntfs3: check return values in indx_delete_entry()

In reply to Greg Kroah-Hartman

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

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

From: Dmitry Morgun <[email protected]>

[ Upstream commit 131f7d7abf0f10edc6ea6b032f8a3908bdb13ce8 ]

When the index tree collapses down to an empty root, indx_delete_entry() calls attr_set_size() and ni_remove_attr() for both ATTR_ALLOC and ATTR_BITMAP, but their return values are overwritten by the following call without being checked.

In most other call sites of these functions the return value is checked, so add the same checks here in case an error at this point is meaningful.

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

Fixes 82cae269cfa9 ("fs/ntfs3: Add initialization of super block")
[ sashal: adjusted the two attr_set_size() calls to pass an extra trailing NULL argument to match the older function signature. ]
---
 fs/ntfs3/index.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
fs/ntfs3/index.c +10 -0
index 97cbe176a83e5..88a5f336d9040 100644
@@ -2691,18 +2691,28 @@ int indx_delete_entry(struct ntfs_index *indx, struct ntfs_inode *ni,
 
 		err = attr_set_size(ni, ATTR_ALLOC, in->name, in->name_len,
 				    &indx->alloc_run, 0, NULL, false, NULL);
+		if (err)
+			goto out;
+
 		if (in->name == I30_NAME)
 			i_size_write(&ni->vfs_inode, 0);
 
 		err = ni_remove_attr(ni, ATTR_ALLOC, in->name, in->name_len,
 				     false, NULL);
 		run_close(&indx->alloc_run);
+		if (err)
+			goto out;
 
 		err = attr_set_size(ni, ATTR_BITMAP, in->name, in->name_len,
 				    &indx->bitmap_run, 0, NULL, false, NULL);
+		if (err)
+			goto out;
+
 		err = ni_remove_attr(ni, ATTR_BITMAP, in->name, in->name_len,
 				     false, NULL);
 		run_close(&indx->bitmap_run);
+		if (err)
+			goto out;
 
 		root = indx_get_root(indx, ni, &attr, &mi);
 		if (!root) {
Signature · 1 line
2.53.0
author maintainer
#474 lore raw

PATCH 470/816 net: stmmac: fix TX coalesce race and div-by-zero in XDP/legacy path

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Bianconi <[email protected]>

[ Upstream commit 237782c3d416b392a12642f32959e9d3c94e0c26 ]

tx_coal_frames[] is written by ethtool (stmmac_set_coalesce) and read locklessly from the TX fast path (stmmac_xmit, stmmac_tso_xmit, stmmac_xdp_xmit_zc and stmmac_xdp_xmit_xdpf), so pair every access with READ_ONCE()/WRITE_ONCE() to mark the intentional data race and read a consistent value into a local variable.

Moreover, ethtool allows disabling TX coalescing by setting tx_max_coalesced_frames to 0: guard the modulo operation in stmmac_xdp_xmit_xdpf() against a zero tx_coal_frames[queue] to avoid a division by zero.

Both issues were found by code inspection while extending the XDP TX path with multi-buff support, and neither has ever been triggered, so they are only theoretical. Tested on the Qualcomm RB3-gen2 board.

Fixes db2f2842e6f5 ("net: stmmac: add per-queue TX & RX coalesce ethtool support")
Fixes be8b38a722e6 ("net: stmmac: Add support for XDP_TX action")
[ sashal: Dropped the unused sdu_len declaration and kept local declaration blocks as they were, adding only tx_coal, because the surrounding functions differ from upstream. ]
---
 .../ethernet/stmicro/stmmac/stmmac_ethtool.c  | 11 ++---
 .../net/ethernet/stmicro/stmmac/stmmac_main.c | 41 ++++++++-----------
 2 files changed, 24 insertions(+), 28 deletions(-)
drivers/net/ethernet/stmicro/stmmac/stmmac_ethtool.c +6 -5
index 5d94de4670557..4569b950e96b2 100644
@@ -979,7 +979,8 @@ static int __stmmac_get_coalesce(struct net_device *dev,
 
 	if (queue < tx_cnt) {
 		ec->tx_coalesce_usecs = priv->tx_coal_timer[queue];
-		ec->tx_max_coalesced_frames = priv->tx_coal_frames[queue];
+		ec->tx_max_coalesced_frames =
+			READ_ONCE(priv->tx_coal_frames[queue]);
 	} else {
 		ec->tx_coalesce_usecs = 0;
 		ec->tx_max_coalesced_frames = 0;
@@ -1068,14 +1069,14 @@ static int __stmmac_set_coalesce(struct net_device *dev,
 		int i;
 
 		for (i = 0; i < tx_cnt; i++) {
-			priv->tx_coal_frames[i] =
-				ec->tx_max_coalesced_frames;
+			WRITE_ONCE(priv->tx_coal_frames[i],
+				   ec->tx_max_coalesced_frames);
 			priv->tx_coal_timer[i] =
 				ec->tx_coalesce_usecs;
 		}
 	} else if (queue < tx_cnt) {
-		priv->tx_coal_frames[queue] =
-			ec->tx_max_coalesced_frames;
+		WRITE_ONCE(priv->tx_coal_frames[queue],
+			   ec->tx_max_coalesced_frames);
 		priv->tx_coal_timer[queue] =
 			ec->tx_coalesce_usecs;
 	}
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +18 -23

110 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#475 lore raw

PATCH 471/816 ALSA: pcmtest: Fix leak at probe error

In reply to Greg Kroah-Hartman

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

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

From: Takashi Iwai <[email protected]>

[ Upstream commit d0f2ca62e89f3c666d0ec203eaa23b8d965e5443 ]

When an error happens at probe of pcmtest driver before snd_card_register() succeeds, we have to release the card explicitly, but it's not done, leading to a potential memory leak.

Also, pcmtest driver manages struct pcmtst object unnecessarily complicatedly by a dynamic allocation and release.

This patch fixes and cleans up the resource management:
- Use card's private_data allocation for struct sndpcmtst at the card creation, which is released automatically together with the card
- Since the allocation of pcmtest is gone, snd_pcmtst_create() is rather pointless, so just directly calling snd_pcmtst_new_pcm()
- Use the new auto-clean mechanism to handle the error case at probe.
- Many release handlers became superfluous and dropped

In the end we got a good amount of code reduction.

Fixes 315a3d57c64c ("ALSA: Implement the new Virtual PCM Test Driver")
[ sashal: Adjusted context in two hunks (kzalloc vs kzalloc_obj, .remove_new vs .remove), both on lines the patch deletes, so the final code matches upstream. ]
---
 sound/drivers/pcmtest.c | 66 +++++++----------------------------------
 1 file changed, 10 insertions(+), 56 deletions(-)
sound/drivers/pcmtest.c +10 -56
index 0376fe17365a8..0e325ae96371f 100644
@@ -464,20 +464,6 @@ static snd_pcm_uframes_t snd_pcmtst_pcm_pointer(struct snd_pcm_substream *substr
 	return bytes_to_frames(substream->runtime, v_iter->buf_pos);
 }
 
-static int snd_pcmtst_free(struct pcmtst *pcmtst)
-{
-	if (!pcmtst)
-		return 0;
-	kfree(pcmtst);
-	return 0;
-}
-
-// These callbacks are required, but empty - all freeing occurs in pdev_remove
-static int snd_pcmtst_dev_free(struct snd_device *device)
-{
-	return 0;
-}
-
 static void pcmtst_pdev_release(struct device *dev)
 {
 }
@@ -581,40 +567,9 @@ static int snd_pcmtst_new_pcm(struct pcmtst *pcmtst)
 	return err;
 }
 
-static int snd_pcmtst_create(struct snd_card *card, struct platform_device *pdev,
-			     struct pcmtst **r_pcmtst)
-{
-	struct pcmtst *pcmtst;
-	int err;
-	static const struct snd_device_ops ops = {
-		.dev_free = snd_pcmtst_dev_free,
-	};
-
-	pcmtst = kzalloc(sizeof(*pcmtst), GFP_KERNEL);
-	if (!pcmtst)
-		return -ENOMEM;
-	pcmtst->card = card;
-	pcmtst->pdev = pdev;
-
-	err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, pcmtst, &ops);
-	if (err < 0)
-		goto _err_free_chip;
-
-	err = snd_pcmtst_new_pcm(pcmtst);
-	if (err < 0)
-		goto _err_free_chip;
-
-	*r_pcmtst = pcmtst;
-	return 0;
-
-_err_free_chip:
-	snd_pcmtst_free(pcmtst);
-	return err;
-}
-
 static int pcmtst_probe(struct platform_device *pdev)
 {
-	struct snd_card *card;
+	struct snd_card *card __free(snd_card_free) = NULL;
 	struct pcmtst *pcmtst;
 	int err;
 
@@ -622,10 +577,16 @@ static int pcmtst_probe(struct platform_device *pdev)
 	if (err)
 		return err;
 
-	err = snd_devm_card_new(&pdev->dev, index, id, THIS_MODULE, 0, &card);
+	err = snd_devm_card_new(&pdev->dev, index, id, THIS_MODULE,
+				sizeof(*pcmtst), &card);
 	if (err < 0)
 		return err;
-	err = snd_pcmtst_create(card, pdev, &pcmtst);
+
+	pcmtst = card->private_data;
+	pcmtst->card = card;
+	pcmtst->pdev = pdev;
+
+	err = snd_pcmtst_new_pcm(pcmtst);
 	if (err < 0)
 		return err;
 
@@ -638,17 +599,11 @@ static int pcmtst_probe(struct platform_device *pdev)
 		return err;
 
 	platform_set_drvdata(pdev, pcmtst);
+	card = NULL; /* probe succeeded, don't release as error */
 
 	return 0;
 }
 
-static void pdev_remove(struct platform_device *pdev)
-{
-	struct pcmtst *pcmtst = platform_get_drvdata(pdev);
-
-	snd_pcmtst_free(pcmtst);
-}
-
 static struct platform_device pcmtst_pdev = {
 	.name =		"pcmtest",
 	.dev.release =	pcmtst_pdev_release,
@@ -656,7 +611,6 @@ static struct platform_device pcmtst_pdev = {
 
 static struct platform_driver pcmtst_pdrv = {
 	.probe =	pcmtst_probe,
-	.remove_new =	pdev_remove,
 	.driver =	{
 		.name = "pcmtest",
 	},
Signature · 1 line
2.53.0
author maintainer
#476 lore raw

PATCH 472/816 ALSA: aloop: Avoid a bad mixure of guard() and goto

In reply to Greg Kroah-Hartman

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

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

From: Takashi Iwai <[email protected]>

[ Upstream commit f7faf5d9b5668919cae84a6247f8f7b4e2c0227c ]

The rewrite of aloop driver code using guard() leaded to a mixture of guard() and some goto; although it currently works, it isn't really a good match.

For avoiding the bad match, just move the code using goto into a function and wrap it with guard().

Fixes ebd9b6c91d4e ("ALSA: aloop: Use guard() for mutex locks")
[ sashal: Kept the local kzalloc(sizeof(*dpcm), GFP_KERNEL) call in place of upstream's kzalloc_obj(*dpcm) so the hunk applies; the rest matches upstream. ]
---
 sound/drivers/aloop.c | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
sound/drivers/aloop.c +9 -2
index d7857659a7313..fa8d2877516d9 100644
@@ -1273,7 +1273,7 @@ static const struct loopback_ops loopback_snd_timer_ops = {
 	.dpcm_info = loopback_snd_timer_dpcm_info,
 };
 
-static int loopback_open(struct snd_pcm_substream *substream)
+static int __loopback_open(struct snd_pcm_substream *substream)
 {
 	struct snd_pcm_runtime *runtime = substream->runtime;
 	struct loopback *loopback = substream->private_data;
@@ -1282,7 +1282,6 @@ static int loopback_open(struct snd_pcm_substream *substream)
 	int err = 0;
 	int dev = get_cable_index(substream);
 
-	guard(mutex)(&loopback->cable_lock);
 	dpcm = kzalloc(sizeof(*dpcm), GFP_KERNEL);
 	if (!dpcm)
 		return -ENOMEM;
@@ -1373,6 +1372,14 @@ static int loopback_open(struct snd_pcm_substream *substream)
 	return err;
 }
 
+static int loopback_open(struct snd_pcm_substream *substream)
+{
+	struct loopback *loopback = substream->private_data;
+
+	guard(mutex)(&loopback->cable_lock);
+	return __loopback_open(substream);
+}
+
 static int loopback_close(struct snd_pcm_substream *substream)
 {
 	struct loopback *loopback = substream->private_data;
Signature · 1 line
2.53.0
author maintainer
#477 lore raw

PATCH 473/816 ALSA: hda: Use linked list for jack table

In reply to Greg Kroah-Hartman

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

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

From: Takashi Iwai <[email protected]>

[ Upstream commit 5676e013f16ac4b616d433af24647d0ce4b067aa ]

So far we've used snd_array infrastructure for managing the hda_jack_tbl elements, but it turned out that this may lead to a UAF when a different order of destruction procedure is applied; namely, each hda_jack_tbl object creates a snd_jack object and sets the private_data pointing to the hda_jack_tbl, and private_free to release it. It looks harmless, but since snd_array may reallocate the whole table at growing, the formerly referred jack pointer may become stale.

Fortunately, currently there is no call pattern that triggers this issue, so it's only hypothetical, but we should address it in anyway.

There are several ways to address this, and at this time, we rather redesign the hda_jack_tbl allocations: instead of snd_array(), do a normal kmalloc() + linked list. There will be more kmalloc calls than the original code, but as the number of jacks are usually at most handful, it must not be a problem. This change allows us the persistent jack pointer, so no stale pointer access can happen any longer.

This also fixes another reported issue about the stale jack pointer reference in snd_hda_jack_tbl_new(), too.

Fixes 31ef22579302 ("ALSA: hda - Integrate input-jack stuff into kctl-jack")
[ sashal: Dropped the struct hda_codec_ops; context line from the forward-declaration hunk in hda_codec.h, since this tree lacks it, and kept only the added struct hda_jack_tbl;. ]
---
 include/sound/hda_codec.h       |  6 ++-
 sound/pci/hda/hda_codec.c       |  1 -
 sound/pci/hda/hda_jack.c        | 79 ++++++++++++++++++---------------
 sound/pci/hda/hda_jack.h        |  1 +
 sound/soc/sof/intel/hda-codec.c |  4 +-
 5 files changed, 51 insertions(+), 40 deletions(-)
include/sound/hda_codec.h +4 -2
index 908258fb23eaf..ceeaafb146d84 100644
@@ -27,6 +27,7 @@ struct hda_beep;
 struct hda_codec;
 struct hda_pcm;
 struct hda_pcm_stream;
+struct hda_jack_tbl;
 
 /*
  * codec bus
@@ -271,7 +272,8 @@ struct hda_codec {
 				 struct hda_codec *codec, hda_nid_t nid);
 
 	/* jack detection */
-	struct snd_array jacktbl;
+	struct hda_jack_tbl *jacktbl, *jacktbl_last; /* linked list head/tail */
+	int jacktbl_used; /* number of jacktbl elements */
 	unsigned long jackpoll_interval; /* In jiffies. Zero means no poll, rely on unsol events */
 	struct delayed_work jackpoll_work;
 
@@ -496,7 +498,7 @@ void snd_hda_update_power_acct(struct hda_codec *codec);
 
 static inline bool hda_codec_need_resume(struct hda_codec *codec)
 {
-	return !codec->relaxed_resume && codec->jacktbl.used;
+	return !codec->relaxed_resume && codec->jacktbl_used;
 }
 
 /*
sound/pci/hda/hda_codec.c +0 -1
index 791f3a3e8e258..670db66ef4e51 100644
@@ -940,7 +940,6 @@ snd_hda_codec_device_init(struct hda_bus *bus, unsigned int codec_addr,
 	snd_array_init(&codec->driver_pins, sizeof(struct hda_pincfg), 16);
 	snd_array_init(&codec->cvt_setups, sizeof(struct hda_cvt_setup), 8);
 	snd_array_init(&codec->spdif_out, sizeof(struct hda_spdif_out), 16);
-	snd_array_init(&codec->jacktbl, sizeof(struct hda_jack_tbl), 16);
 	snd_array_init(&codec->verbs, sizeof(struct hda_verb *), 8);
 	INIT_LIST_HEAD(&codec->conn_list);
 	INIT_LIST_HEAD(&codec->pcm_list_head);
sound/pci/hda/hda_jack.c +44 -35

170 lines not on this page · raw message

sound/pci/hda/hda_jack.h +1 -0
index ff7d289c034bf..26bfaae393568 100644
@@ -44,6 +44,7 @@ struct hda_jack_tbl {
 	int type;
 	int button_state;
 	struct snd_jack *jack;
+	struct hda_jack_tbl *next;
 };
 
 struct hda_jack_keymap {
sound/soc/sof/intel/hda-codec.c +2 -2
index 57998d3d8d15b..57c3a4df5627a 100644
@@ -87,7 +87,7 @@ void hda_codec_jack_wake_enable(struct snd_sof_dev *sdev, bool enable)
 		list_for_each_codec(codec, hbus) {
 			/* only set WAKEEN when needed for HDaudio codecs */
 			mask |= BIT(codec->core.addr);
-			if (codec->jacktbl.used)
+			if (codec->jacktbl_used)
 				val |= BIT(codec->core.addr);
 		}
 	} else {
@@ -116,7 +116,7 @@ void hda_codec_jack_check(struct snd_sof_dev *sdev)
 		 * Wake up all jack-detecting codecs regardless whether an event
 		 * has been recorded in STATESTS
 		 */
-		if (codec->jacktbl.used)
+		if (codec->jacktbl_used)
 			pm_request_resume(&codec->core.dev);
 }
 EXPORT_SYMBOL_NS_GPL(hda_codec_jack_check, SND_SOC_SOF_HDA_AUDIO_CODEC);
Signature · 1 line
2.53.0
author maintainer
#478 lore raw

PATCH 474/816 wifi: nl80211: reject zero RNR/MBSSID elements

In reply to Greg Kroah-Hartman

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

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

From: Johannes Berg <[email protected]>

[ Upstream commit c767e1173aeab7825a8dfb197041d3996db84e39 ]

That's a nonsensical configuration, and we get errors reported further down in mac80211 for it; hostapd has code that only adds the nested element if it'll not be an empty list.

Remove an unnecessary NULL check while at it.

Fixes dbbb27e183b1 ("cfg80211: support RNR for EMA AP")
Assisted-by LLM
[ sashal: Kept the existing kzalloc(struct_size(...), GFP_KERNEL) allocation instead of kzalloc_flex() in both parsers, and added the zero-element check above it. ]
---
 net/wireless/nl80211.c | 9 ++++++++-
 1 file changed, 8 insertions(+), 1 deletion(-)
net/wireless/nl80211.c +8 -1
index 0062ce34d4efb..4961c324a1714 100644
@@ -5581,6 +5581,9 @@ nl80211_parse_mbssid_elems(struct wiphy *wiphy, struct nlattr *attrs,
 		num_elems++;
 	}
 
+	if (!num_elems)
+		return ERR_PTR(-EINVAL);
+
 	elems = kzalloc(struct_size(elems, elem, num_elems), GFP_KERNEL);
 	if (!elems)
 		return ERR_PTR(-ENOMEM);
@@ -5616,6 +5619,9 @@ nl80211_parse_rnr_elems(struct wiphy *wiphy, struct nlattr *attrs,
 		num_elems++;
 	}
 
+	if (!num_elems)
+		return ERR_PTR(-EINVAL);
+
 	elems = kzalloc(struct_size(elems, elem, num_elems), GFP_KERNEL);
 	if (!elems)
 		return ERR_PTR(-ENOMEM);
@@ -5764,7 +5770,8 @@ static int nl80211_parse_beacon(struct cfg80211_registered_device *rdev,
 			if (IS_ERR(rnr))
 				return PTR_ERR(rnr);
 
-			if (rnr && rnr->cnt < bcn->mbssid_ies->cnt) {
+			/* RNR elements are only used with MBSSID elements */
+			if (rnr->cnt < bcn->mbssid_ies->cnt) {
 				kfree(rnr);
 				return -EINVAL;
 			}
Signature · 1 line
2.53.0
author maintainer
#479 lore raw

PATCH 475/816 dma-direct: Restore arch_dma_alloc() for the DMA_ATTR_NO_KERNEL_MAPPING case

In reply to Greg Kroah-Hartman

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

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

From: Marek Szyprowski <[email protected]>

[ Upstream commit 5e3bc6b44c8853bcc7782eac122c5baf2d02f399 ]

Commit 849facea92fa ("dma-direct: simplify the DMA_ATTR_NO_KERNEL_MAPPING handling") moved the DMA_ATTR_NO_KERNEL_MAPPING shortcut in dma_direct_alloc() in front of the arch_dma_alloc() call. Architectures providing their own DMA coherent allocator (CONFIG_ARCH_HAS_DMA_ALLOC) therefore no longer see such requests. ARM 32bit is one of such. Lack of the call to arch_dma_alloc() results in the lack of proper cache management on HighMem pages.

Take the dma-direct shortcut only for coherent devices or when the architecture doesn't provide arch_dma_alloc(). While touching this, move that check into separate function to avoid duplication in alloc and free paths.

Fixes 849facea92fa ("dma-direct: simplify the DMA_ATTR_NO_KERNEL_MAPPING handling")
Assisted-by Claude Opus 5.5 <[email protected]>
[ sashal: Replaced the upstream __DMA_ATTR_ALLOC_CC_SHARED check with the existing force_dma_unencrypted(dev) test in the new dma_direct_use_no_mapping() helper, since that attribute doesn't exist here. ]
---
 kernel/dma/direct.c | 21 +++++++++++++++++----
 1 file changed, 17 insertions(+), 4 deletions(-)
kernel/dma/direct.c +17 -4
index c8bba1b6f59c2..8abca2804435a 100644
@@ -185,6 +185,21 @@ static struct page *dma_direct_alloc_from_pool(struct device *dev, size_t size,
 	return page;
 }
 
+/*
+ * Check if the allocation can skip the kernel mapping and return the page
+ * pointer as the cookie.
+ */
+static bool dma_direct_use_no_mapping(struct device *dev, unsigned long attrs)
+{
+	if (!(attrs & DMA_ATTR_NO_KERNEL_MAPPING))
+		return false;
+	if (force_dma_unencrypted(dev) || is_swiotlb_for_alloc(dev))
+		return false;
+	if (IS_ENABLED(CONFIG_ARCH_HAS_DMA_ALLOC) && !dev_is_dma_coherent(dev))
+		return false;
+	return true;
+}
+
 static void *dma_direct_alloc_no_mapping(struct device *dev, size_t size,
 		dma_addr_t *dma_handle, gfp_t gfp)
 {
@@ -214,8 +229,7 @@ void *dma_direct_alloc(struct device *dev, size_t size,
 	if (attrs & DMA_ATTR_NO_WARN)
 		gfp |= __GFP_NOWARN;
 
-	if ((attrs & DMA_ATTR_NO_KERNEL_MAPPING) &&
-	    !force_dma_unencrypted(dev) && !is_swiotlb_for_alloc(dev))
+	if (dma_direct_use_no_mapping(dev, attrs))
 		return dma_direct_alloc_no_mapping(dev, size, dma_handle, gfp);
 
 	if (!dev_is_dma_coherent(dev)) {
@@ -318,8 +332,7 @@ void dma_direct_free(struct device *dev, size_t size,
 {
 	unsigned int page_order = get_order(size);
 
-	if ((attrs & DMA_ATTR_NO_KERNEL_MAPPING) &&
-	    !force_dma_unencrypted(dev) && !is_swiotlb_for_alloc(dev)) {
+	if (dma_direct_use_no_mapping(dev, attrs)) {
 		/* cpu_addr is a struct page cookie, not a kernel address */
 		dma_free_contiguous(dev, cpu_addr, size);
 		return;
Signature · 1 line
2.53.0
author maintainer
#480 lore raw

PATCH 476/816 PCI/P2PDMA: Do not tear down the allocate attribute on registration failure

In reply to Greg Kroah-Hartman

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

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

From: Leon Romanovsky <[email protected]>

[ Upstream commit 7c4d6505a1f8a1ebe8019b7f988ed494b696653b ]

pci_p2pdma_add_resource() installs pci_p2pdma_unmap_mappings() as a devres action with the devres allocated p2p_pgmap as its data, and only then adds the range to the pool:

error = devm_add_action_or_reset(&pdev->dev, pci_p2pdma_unmap_mappings,

                                   p2p_pgmap);
  if (error)
          goto pages_free;
  p2pdma = rcu_dereference_protected(pdev->p2pdma, 1);
  error = gen_pool_add_owner(p2pdma->pool, ...);
  if (error)
          goto pages_free;

The action removes the allocate attribute for the whole device, which tears down existing userspace mappings of every BAR already registered on it. Both failures here get that wrong, in opposite ways.

devm_add_action_or_reset() runs the action when it cannot allocate its devres node, so an -ENOMEM while registering a second BAR unmaps the first one. Use devm_add_action() and let the error path unwind only what this call created.

gen_pool_add_owner() allocates a chunk and can also fail with -ENOMEM. There the action is registered, and the error path frees p2p_pgmap with devm_kfree() while leaving the action pointing at it. On unbind devres runs the action and pci_p2pdma_unmap_mappings() dereferences p2p_pgmap->mem->owner->kobj, which is freed memory. Give that failure its own label and drop the action with devm_remove_action(), which removes it without running it.

Fixes 7e9c7ef83d78 ("PCI/P2PDMA: Allow userspace VMA allocations through sysfs")
Fixes f58ef9d1d135 ("PCI/P2PDMA: Separate the mmap() support from the core logic")
[ sashal: Passes pdev instead of p2p_pgmap as the devres action data in both devm_add_action() and devm_remove_action(), since the older unmap callback takes a struct pci_dev *. ]
---
 drivers/pci/p2pdma.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
drivers/pci/p2pdma.c +5 -3
index 01c8b79a9e0d7..d438ff25d2de1 100644
@@ -331,8 +331,8 @@ int pci_p2pdma_add_resource(struct pci_dev *pdev, int bar, size_t size,
 		goto pgmap_free;
 	}
 
-	error = devm_add_action_or_reset(&pdev->dev, pci_p2pdma_unmap_mappings,
-					 pdev);
+	error = devm_add_action(&pdev->dev, pci_p2pdma_unmap_mappings,
+				pdev);
 	if (error)
 		goto pages_free;
 
@@ -342,13 +342,15 @@ int pci_p2pdma_add_resource(struct pci_dev *pdev, int bar, size_t size,
 			range_len(&pgmap->range), dev_to_node(&pdev->dev),
 			&pgmap->ref);
 	if (error)
-		goto pages_free;
+		goto mappings_remove;
 
 	pci_info(pdev, "added peer-to-peer DMA memory %#llx-%#llx\n",
 		 pgmap->range.start, pgmap->range.end);
 
 	return 0;
 
+mappings_remove:
+	devm_remove_action(&pdev->dev, pci_p2pdma_unmap_mappings, pdev);
 pages_free:
 	devm_memunmap_pages(&pdev->dev, pgmap);
 pgmap_free:
Signature · 1 line
2.53.0
author maintainer
#481 lore raw

PATCH 477/816 fs/resctrl: Ensure default group reports tasks on monitor-only systems

In reply to Greg Kroah-Hartman

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

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

From: Tony Luck <[email protected]>

[ Upstream commit 2c10b3fa5bdf61e344bc522e6c2e00d870ce7ab8 ]

resctrl can be mounted on a system that supports monitoring but not allocation.

On such a system reading the "tasks" file in the default group reports no tasks, even when there are tasks assigned to the default group. This problem occurs because the check for whether a task belongs to a CTRL_MON group is gated by a check for whether the system supports allocation.

The resctrl_arch_alloc_capable() check in is_closid_match() breaks task reporting for the default group on monitor-only systems so remove this check. On systems that support allocation the check is redundant.

Fixes e6b2fac36fcc ("x86/resctrl: Use is_closid_match() in more places")
[ sashal: Changed the file path from fs/resctrl/rdtgroup.c to arch/x86/kernel/cpu/resctrl/rdtgroup.c, since resctrl hasn't been moved out of arch code yet; the one-line change itself is identical. ]
---
 arch/x86/kernel/cpu/resctrl/rdtgroup.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
arch/x86/kernel/cpu/resctrl/rdtgroup.c +1 -1
index 868e260947a10..3db3af835471e 100644
@@ -645,7 +645,7 @@ static int __rdtgroup_move_task(struct task_struct *tsk,
 
 static bool is_closid_match(struct task_struct *t, struct rdtgroup *r)
 {
-	return (resctrl_arch_alloc_capable() && (r->type == RDTCTRL_GROUP) &&
+	return (r->type == RDTCTRL_GROUP &&
 		resctrl_arch_match_closid(t, r->closid));
 }
 
Signature · 1 line
2.53.0
author maintainer
#482 lore raw

PATCH 478/816 bpf, arm64: Fix racy plt target update in bpf_arch_text_poke()

In reply to Greg Kroah-Hartman

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

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

From: Matthew Wood <[email protected]>

[ Upstream commit 6335e6719fd323c345427b7cf2d5d17c28fdbc41 ]

When a long-jump trampoline is attached to or detached from a bpf prog, bpf_arch_text_poke() updates the plt target at the end of the prog by temporarily making the page writable:

	set_memory_rw(page);
	WRITE_ONCE(plt->target, plt_target);
	set_memory_ro(page);

Since commit 1dad391daef1 ("bpf, arm64: use bpf_prog_pack for memory management"), bpf progs are allocated from the bpf prog pack, so unrelated progs and their plts commonly share a page. The sequence above is not serialized against other pokers, it runs before text_mutex is taken and callers only hold the lock of the trampoline being updated. Two CPUs attaching to or detaching from different target progs in the same page can therefore race:

	CPU A                           CPU B
	set_memory_rw(page)
	                                set_memory_rw(page)
	                                WRITE_ONCE(plt_B->target, ...)
	                                set_memory_ro(page)
	WRITE_ONCE(plt_A->target, ...)  <- permission fault

This was hit on an arm64 server with 64K pages while attaching fentry programs to bpf progs:

  Unable to handle kernel write to read-only memory at virtual address ffff80008f46d5f8
  ESR = 0x000000009600004f
  FSC = 0x0f: level 3 permission fault
  pte=00c00200ea5a0783
  Internal error: Oops: 000000009600004f [#1]  SMP
  pc : bpf_arch_text_poke+0x214/0x238
  lr : bpf_arch_text_poke+0x200/0x238
  Call trace:
   bpf_arch_text_poke+0x214/0x238 (P)
   __bpf_trampoline_link_prog+0x1c8/0x470
   bpf_trampoline_link_prog+0x64/0x90
   bpf_tracing_prog_attach+0x318/0x4a8
   bpf_raw_tp_link_attach+0x104/0x258
   bpf_raw_tracepoint_open+0x6c/0x90
   __sys_bpf+0x134c/0x3e10

Rather than serializing the permission changes, stop changing page permissions altogether and write the plt target with aarch64_insn_write_literal_u64(). It writes through the text patching fixmap under patch_lock, the same way the rest of the prog pack is written, and performs a single-copy atomic 64-bit store. The plt target is naturally aligned (see build_plt()), so CPUs concurrently executing the plt still observe either the old or the new target. This is the same helper ftrace and static calls use to update 64-bit literals that are loaded concurrently.

Fixes 1dad391daef1 ("bpf, arm64: use bpf_prog_pack for memory management")
[ sashal: Kept the local <asm/patching.h> include instead of upstream's <asm/text-patching.h> and dropped <asm/set_memory.h>; the hunk was otherwise identical, with only an offset shift. ]
---
 arch/arm64/net/bpf_jit_comp.c | 32 ++++++++++++++++----------------
 1 file changed, 16 insertions(+), 16 deletions(-)
arch/arm64/net/bpf_jit_comp.c +16 -16
index 9c28bb7b69ae6..6900a5ddb9439 100644
@@ -22,7 +22,6 @@
 #include <asm/debug-monitors.h>
 #include <asm/insn.h>
 #include <asm/patching.h>
-#include <asm/set_memory.h>
 
 #include "bpf_jit.h"
 
@@ -2631,21 +2630,22 @@ int bpf_arch_text_poke(void *ip, enum bpf_text_poke_type poke_type,
 		 */
 		plt_target = (u64)&dummy_tramp;
 
-	if (plt_target) {
-		/* non-zero plt_target indicates we're patching a bpf prog,
-		 * which is read only.
-		 */
-		if (set_memory_rw(PAGE_MASK & ((uintptr_t)&plt->target), 1))
-			return -EFAULT;
-		WRITE_ONCE(plt->target, plt_target);
-		set_memory_ro(PAGE_MASK & ((uintptr_t)&plt->target), 1);
-		/* since plt target points to either the new trampoline
-		 * or dummy_tramp, even if another CPU reads the old plt
-		 * target value before fetching the bl instruction to plt,
-		 * it will be brought back by dummy_tramp, so no barrier is
-		 * required here.
-		 */
-	}
+	/*
+	 * non-zero plt_target indicates we're patching a bpf prog,
+	 * which is read only. The prog may share its page in the bpf
+	 * prog pack with other progs, so write the aligned target
+	 * through the text patching fixmap without flipping the
+	 * page permissions to avoid racing with concurrent pokers.
+	 *
+	 * since plt target points to either the new trampoline
+	 * or dummy_tramp, even if another CPU reads the old plt
+	 * target value before fetching the bl instruction to plt,
+	 * it will be brought back by dummy_tramp, so no barrier is
+	 * required here.
+	 */
+	if (plt_target &&
+	    aarch64_insn_write_literal_u64(&plt->target, plt_target))
+		return -EFAULT;
 
 	/* if the old target and the new target are both long jumps, no
 	 * patching is required
Signature · 1 line
2.53.0
author maintainer
#483 lore raw

PATCH 479/816 ALSA: hda/realtek: Fix mute LEDs on HP ENVY 17-cr1xxx

In reply to Greg Kroah-Hartman

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

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

From: Maksim Krasutski <[email protected]>

[ Upstream commit dd83323e4d5e22bd04f7506a9ec33533465c8393 ]

The HP ENVY Laptop 17-cr1xxx with subsystem ID 103c:8be8 uses an ALC245 codec and two CS35L41 I2C speaker amplifiers. Its existing quirk configures the amplifiers but does not enable the speaker and microphone mute LED handlers.

Select ALC287_FIXUP_CS35L41_I2C_2_HP_MUTE_LEDS to retain the amplifier setup and enable both mute indicators.

The equivalent change was tested on an HP ENVY 17-cr1xxx running Kubuntu 26.04.1 with kernel 7.0.0-38-generic. Both keyboard mute indicators were confirmed working.

Fixes aa8e3ef4fe53 ("ALSA: hda/realtek: Add quirks for various HP ENVY models")
Assisted-by LLM
[ sashal: Applied the same one-line quirk change in the older Realtek HDA file path, since the upstream file location does not exist in this tree. ]
---
 sound/pci/hda/patch_realtek.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/pci/hda/patch_realtek.c +1 -1
index bfc75a1733fb5..b18eb7974c8eb 100644
@@ -11154,7 +11154,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = {
 	SND_PCI_QUIRK(0x103c, 0x8be5, "HP Envy 16", ALC287_FIXUP_CS35L41_I2C_2),
 	SND_PCI_QUIRK(0x103c, 0x8be6, "HP Envy 16", ALC287_FIXUP_CS35L41_I2C_2),
 	SND_PCI_QUIRK(0x103c, 0x8be7, "HP Envy 17", ALC287_FIXUP_CS35L41_I2C_2),
-	SND_PCI_QUIRK(0x103c, 0x8be8, "HP Envy 17", ALC287_FIXUP_CS35L41_I2C_2),
+	SND_PCI_QUIRK(0x103c, 0x8be8, "HP Envy 17", ALC287_FIXUP_CS35L41_I2C_2_HP_MUTE_LEDS),
 	SND_PCI_QUIRK(0x103c, 0x8be9, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2),
 	SND_PCI_QUIRK(0x103c, 0x8bf0, "HP", ALC236_FIXUP_HP_GPIO_LED),
 	SND_PCI_QUIRK(0x103c, 0x8bfd, "HP Pavilion 15-eg3xxx", ALC287_FIXUP_HP_GPIO_LED),
Signature · 1 line
2.53.0
author maintainer
#484 lore raw

PATCH 480/816 RDMA/rtrs-clt: Fix recv repost to satisfy ib_drain_rq

In reply to Greg Kroah-Hartman

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

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

From: Quanye Yang <[email protected]>

[ Upstream commit 3255d6b83491574b115806ec958d8f6ca090fa9c ]

On disconnect the client error recovery path calls ib_drain_qp(), which requires one free RQ slot and that no recv WQEs are posted while the queue is being drained.

When the server is loaded with always_invalidate=N, the path does not advertise RTRS_MSG_NEW_RKEY_F. A client-requested invalidation is then a standalone SEND_WITH_INV. The recv completion path did not repost that WQE; it posted two empty recv WQEs later, when the RDMA-with-IMM response carried RTRS_IO_RSP_W_INV_IMM. If the invalidate receive never arrived, each such response increased RQ occupancy by one until ib_post_recv() started returning -ENOMEM and __ib_drain_rq() failed with:

failed to drain recv queue: -12

Repost one empty recv WQE for every receive completion, including SEND_WITH_INV completions on the always_invalidate=N path, and only while the path is still connected so CQ polling cannot race with ib_drain_qp(). Size IO connection RQs to 2 * queue_depth + 1 to match the posted recv count and leave the drain slot.

Tested with a synthetic RTRS client flooding unpaired RTRS_IO_RSP_W_INV_IMM messages; error recovery no longer triggers __ib_drain_rq() warnings.

Fixes 6a98d71daea1 ("RDMA/rtrs: client: main functionality")
[ sashal: Kept this tree's min_t(int, ...) formatting in create_con_cq_qp() while changing the multiplier from 3 to 2, and dropped the removed block's %d error print in favor of the helper's %pe print. ]
---
 drivers/infiniband/ulp/rtrs/rtrs-clt.c | 45 +++++++++-----------------
 1 file changed, 15 insertions(+), 30 deletions(-)
drivers/infiniband/ulp/rtrs/rtrs-clt.c +15 -30
index dbce23eabcfd1..3525508fe0321 100644
@@ -582,25 +582,21 @@ static struct ib_cqe io_comp_cqe = {
 	.done = rtrs_clt_rdma_done
 };
 
-/*
- * Post x2 empty WRs: first is for this RDMA with IMM,
- * second is for RECV with INV, which happened earlier.
- */
-static int rtrs_post_recv_empty_x2(struct rtrs_con *con, struct ib_cqe *cqe)
+static int rtrs_clt_repost_recv(struct rtrs_clt_con *con)
 {
-	struct ib_recv_wr wr_arr[2], *wr;
-	int i;
+	struct rtrs_clt_path *clt_path = to_clt_path(con->c.path);
+	int err;
 
-	memset(wr_arr, 0, sizeof(wr_arr));
-	for (i = 0; i < ARRAY_SIZE(wr_arr); i++) {
-		wr = &wr_arr[i];
-		wr->wr_cqe  = cqe;
-		if (i)
-			/* Chain backwards */
-			wr->next = &wr_arr[i - 1];
-	}
+	if (READ_ONCE(clt_path->state) != RTRS_CLT_CONNECTED)
+		return 0;
 
-	return ib_post_recv(con->qp, wr, NULL);
+	err = rtrs_post_recv_empty(&con->c, &io_comp_cqe);
+	if (err) {
+		rtrs_err(con->c.path, "rtrs_post_recv_empty(): %pe\n",
+			 ERR_PTR(err));
+		rtrs_rdma_error_recovery(con);
+	}
+	return err;
 }
 
 static void rtrs_clt_rdma_done(struct ib_cq *cq, struct ib_wc *wc)
@@ -661,19 +657,7 @@ static void rtrs_clt_rdma_done(struct ib_cq *cq, struct ib_wc *wc)
 			rtrs_wrn(con->c.path, "Unknown IMM type %u\n",
 				  imm_type);
 		}
-		if (w_inval)
-			/*
-			 * Post x2 empty WRs: first is for this RDMA with IMM,
-			 * second is for RECV with INV, which happened earlier.
-			 */
-			err = rtrs_post_recv_empty_x2(&con->c, &io_comp_cqe);
-		else
-			err = rtrs_post_recv_empty(&con->c, &io_comp_cqe);
-		if (err) {
-			rtrs_err(con->c.path, "rtrs_post_recv_empty(): %d\n",
-				  err);
-			rtrs_rdma_error_recovery(con);
-		}
+		rtrs_clt_repost_recv(con);
 		break;
 	case IB_WC_RECV:
 		/*
@@ -689,6 +673,7 @@ static void rtrs_clt_rdma_done(struct ib_cq *cq, struct ib_wc *wc)
 
 			return  rtrs_clt_rkey_rsp_done(con, wc);
 		}
+		rtrs_clt_repost_recv(con);
 		break;
 	case IB_WC_RDMA_WRITE:
 		/*
@@ -1710,7 +1695,7 @@ static int create_con_cq_qp(struct rtrs_clt_con *con)
 			      /* QD * (REQ + RSP + FR REGS or INVS) + drain */
 			      clt_path->queue_depth * 4 + 1);
 		max_recv_wr = min_t(int, wr_limit,
-			      clt_path->queue_depth * 3 + 1);
+			      clt_path->queue_depth * 2 + 1);
 		max_send_sge = 2;
 	}
 	atomic_set(&con->c.sq_wr_avail, max_send_wr);
Signature · 1 line
2.53.0
author maintainer
#485 lore raw

PATCH 481/816 RDMA/core: Clear driver_udata before destroying objects in rdma_core

In reply to Greg Kroah-Hartman

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

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

From: Jacob Moroni <[email protected]>

[ Upstream commit d37e98844afea39a9614cac0de837701263c90f7 ]

When uobject creation fails while copying user output data (i.e., after the HW object has been created), it calls rdma_alloc_abort_uobject() with hw_obj_valid=true which then invokes the object's destroy callback, but passes the uverbs_attr_bundle from the original creation command.

The issue is that drivers are expected to validate the udata and return an error if there's unexpected content, and data from the wrong command counts as "unexpected content", so this ends up causing the driver's destroy call to fail.

A similar issue exists in the rereg_mr path when a new MR is created and the old one is destroyed.

Fix this by clearing driver_udata before invoking the driver's destroy method.

Fixes 6e0954b11c05 ("RDMA/uverbs: Allow drivers to create a new HW object during rereg_mr")
Fixes 0ac8903cbbe6 ("RDMA/core: Allow the ioctl layer to abort a fully created uobject")
[ sashal: Only the two uverbs_get_cleared_udata(attrs) calls in rdma_core.c were applied; the upstream helper move to a static inline in rdma_core.h and the create_qp() cleanup were dropped because this branch's layout differs. ]
---
 drivers/infiniband/core/rdma_core.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/infiniband/core/rdma_core.c +2 -0
index 29b1ab1d5f933..54d008e9ae85a 100644
@@ -687,6 +687,7 @@ void rdma_assign_uobject(struct ib_uobject *to_uobj, struct ib_uobject *new_uobj
 	 * If this fails then the uobject is still completely valid (though with
 	 * a new ID) and we leak it until context close.
 	 */
+	uverbs_get_cleared_udata(attrs);
 	uverbs_destroy_uobject(to_uobj, RDMA_REMOVE_DESTROY, attrs);
 }
 
@@ -702,6 +703,7 @@ void rdma_alloc_abort_uobject(struct ib_uobject *uobj,
 	int ret;
 
 	if (hw_obj_valid) {
+		uverbs_get_cleared_udata(attrs);
 		ret = uobj->uapi_object->type_class->destroy_hw(
 			uobj, RDMA_REMOVE_ABORT, attrs);
 		/*
Signature · 1 line
2.53.0
author maintainer
#486 lore raw

PATCH 482/816 dmaengine: ste_dma40: Preserve the LCPA I/O address space

In reply to Greg Kroah-Hartman

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

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

From: Linus Walleij <[email protected]>

[ Upstream commit 42c31fec1ca76b8b5f7759def122d418dff2cd4b ]

The LCPA area is mapped with devm_ioremap(), but lcpa_base and the per-channel lcpa pointer lack __iomem annotations. This loses the I/O address space and makes sparse warn when d40_current_addr() assigns LCPA register addresses to its __iomem pointers.

Annotate both pointers and the LCPA argument of d40_log_lli_lcpa_write() to preserve the I/O address space from the mapping to the register accessors. This also fixes the existing LCPA read and write warnings without changing the generated code.

---
 drivers/dma/ste_dma40.c    | 4 ++--
 drivers/dma/ste_dma40_ll.c | 8 ++++----
 drivers/dma/ste_dma40_ll.h | 2 +-
 3 files changed, 7 insertions(+), 7 deletions(-)
drivers/dma/ste_dma40.c +2 -2
index 2c83eb05faa16..6699689deecae 100644
@@ -509,7 +509,7 @@ struct d40_chan {
 	u32				 src_def_cfg;
 	u32				 dst_def_cfg;
 	struct d40_def_lcsp		 log_def;
-	struct d40_log_lli_full		*lcpa;
+	struct d40_log_lli_full __iomem	*lcpa;
 	/* Runtime reconfiguration */
 	dma_addr_t			runtime_addr;
 	enum dma_transfer_direction	runtime_direction;
@@ -617,7 +617,7 @@ struct d40_base {
 	/* Physical half channels */
 	struct d40_phy_res		 *phy_res;
 	struct d40_lcla_pool		  lcla_pool;
-	void				 *lcpa_base;
+	void __iomem			 *lcpa_base;
 	dma_addr_t			  phy_lcpa;
 	resource_size_t			  lcpa_size;
 	struct kmem_cache		 *desc_slab;
drivers/dma/ste_dma40_ll.c +4 -4
index 4c489b126cb27..3be7f5b1abb08 100644
@@ -333,10 +333,10 @@ static void d40_log_lli_link(struct d40_log_lli *lli_dst,
 		(dlos << D40_MEM_LCSP1_SLOS_POS);
 }
 
-void d40_log_lli_lcpa_write(struct d40_log_lli_full *lcpa,
-			   struct d40_log_lli *lli_dst,
-			   struct d40_log_lli *lli_src,
-			   int next, unsigned int flags)
+void d40_log_lli_lcpa_write(struct d40_log_lli_full __iomem *lcpa,
+			    struct d40_log_lli *lli_dst,
+			    struct d40_log_lli *lli_src,
+			    int next, unsigned int flags)
 {
 	d40_log_lli_link(lli_dst, lli_src, next, flags);
 
drivers/dma/ste_dma40_ll.h +1 -1
index 55090cb310579..ca9d076493610 100644
@@ -455,7 +455,7 @@ int d40_log_sg_to_lli(struct scatterlist *sg,
 		      u32 lcsp13, /* src or dst*/
 		      u32 data_width1, u32 data_width2);
 
-void d40_log_lli_lcpa_write(struct d40_log_lli_full *lcpa,
+void d40_log_lli_lcpa_write(struct d40_log_lli_full __iomem *lcpa,
 			    struct d40_log_lli *lli_dst,
 			    struct d40_log_lli *lli_src,
 			    int next, unsigned int flags);
Signature · 1 line
2.53.0
author maintainer
#487 lore raw

PATCH 483/816 mailbox: qcom-ipcc: Remove redundant mbox_controller_unregister() on probe failure

In reply to Greg Kroah-Hartman

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

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

From: Anup Vishwakarma <[email protected]>

[ Upstream commit da988ac6afe152f802140ccaa0ad5e8f675b8814 ]

qcom_ipcc_probe() registers the mailbox controller via devm_mbox_controller_register(), which automatically calls mbox_controller_unregister() through devres when the device is removed or probe fails. If devm_request_irq() subsequently fails, the
err_req_irq: label also manually calls mbox_controller_unregister(), resulting in a double call that corrupts the global mailbox controller list and causes a kernel panic.

Remove the redundant manual call and rely on devres for cleanup.

Fixes e9d50e4b4d04 ("mailbox: qcom-ipcc: Dynamic alloc for channel arrangement")
[ sashal: Adjusted context to keep the existing braces and dev_err() around the goto in qcom_ipcc_probe(), which the upstream hunk lacked. ]
---
 drivers/mailbox/qcom-ipcc.c | 5 +----
 1 file changed, 1 insertion(+), 4 deletions(-)
drivers/mailbox/qcom-ipcc.c +1 -4
index c619dfb24cd0e..c37ce8258da71 100644
@@ -321,16 +321,13 @@ static int qcom_ipcc_probe(struct platform_device *pdev)
 			       IRQF_NO_THREAD, name, ipcc);
 	if (ret < 0) {
 		dev_err(&pdev->dev, "Failed to register the irq: %d\n", ret);
-		goto err_req_irq;
+		goto err_mbox;
 	}
 
 	platform_set_drvdata(pdev, ipcc);
 
 	return 0;
 
-err_req_irq:
-	if (ipcc->num_chans)
-		mbox_controller_unregister(&ipcc->mbox);
 err_mbox:
 	irq_domain_remove(ipcc->irq_domain);
 
Signature · 1 line
2.53.0
author maintainer
#488 lore raw

PATCH 484/816 mailbox: arm_mhu_db: Remove redundant mbox_controller_unregister() on probe failure

In reply to Greg Kroah-Hartman

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

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

From: Anup Vishwakarma <[email protected]>

[ Upstream commit 8228ed61b6cbd6e79531c9ebfcad233c35eae562 ]

mhu_db_probe() registers the mailbox controller via devm_mbox_controller_register(), which automatically calls mbox_controller_unregister() through devres when the device is removed or probe fails. If devm_request_threaded_irq() subsequently fails in the channel setup loop, the error path also manually calls mbox_controller_unregister(), resulting in a double call that corrupts the global mailbox controller list and causes a kernel panic.

Remove the redundant manual call and rely on devres for cleanup.

Fixes 7002ca237b21 ("mailbox: arm_mhu: Add ARM MHU doorbell driver")
[ sashal: Kept the braces and the dev_err() line in the error branch, since a prerequisite cleanup is missing here, and removed only the mbox_controller_unregister() call. ]
---
 drivers/mailbox/arm_mhu_db.c | 1 -
 1 file changed, 1 deletion(-)
drivers/mailbox/arm_mhu_db.c +0 -1
index 27a510d469082..b6eeef867cbfc 100644
@@ -319,7 +319,6 @@ static int mhu_db_probe(struct amba_device *adev, const struct amba_id *id)
 						IRQF_ONESHOT, "mhu_db_link", mhu);
 		if (err) {
 			dev_err(dev, "Can't claim IRQ %d\n", irq);
-			mbox_controller_unregister(&mhu->mbox);
 			return err;
 		}
 	}
Signature · 1 line
2.53.0
author maintainer
#489 lore raw

PATCH 485/816 seq_buf: Do not print an empty line from an overflowed seq_buf_do_printk()

In reply to Greg Kroah-Hartman

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

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

From: Kees Cook <[email protected]>

[ Upstream commit a09fb764832dd7dbb9ccc38a9830f7294889c8ae ]

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

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

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

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

Fixes 96928d9032a7c ("seq_buf: Add seq_buf_do_printk() helper")
Assisted-by LLM
[ sashal: Dropped the new KUnit test hunk because the test file doesn't exist in this tree; the one-line fix in lib/seq_buf.c applied unchanged. ]
---
 lib/seq_buf.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/seq_buf.c +1 -1
index f3f3436d60a94..12082f042ff72 100644
@@ -128,7 +128,7 @@ void seq_buf_do_printk(struct seq_buf *s, const char *lvl)
 	}
 
 	/* No trailing LF */
-	if (start < s->buffer + s->len)
+	if (*start)
 		printk("%s%s\n", lvl, start);
 }
 EXPORT_SYMBOL_GPL(seq_buf_do_printk);
Signature · 1 line
2.53.0
author maintainer
#490 lore raw

PATCH 486/816 drm/panfrost: Fix PM refcnt and autosuspend issues at device probe/remove

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit e9672bf9382ff80be21d586f88e50339b85f5766 ]

During device probe(), failure to do a PM get() will leave the usage_count set to 0, which is the value assigned at device creation time. That means when the autosuspend delay expires, runtime suspend callback won't be invoked, so the device will remain powered on forever.

On top of that, failure to call PM put() during device unplug means Panfrost device's PM usage_count increases monotonically for every new module reload.

The outcome of both of the above meant that:

- Devfreq OPP transition notifications would be printed all the time, even when no jobs are being submitted. This quickly fills the kernel ring buffer with junk.
- Because MMU interrupts are only enabled when the device is reset, the very first job targeting the tiler heap BO after device probe() would always time out, since the driver's PM runtime resume callback would not be invoked.

To fix the above:
- Manually adjust the PM refcnt at device probe and removal time.
- Ensure pm_runtime_dont_use_autosuspend is called in the wind-down path.
- Call pm_runtime_put_autosuspend() when device is ready to accept jobs

Fixes 635430797d3f ("drm/panfrost: Rework runtime PM initialization")
Fixes 876b15d2c88d ("drm/panfrost: Fix module unload")
[ sashal: Replaced pfdev->base.dev with pfdev->dev, adjusted context for the shrinker and drm_dev_put() paths, and added pm_runtime_mark_last_busy() before pm_runtime_put_autosuspend() in probe. ]
---
 drivers/gpu/drm/panfrost/panfrost_drv.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)
drivers/gpu/drm/panfrost/panfrost_drv.c +12 -0
index c20a817dcd1f0..ef46ceb3e4c68 100644
@@ -644,6 +644,11 @@ static int panfrost_probe(struct platform_device *pdev)
 		goto err_out0;
 	}
 
+	/* The reason we must manually set the PM status and usage counter is
+	 * we have just powered the device up but did not go through the PM
+	 * runtime resume callback, so we need to update these ourselves.
+	 */
+	pm_runtime_get_noresume(pfdev->dev);
 	pm_runtime_set_active(pfdev->dev);
 	pm_runtime_mark_last_busy(pfdev->dev);
 	pm_runtime_enable(pfdev->dev);
@@ -662,14 +667,19 @@ static int panfrost_probe(struct platform_device *pdev)
 	if (err)
 		goto err_out2;
 
+	pm_runtime_mark_last_busy(pfdev->dev);
+	pm_runtime_put_autosuspend(pfdev->dev);
+
 	return 0;
 
 err_out2:
 	drm_dev_unregister(ddev);
 err_out1:
+	pm_runtime_dont_use_autosuspend(pfdev->dev);
 	pm_runtime_disable(pfdev->dev);
 	panfrost_device_fini(pfdev);
 	pm_runtime_set_suspended(pfdev->dev);
+	pm_runtime_put_noidle(pfdev->dev);
 err_out0:
 	drm_dev_put(ddev);
 	return err;
@@ -684,9 +694,11 @@ static void panfrost_remove(struct platform_device *pdev)
 	panfrost_gem_shrinker_cleanup(ddev);
 
 	pm_runtime_get_sync(pfdev->dev);
+	pm_runtime_dont_use_autosuspend(pfdev->dev);
 	pm_runtime_disable(pfdev->dev);
 	panfrost_device_fini(pfdev);
 	pm_runtime_set_suspended(pfdev->dev);
+	pm_runtime_put_noidle(pfdev->dev);
 
 	drm_dev_put(ddev);
 }
Signature · 1 line
2.53.0
author maintainer
#491 lore raw

PATCH 487/816 net: stmmac: set real_num_tx_queues to max(offset + count)

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Bianconi <[email protected]>

[ Upstream commit d128212667593c548a3c67d30031063ed46c29b7 ]

tc_setup_dwmac510_mqprio() computes the number of real TX queues as the sum of the per-TC queue counts. mqprio_validate_queue_counts() only rejects out-of-bounds or overlapping ranges, so layouts with gaps or a non-zero first offset are accepted, and in those cases the sum is smaller than the highest queue referenced by the netdev TC map.

netif_set_real_num_tx_queues() then passes this too-small count to netif_setup_tc(). However stmmac_set_ndev_tcs() has already zeroed dev->prio_tc_map() through netdev_reset_tc(), so when netif_setup_tc() runs every priority maps to TC0 and only the TC0 range is checked. A layout whose TC0 range fits but where a later TC references a queue beyond the new real_num_tx_queues is left with num_tc set and its TC map pointing at queues that are no longer real, without any warning; only when TC0 itself is out of range is the mapping disabled. The real prio_tc_map is programmed later by the qdisc, after this call, so the driver cannot rely on netif_setup_tc() to catch those cases.

Compute num_tx_queues as the maximum of offset[i] + count[i] instead of the sum of the counts, so real_num_tx_queues always covers the highest queue referenced by the TC map. This is a no-op for the contiguous channel-mode layouts where offset[i] == i and count[i] == 1.

The issue has been reported by sashiko and the patch has been tested on Qualcomm RB3-Gen2 board.

---
 drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c +2 -1
index 65085f9c9290e..f29fa17584788 100644
@@ -1265,7 +1265,8 @@ static int tc_setup_dwmac510_mqprio(struct stmmac_priv *priv,
 	for (u32 tc = 0; tc < num_tc; tc++) {
 		offset = qopt->offset[tc];
 		count = qopt->count[tc];
-		num_stack_tx_queues += count;
+		num_stack_tx_queues = max(num_stack_tx_queues,
+					  offset + count);
 
 		err = netdev_set_tc_queue(ndev, tc, count, offset);
 		if (err)
Signature · 1 line
2.53.0
author maintainer
#492 lore raw

PATCH 488/816 net: stmmac: align real_num_tx_queues to mqprio configuration

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Bianconi <[email protected]>

[ Upstream commit ac1ca0c3e139a2ebef2fc6c570af6647329726f1 ]

stmmac_hw_setup() unconditionally sets the number of real TX queues to plat->tx_queues_to_use on every device open. When a tc-mqprio qdisc is offloaded the driver reduces netif_set_real_num_tx_queues() to the number of queues enabled by the offload, but the next device open reverts it to plat->tx_queues_to_use while the netdev TC map is still the one programmed by the qdisc, leaving the two inconsistent.

Track the number of TX queues enabled by the current qdisc configuration in the per-qdisc state (priv->xmit_qdisc.num_tx_queues) and use it in stmmac_hw_setup(). The field defaults to plat->tx_queues_to_use at probe time and when the mqprio qdisc is destroyed, meaning no offload is active and the number of real TX queues must match the number of queues the driver allocated, and it is updated to the offloaded queue count on a successful mqprio setup.

mqprio only validates the requested queue ranges against dev->real_num_tx_queues, which can be larger than plat->tx_queues_to_use while the interface has not been opened yet. Reject a qopt whose highest referenced queue (offset + count) exceeds plat->tx_queues_to_use, so xmit_qdisc.num_tx_queues can never be larger than the number of TX queues the driver provisions. Otherwise stmmac_hw_setup() would expose TX queues without an allocated DMA ring.

Refuse to lower the number of TX queues below the count required by the active mqprio offload in stmmac_reinit_queues(), otherwise netif_set_real_num_tx_queues() would leave real_num_tx_queues inconsistent with the netdev TC map.

The issue has been reported by sashiko and the patch has been tested on a Qualcomm RB3-Gen2 board.

Fixes 195e4f409a40 ("net: stmmac: support fp parameter of tc-mqprio")
[ sashal: Adapted the simplified mqprio setup function by adding a pre-validation loop that rejects out-of-range queue configs before any state changes, since upstream's rollback machinery is absent. ]
---
 drivers/net/ethernet/stmicro/stmmac/stmmac.h      |  6 ++++++
 drivers/net/ethernet/stmicro/stmmac/stmmac_main.c | 12 +++++++++++-
 drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c   | 15 +++++++++++++++
 3 files changed, 32 insertions(+), 1 deletion(-)
drivers/net/ethernet/stmicro/stmmac/stmmac.h +6 -0
index dcdc4e24002ed..2bb4517b42c1b 100644
@@ -302,6 +302,12 @@ struct stmmac_priv {
 	/* Protect est parameters */
 	struct mutex est_lock;
 	struct stmmac_est *est;
+
+	struct {
+		bool enabled;
+		u32 num_tx_queues;
+	} xmit_qdisc;
+
 	struct dma_features dma_cap;
 	struct stmmac_counters mmc;
 	int hw_cap_support;
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +11 -1
index 81e97ab3178b4..c47114ccf7c45 100644
@@ -3548,7 +3548,7 @@ static int stmmac_hw_setup(struct net_device *dev, bool ptp_register)
 
 	/* Configure real RX and TX queues */
 	netif_set_real_num_rx_queues(dev, priv->plat->rx_queues_to_use);
-	netif_set_real_num_tx_queues(dev, priv->plat->tx_queues_to_use);
+	netif_set_real_num_tx_queues(dev, priv->xmit_qdisc.num_tx_queues);
 
 	/* Start the ball rolling... */
 	stmmac_start_all_dma(priv);
@@ -7465,6 +7465,10 @@ int stmmac_reinit_queues(struct net_device *dev, u32 rx_cnt, u32 tx_cnt)
 	struct stmmac_priv *priv = netdev_priv(dev);
 	int ret = 0, i;
 
+	if (priv->xmit_qdisc.enabled &&
+	    tx_cnt < priv->xmit_qdisc.num_tx_queues)
+		return -EINVAL;
+
 	if (netif_running(dev))
 		stmmac_release(dev);
 
@@ -7472,6 +7476,9 @@ int stmmac_reinit_queues(struct net_device *dev, u32 rx_cnt, u32 tx_cnt)
 
 	priv->plat->rx_queues_to_use = rx_cnt;
 	priv->plat->tx_queues_to_use = tx_cnt;
+	if (!priv->xmit_qdisc.enabled)
+		priv->xmit_qdisc.num_tx_queues = tx_cnt;
+
 	if (!netif_is_rxfh_configured(dev))
 		for (i = 0; i < ARRAY_SIZE(priv->rss.table); i++)
 			priv->rss.table[i] = ethtool_rxfh_indir_default(i,
@@ -7745,6 +7752,9 @@ int stmmac_dvr_probe(struct device *device,
 	ndev->xdp_features = NETDEV_XDP_ACT_BASIC | NETDEV_XDP_ACT_REDIRECT |
 			     NETDEV_XDP_ACT_XSK_ZEROCOPY;
 
+	/* Default qdisc num_tx_queues */
+	priv->xmit_qdisc.num_tx_queues = priv->plat->tx_queues_to_use;
+
 	ret = stmmac_tc_init(priv, priv);
 	if (!ret) {
 		ndev->hw_features |= NETIF_F_HW_TC;
drivers/net/ethernet/stmicro/stmmac/stmmac_tc.c +15 -0
index f29fa17584788..1bedea21194fa 100644
@@ -1239,6 +1239,9 @@ static int stmmac_reset_tc_mqprio(struct net_device *ndev,
 {
 	struct stmmac_priv *priv = netdev_priv(ndev);
 
+	priv->xmit_qdisc.num_tx_queues = priv->plat->tx_queues_to_use;
+	priv->xmit_qdisc.enabled = false;
+
 	netdev_reset_tc(ndev);
 	netif_set_real_num_tx_queues(ndev, priv->plat->tx_queues_to_use);
 
@@ -1258,6 +1261,15 @@ static int tc_setup_dwmac510_mqprio(struct stmmac_priv *priv,
 	if (!num_tc)
 		return stmmac_reset_tc_mqprio(ndev, extack);
 
+	for (u32 tc = 0; tc < num_tc; tc++) {
+		if (qopt->offset[tc] + qopt->count[tc] >
+		    priv->plat->tx_queues_to_use) {
+			NL_SET_ERR_MSG_MOD(extack,
+					   "Queues exceed hw TX queues");
+			return -EINVAL;
+		}
+	}
+
 	err = netdev_set_num_tc(ndev, num_tc);
 	if (err)
 		return err;
@@ -1282,6 +1294,9 @@ static int tc_setup_dwmac510_mqprio(struct stmmac_priv *priv,
 	if (err)
 		goto err_reset_tc;
 
+	priv->xmit_qdisc.num_tx_queues = num_stack_tx_queues;
+	priv->xmit_qdisc.enabled = true;
+
 	return 0;
 
 err_reset_tc:
Signature · 1 line
2.53.0
author maintainer
#493 lore raw

PATCH 489/816 btrfs: roll back sprout setup after device add failure

In reply to Greg Kroah-Hartman

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

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

From: Guanghui Yang <[email protected]>

[ Upstream commit f5166f53b60b4d1ee9957c0baccd3b09735001d4 ]

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

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

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

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

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

[ sashal: Dropped the context line calling btrfs_update_per_profile_avail() after the rollback call, since that helper doesn't exist in this tree. ]
---
 fs/btrfs/volumes.c | 37 +++++++++++++++++++++++++++++++++++++
 1 file changed, 37 insertions(+)
fs/btrfs/volumes.c +37 -0
index b6ed1190a63d7..0652c630743e8 100644
@@ -2715,6 +2715,41 @@ static void btrfs_setup_sprout(struct btrfs_fs_info *fs_info,
 	btrfs_set_super_flags(disk_super, super_flags);
 }
 
+static void btrfs_rollback_sprout(struct btrfs_fs_info *fs_info,
+				  struct btrfs_fs_devices *seed_devices)
+{
+	struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
+	struct btrfs_super_block *disk_super = fs_info->super_copy;
+	struct btrfs_device *device;
+	u64 super_flags;
+
+	lockdep_assert_held(&uuid_mutex);
+	lockdep_assert_held(&fs_devices->device_list_mutex);
+
+	list_del_init(&seed_devices->seed_list);
+	list_splice_init_rcu(&seed_devices->devices, &fs_devices->devices, synchronize_rcu);
+	list_for_each_entry(device, &fs_devices->devices, dev_list) {
+		device->fs_devices = fs_devices;
+	}
+
+	fs_devices->seeding = true;
+	fs_devices->num_devices = seed_devices->num_devices;
+	fs_devices->open_devices = seed_devices->open_devices;
+	fs_devices->missing_devices = seed_devices->missing_devices;
+	fs_devices->rotating = seed_devices->rotating;
+	fs_devices->latest_dev = seed_devices->latest_dev;
+
+	memcpy(fs_devices->fsid, seed_devices->fsid, BTRFS_FSID_SIZE);
+	memcpy(fs_devices->metadata_uuid, seed_devices->metadata_uuid, BTRFS_FSID_SIZE);
+	memcpy(disk_super->fsid, seed_devices->fsid, BTRFS_FSID_SIZE);
+
+	super_flags = (btrfs_super_flags(disk_super) | BTRFS_SUPER_FLAG_SEEDING);
+	btrfs_set_super_flags(disk_super, super_flags);
+
+	seed_devices->opened = 0;
+	free_fs_devices(seed_devices);
+}
+
 /*
  * Store the expected generation for seed devices in device items.
  */
@@ -3027,6 +3062,8 @@ int btrfs_init_new_device(struct btrfs_fs_info *fs_info, const char *device_path
 				    orig_super_total_bytes);
 	btrfs_set_super_num_devices(fs_info->super_copy,
 				    orig_super_num_devices);
+	if (seeding_dev)
+		btrfs_rollback_sprout(fs_info, seed_devices);
 	mutex_unlock(&fs_info->chunk_mutex);
 	mutex_unlock(&fs_info->fs_devices->device_list_mutex);
 error_trans:
Signature · 1 line
2.53.0
author maintainer
#494 lore raw

PATCH 490/816 ASoC: codecs: wcd939x: read the SoundWire port switches per channel

In reply to Greg Kroah-Hartman

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

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

From: Joonhoe Kim <[email protected]>

[ Upstream commit e7860dc5d8d45f6a0e98bfe542c7b776c5ede2a4 ]

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

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

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

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

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

PATCH 491/816 wifi: ath12k: avoid IDR mutation during pending mgmt TX cleanup

In reply to Greg Kroah-Hartman

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

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

From: Jiale Yao <[email protected]>

[ Upstream commit 94c7b50351fd30e1dfe1b4051197a1445d8547e1 ]

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

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

Fixes d889913205cf ("wifi: ath12k: driver for Qualcomm Wi-Fi 7 devices")
[ sashal: Adjusted context lines in core.c and mac.h for older surrounding code (different neighbouring calls, a missing helper); the changed lines match upstream. ]
---
 drivers/net/wireless/ath/ath12k/core.c |  3 +--
 drivers/net/wireless/ath/ath12k/mac.c  | 12 ++++++------
 drivers/net/wireless/ath/ath12k/mac.h  |  2 +-
 3 files changed, 8 insertions(+), 9 deletions(-)
drivers/net/wireless/ath/ath12k/core.c +1 -2
index c3c76e2680629..af4e9c77f5209 100644
@@ -1064,8 +1064,7 @@ static void ath12k_core_pre_reconfigure_recovery(struct ath12k_base *ab)
 			complete(&ar->bss_survey_done);
 
 			wake_up(&ar->dp.tx_empty_waitq);
-			idr_for_each(&ar->txmgmt_idr,
-				     ath12k_mac_tx_mgmt_pending_free, ar);
+			ath12k_mac_tx_mgmt_pending_free(ar);
 			idr_destroy(&ar->txmgmt_idr);
 			wake_up(&ar->txmgmt_empty_waitq);
 		}
drivers/net/wireless/ath/ath12k/mac.c +6 -6
index 9f10eb7de3df2..6f2df6d2b68d4 100644
@@ -5699,13 +5699,13 @@ static void ath12k_mac_tx_mgmt_free(struct ath12k *ar, int buf_id)
 	ath12k_mgmt_over_wmi_tx_drop(ar, msdu);
 }
 
-int ath12k_mac_tx_mgmt_pending_free(int buf_id, void *skb, void *ctx)
+void ath12k_mac_tx_mgmt_pending_free(struct ath12k *ar)
 {
-	struct ath12k *ar = ctx;
-
-	ath12k_mac_tx_mgmt_free(ar, buf_id);
+	struct sk_buff *msdu;
+	int buf_id;
 
-	return 0;
+	idr_for_each_entry(&ar->txmgmt_idr, msdu, buf_id)
+		ath12k_mac_tx_mgmt_free(ar, buf_id);
 }
 
 static void ath12k_mac_vif_txmgmt_cleanup(struct ath12k *ar,
@@ -8999,7 +8999,7 @@ static const struct wiphy_iftype_ext_capab ath12k_iftypes_ext_capa[] = {
 
 static void ath12k_mac_cleanup_unregister(struct ath12k *ar)
 {
-	idr_for_each(&ar->txmgmt_idr, ath12k_mac_tx_mgmt_pending_free, ar);
+	ath12k_mac_tx_mgmt_pending_free(ar);
 	idr_destroy(&ar->txmgmt_idr);
 
 	kfree(ar->mac.sbands[NL80211_BAND_2GHZ].channels);
drivers/net/wireless/ath/ath12k/mac.h +1 -1
index 5efbb6822628f..2c0a3b199669b 100644
@@ -73,7 +73,7 @@ struct ath12k *ath12k_mac_get_ar_by_pdev_id(struct ath12k_base *ab, u32 pdev_id)
 
 void ath12k_mac_drain_tx(struct ath12k *ar);
 void ath12k_mac_peer_cleanup_all(struct ath12k *ar);
-int ath12k_mac_tx_mgmt_pending_free(int buf_id, void *skb, void *ctx);
+void ath12k_mac_tx_mgmt_pending_free(struct ath12k *ar);
 enum rate_info_bw ath12k_mac_bw_to_mac80211_bw(enum ath12k_supported_bw bw);
 enum ath12k_supported_bw ath12k_mac_mac80211_bw_to_ath12k_bw(enum rate_info_bw bw);
 enum hal_encrypt_type ath12k_dp_tx_get_encrypt_type(u32 cipher);
Signature · 1 line
2.53.0
author maintainer
#496 lore raw

PATCH 492/816 perf symbol: Fix symbol loading from libbfd

In reply to Greg Kroah-Hartman

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

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

From: Namhyung Kim <[email protected]>

[ Upstream commit f814d9e6cdbef6413a72d6dd6d5e4e79e815cf44 ]

The dso__load() should return a positive number (number of symbols loaded) when it succeded to load symbols. But dso__load_bfd_symbols() only returns 0 and it's hard to check if it actually loaded symbols or not. Let's return the value of dso__has_symbol() and check it in dso__load() so that it can return 1 for success.

Fixes eac9a4342e5447ca ("perf symbols: Try reading the symbol table with libbfd")
Cc Remi Bernon <[email protected]>
[ sashal: Applied the dso__load_bfd_symbols() return-value change in symbol.c, because the libbfd code hasn't been split out into its own file here. ]
---
 tools/perf/tests/pe-file-parsing.c | 2 +-
 tools/perf/util/symbol.c           | 6 +++---
 2 files changed, 4 insertions(+), 4 deletions(-)
tools/perf/tests/pe-file-parsing.c +1 -1
index fff58b220c07b..69060aa1a62a1 100644
@@ -59,7 +59,7 @@ static int run_dir(const char *d)
 	TEST_ASSERT_VAL("Failed to get dso", dso);
 
 	ret = dso__load_bfd_symbols(dso, debugfile);
-	TEST_ASSERT_VAL("Failed to load symbols", ret == 0);
+	TEST_ASSERT_VAL("Failed to load symbols", ret > 0);
 
 	dso__sort_by_name(dso);
 	sym = dso__find_symbol_by_name(dso, "main", &idx);
tools/perf/util/symbol.c +3 -3
index 99ee76bc6c513..ef4594088684a 100644
@@ -1694,7 +1694,7 @@ int dso__load_bfd_symbols(struct dso *dso, const char *debugfile)
 	symbols__fixup_duplicate(dso__symbols(dso));
 	dso__set_adjust_symbols(dso, true);
 
-	err = 0;
+	err = dso__has_symbols(dso);
 out_free:
 	free(symbols);
 out_close:
@@ -1914,8 +1914,8 @@ int dso__load(struct dso *dso, struct map *map)
 		if (nsexit)
 			nsinfo__mountns_enter(dso__nsinfo(dso), &nsc);
 
-		if (bfdrc == 0) {
-			ret = 0;
+		if (bfdrc > 0) {
+			ret = 1;
 			break;
 		}
 
Signature · 1 line
2.53.0
author maintainer
#497 lore raw

PATCH 493/816 perf symbol: Add missing symsrc__destroy() for libbfd

In reply to Greg Kroah-Hartman

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

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

From: Namhyung Kim <[email protected]>

[ Upstream commit 35477b351e6a697c85dc7d37e5081621889f8e40 ]

When libbfd loaded symbols and there's a pending syms_ss, it'd be lost or overwrite existing symbols. Let's destroy it before breaking the loop so that it can safely return from the function.

Fixes eac9a4342e5447ca ("perf symbols: Try reading the symbol table with libbfd")
Cc Remi Bernon <[email protected]>
---
 tools/perf/util/symbol.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
tools/perf/util/symbol.c +2 -1
index ef4594088684a..4de28911bdb52 100644
@@ -1916,7 +1916,7 @@ int dso__load(struct dso *dso, struct map *map)
 
 		if (bfdrc > 0) {
 			ret = 1;
-			break;
+			goto out_destroy;
 		}
 
 		if (!is_reg || sirc < 0)
@@ -1981,6 +1981,7 @@ int dso__load(struct dso *dso, struct map *map)
 			ret += nr_plt;
 	}
 
+out_destroy:
 	for (; ss_pos > 0; ss_pos--)
 		symsrc__destroy(&ss_[ss_pos - 1]);
 out_free:
Signature · 1 line
2.53.0
author maintainer
#498 lore raw

PATCH 494/816 Bluetooth: hci_sync: fix mesh adv timeout units

In reply to Greg Kroah-Hartman

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

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

From: Pauli Virtanen <[email protected]>

[ Upstream commit 8a8d51eeedebfa5aaaae7720f2fb2aa1a67b8587 ]

Mesh adv instance timeout and duration are in milliseconds, see mesh_send_sync, hci_add_adv_instance. hci_schedule_adv_instance_sync() and hci_enable_ext_advertising_sync() ignore this, and scale the timeout wrong.

Fix for mesh instances by using msecs_to_jiffies() in hci_schedule_adv_instance_sync and fixing the scaling in hci_enable_ext_advertising_sync.

Fixes BlueZ "Mesh - Send cancel" test failures.

Fixes b338d91703fa ("Bluetooth: Implement support for Mesh")
Assisted-by opencode:qwen3.8-flash-next sashiko
[ sashal: Kept the tree's msecs_to_jiffies(timeout * 1000) for the non-mesh case instead of upstream's secs_to_jiffies(timeout), since that helper isn't used in this file here, and added the mesh branch. ]
---
 net/bluetooth/hci_sync.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
net/bluetooth/hci_sync.c +4 -2
index e51af37b10152..3793fc359a9ff 100644
@@ -1731,7 +1731,8 @@ int hci_enable_ext_advertising_sync(struct hci_dev *hdev, u8 instance)
 	 * scheduling it.
 	 */
 	if (adv && adv->timeout) {
-		u16 duration = adv->timeout * MSEC_PER_SEC;
+		u16 duration = adv->mesh ? adv->timeout :
+					   adv->timeout * MSEC_PER_SEC;
 
 		/* Time = N * 10 ms */
 		set->duration = cpu_to_le16(duration / 10);
@@ -2191,7 +2192,8 @@ int hci_schedule_adv_instance_sync(struct hci_dev *hdev, u8 instance,
 		hdev->adv_instance_timeout = timeout;
 		queue_delayed_work(hdev->req_workqueue,
 				   &hdev->adv_instance_expire,
-				   msecs_to_jiffies(timeout * 1000));
+				   adv->mesh ? msecs_to_jiffies(timeout) :
+					       msecs_to_jiffies(timeout * 1000));
 	}
 
 	/* If we're just re-scheduling the same instance again then do not
Signature · 1 line
2.53.0
author maintainer
#499 lore raw

PATCH 495/816 Bluetooth: hci_event: Fix LE link drop on remote features command status

In reply to Greg Kroah-Hartman

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

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

From: Kevin Dewald <[email protected]>

[ Upstream commit 91638f53ff2b8234195ff27ec913e068269a28e9 ]

When the local controller supports peripheral-initiated features exchange, the LE Read Remote Features procedure also runs for incoming connections, and it fails with Unsupported Remote Feature (0x1a) if the central does not support that feature. hci_le_remote_feat_complete_evt() and hci_le_read_all_remote_features_evt() handle this and let the connection transition into connected state.

A controller can also return that error in the Command Status event instead. An Intel controller does so for a central that does not support peripheral-initiated features exchange, presumably because it already has the features of the central. hci_cs_le_read_remote_features() and hci_cs_le_read_all_remote_features() then confirm the connection as failed while it is still in BT_CONFIG, and the hci_conn_drop() in le_read_features_complete() disconnects it right away:

Quoted 1 line

HCI Event: LE Meta Event (0x3e) plen 31

      LE Enhanced Connection Complete (0x0a)
        Status: Success (0x00)
        Role: Peripheral (0x01)

< HCI Command: LE Read Remote Used Features (0x08|0x0016) plen 2

Quoted 1 line

HCI Event: Command Status (0x0f) plen 4

      LE Read Remote Used Features (0x08|0x0016) ncmd 1
        Status: Unsupported Remote Feature / Unsupported LMP Feature (0x1a)
  < HCI Command: Disconnect (0x01|0x0006) plen 3
        Reason: Remote User Terminated Connection (0x13)

Data the central sends afterwards is reported as:

Bluetooth: hci0: ACL packet for unknown connection handle 3585

Handle Unsupported Remote Feature in the command status the same way as in the complete events.

Fixes 0fe29fd1cd77 ("Bluetooth: Read LE remote features during connection establishment")
Fixes a106e50be74b ("Bluetooth: HCI: Add support for LL Extended Feature Set")
Assisted-by Claude:claude-opus-5.5
[ sashal: Kept this tree's nested if (conn) { if (conn->state == BT_CONFIG) {...} } with hci_conn_drop() and added the new block inside, and dropped the second hunk because the all-remote-features function doesn't exist here. ]
---
 net/bluetooth/hci_event.c | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)
net/bluetooth/hci_event.c +16 -0
index 3eea2343f1977..f723210c52e53 100644
@@ -2930,6 +2930,22 @@ static void hci_cs_le_read_remote_features(struct hci_dev *hdev, u8 status)
 	conn = hci_conn_hash_lookup_handle(hdev, __le16_to_cpu(cp->handle));
 	if (conn) {
 		if (conn->state == BT_CONFIG) {
+			/* If the local controller supports peripheral-initiated
+			 * features exchange, but the remote controller does not,
+			 * then the controller may already return the error code
+			 * 0x1a for unsupported remote feature in the command
+			 * status.
+			 *
+			 * Handle it as hci_le_remote_feat_complete_evt() does and
+			 * allow the connection to transition into connected state.
+			 */
+			if (!conn->out &&
+			    status == HCI_ERROR_UNSUPPORTED_REMOTE_FEATURE &&
+			    (hdev->le_features[0] & HCI_LE_PERIPHERAL_FEATURES)) {
+				conn->state = BT_CONNECTED;
+				status = 0x00;
+			}
+
 			hci_connect_cfm(conn, status);
 			hci_conn_drop(conn);
 		}
Signature · 1 line
2.53.0
author maintainer
#500 lore raw

PATCH 496/816 iommufd: Keep reserved IOVA ranges when a replace within one IOAS fails

In reply to Greg Kroah-Hartman

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

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

From: Donggeun Yoo <[email protected]>

[ Upstream commit 1e67cca28490f897788c128c650a6f2cbb565403 ]

iommufd_device_do_replace() installs the group's reserved IOVA ranges in the new hwpt's IOAS only when it differs from the old hwpt's IOAS. If the replace fails in iommufd_device_do_replace() or iommufd_group_do_replace_reserved_iova(), the error paths remove the ranges from the new hwpt's IOAS whether or not the IOAS is shared between the old and new hwpt, which removes the ranges that the old hwpt still needs.

For example, on x86 with intel-iommu, after a replace within a shared IOAS fails with -ENODEV, IOMMU_IOAS_IOVA_RANGES goes from

0x0-0xfedfffff
0xfef00000-0xffffffffffff

to

0x0-0xffffffffffff

and IOMMU_IOAS_MAP at 0xfee00000 succeeds.

Remove the ranges on failure only when the replace installed them, and look up the old hwpt_paging before the replace so that the error path can compare the IOAS.

Fixes e88d4ec154a8 ("iommufd: Add iommufd_device_replace()")
Assisted-by LLM
[ sashal: adjusted context: no attach_resv variable or pasid check in this tree, so the error-path IOAS guard uses hwpt_paging and old_hwpt_paging is looked up right after old_hwpt. ]
---
 drivers/iommu/iommufd/device.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
drivers/iommu/iommufd/device.c +5 -3
index 5dc9fa269e3a8..fd07f7f25e13f 100644
@@ -592,7 +592,8 @@ iommufd_group_do_replace_reserved_iova(struct iommufd_group *igroup,
 	return 0;
 
 err_unresv:
-	iommufd_group_remove_reserved_iova(igroup, hwpt_paging);
+	if (!old_hwpt_paging || hwpt_paging->ioas != old_hwpt_paging->ioas)
+		iommufd_group_remove_reserved_iova(igroup, hwpt_paging);
 	return rc;
 }
 
@@ -625,6 +626,7 @@ iommufd_device_do_replace(struct iommufd_device *idev, ioasid_t pasid,
 	}
 
 	old_hwpt = igroup->hwpt;
+	old_hwpt_paging = find_hwpt_paging(old_hwpt);
 	if (hwpt_paging) {
 		rc = iommufd_group_do_replace_reserved_iova(igroup, hwpt_paging);
 		if (rc)
@@ -635,7 +637,6 @@ iommufd_device_do_replace(struct iommufd_device *idev, ioasid_t pasid,
 	if (rc)
 		goto err_unresv;
 
-	old_hwpt_paging = find_hwpt_paging(old_hwpt);
 	if (old_hwpt_paging &&
 	    (!hwpt_paging || hwpt_paging->ioas != old_hwpt_paging->ioas))
 		iommufd_group_remove_reserved_iova(igroup, old_hwpt_paging);
@@ -656,7 +657,8 @@ iommufd_device_do_replace(struct iommufd_device *idev, ioasid_t pasid,
 	/* Caller must destroy old_hwpt */
 	return old_hwpt;
 err_unresv:
-	if (hwpt_paging)
+	if (hwpt_paging &&
+	    (!old_hwpt_paging || hwpt_paging->ioas != old_hwpt_paging->ioas))
 		iommufd_group_remove_reserved_iova(igroup, hwpt_paging);
 err_unlock:
 	mutex_unlock(&idev->igroup->lock);
Signature · 1 line
2.53.0
author maintainer
#501 lore raw

PATCH 497/816 rxrpc: Fix aborting in rxperf test server

In reply to Greg Kroah-Hartman

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

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

From: David Howells <[email protected]>

[ Upstream commit 7f15923909866e76608ea6474368570938e783fc ]

Fix rxperf_process_call() to always abort if it gets a send error rather than only aborting on ENOMEM.

Fixes 75bfdbf2fca3 ("rxrpc: Implement an in-kernel rxperf server for testing purposes")
cc Marc Dionne <[email protected]>
cc Eric Dumazet <[email protected]>
cc "David S. Miller" <[email protected]>
cc Jakub Kicinski <[email protected]>
cc Paolo Abeni <[email protected]>
cc Simon Horman <[email protected]>
---
 include/trace/events/rxrpc.h |  2 +-
 net/rxrpc/rxperf.c           | 11 ++++++-----
 2 files changed, 7 insertions(+), 6 deletions(-)
include/trace/events/rxrpc.h +1 -1
index 5e29744e45037..a292b6f08258b 100644
@@ -27,8 +27,8 @@
 	EM(afs_abort_unmarshal_error,		"afs-unmarshal")	\
 	/* rxperf errors */						\
 	EM(rxperf_abort_general_error,		"rxperf-error")		\
-	EM(rxperf_abort_oom,			"rxperf-oom")		\
 	EM(rxperf_abort_op_not_supported,	"rxperf-op-notsupp")	\
+	EM(rxperf_abort_send_error,		"rxperf-send-error")	\
 	EM(rxperf_abort_unmarshal_error,	"rxperf-unmarshal")	\
 	/* RxKAD security errors */					\
 	EM(rxkad_abort_1_short_check,		"rxkad1-short-check")	\
net/rxrpc/rxperf.c +6 -5
index c16afe540d09c..d7215f939bdb3 100644
@@ -526,7 +526,7 @@ static int rxperf_process_call(struct rxperf_call *call)
 		ret = rxrpc_kernel_send_data(rxperf_socket, call->rxcall, &msg,
 					     rxperf_notify_end_reply_tx);
 		if (ret < 0)
-			return ret;
+			goto send_error;
 		reply_len -= len;
 	}
 
@@ -537,10 +537,11 @@ static int rxperf_process_call(struct rxperf_call *call)
 	msg.msg_flags = 0;
 	ret = rxrpc_kernel_send_data(rxperf_socket, call->rxcall, &msg,
 				     rxperf_notify_end_reply_tx);
-	if (ret == -ENOMEM)
-		rxrpc_kernel_abort_call(rxperf_socket, call->rxcall,
-					RXGEN_SS_MARSHAL, -ENOMEM,
-					rxperf_abort_oom);
+	if (ret == 0)
+		return 0;
+send_error:
+	rxrpc_kernel_abort_call(rxperf_socket, call->rxcall, RXGEN_SS_MARSHAL,
+				ret, rxperf_abort_send_error);
 	return ret;
 }
 
Signature · 1 line
2.53.0
author maintainer
#502 lore raw

PATCH 498/816 rxrpc: Fix sendmsg length

In reply to Greg Kroah-Hartman

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

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

From: David Howells <[email protected]>

[ Upstream commit ef369cacbd524931199078427ae152c63a826189 ]

rxrpc_send_data() is given two data lengths (len and msg->msg_iter.count) and is inconsistent about how it uses them. Fix this by using len in preference to msg->msg_iter.count. Also limit the amount copied to either len or msg->msg_iter.count, whichever is smaller.

Note that, currently, all the callers have len and msg->msg_iter.count the same and so the problem won't occur. This is a prerequisite for another patch that fixes the handling of encryption errors.

Fixes 382d7974de31 ("RxRPC: Use iov_iter_count() in rxrpc_send_data() instead of the len argument")
cc Marc Dionne <[email protected]>
cc Jeffrey Altman <[email protected]>
cc Eric Dumazet <[email protected]>
cc "David S. Miller" <[email protected]>
cc Jakub Kicinski <[email protected]>
cc Paolo Abeni <[email protected]>
cc Simon Horman <[email protected]>
[ sashal: Replaced the umin() context line with the tree's min_t(size_t, ...) form by taking the patch's if (len > 0) and min3(txb->space, len, msg_data_left(msg)) lines directly, with no other adaptation. ]
---
 net/rxrpc/sendmsg.c | 17 +++++++++--------
 1 file changed, 9 insertions(+), 8 deletions(-)
net/rxrpc/sendmsg.c +9 -8
index ea649144c49f0..6686fc99ec3b0 100644
@@ -324,9 +324,9 @@ static int rxrpc_send_data(struct rxrpc_sock *rx,
 
 	ret = -EMSGSIZE;
 	if (call->tx_total_len != -1) {
-		if (len - copied > call->tx_total_len)
+		if (len > call->tx_total_len)
 			goto maybe_error;
-		if (!more && len - copied != call->tx_total_len)
+		if (!more && len != call->tx_total_len)
 			goto maybe_error;
 	}
 
@@ -345,7 +345,7 @@ static int rxrpc_send_data(struct rxrpc_sock *rx,
 			 * the security header is going to be in the padded
 			 * region (enc blocksize), but the trailer is not.
 			 */
-			remain = more ? INT_MAX : msg_data_left(msg);
+			remain = more ? INT_MAX : len;
 			txb = call->conn->security->alloc_txbuf(call, remain, sk->sk_allocation);
 			if (!txb) {
 				ret = -ENOMEM;
@@ -359,8 +359,8 @@ static int rxrpc_send_data(struct rxrpc_sock *rx,
 		_debug("append");
 
 		/* append next segment of data to the current buffer */
-		if (msg_data_left(msg) > 0) {
-			size_t copy = min_t(size_t, txb->space, msg_data_left(msg));
+		if (len > 0) {
+			size_t copy = min3(txb->space, len, msg_data_left(msg));
 
 			_debug("add %zu", copy);
 			if (!copy_from_iter_full(txb->kvec[0].iov_base + txb->offset,
@@ -371,6 +371,7 @@ static int rxrpc_send_data(struct rxrpc_sock *rx,
 			txb->len += copy;
 			txb->offset += copy;
 			copied += copy;
+			len -= copy;
 			if (call->tx_total_len != -1)
 				call->tx_total_len -= copy;
 		}
@@ -382,8 +383,8 @@ static int rxrpc_send_data(struct rxrpc_sock *rx,
 
 		/* add the packet to the send queue if it's now full */
 		if (!txb->space ||
-		    (msg_data_left(msg) == 0 && !more)) {
-			if (msg_data_left(msg) == 0 && !more)
+		    (len == 0 && !more)) {
+			if (len == 0 && !more)
 				txb->flags |= RXRPC_LAST_PACKET;
 			else if (call->tx_top - call->acks_hard_ack <
 				 call->tx_winsize)
@@ -398,7 +399,7 @@ static int rxrpc_send_data(struct rxrpc_sock *rx,
 			rxrpc_queue_packet(rx, call, txb, notify_end_tx);
 			call->tx_pending = NULL;
 		}
-	} while (msg_data_left(msg) > 0);
+	} while (len > 0 && msg_data_left(msg) > 0);
 
 success:
 	ret = copied;
Signature · 1 line
2.53.0
author maintainer
#503 lore raw

PATCH 499/816 irqchip/mst-intc: Validate the DT interrupt range

In reply to Greg Kroah-Hartman

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

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

From: Pengpeng Hou <[email protected]>

[ Upstream commit 16f25d326e5d3b9fd51bc5e3916ecbffbca63e7b ]

The driver takes an inclusive interrupt range from the device tree without checking its endpoints. A reversed range wraps the unsigned count calculation, and a range larger than MST_INTC_MAX_IRQS exceeds the controller capacity used by the driver.

Reject these ranges before calculating nr_irqs or creating the domain. Check the difference after ordering the endpoints so the validation itself cannot wrap.

The issue was found by our static-analysis tool.

Fixes ad4c938c92af ("irqchip/irq-mst: Add MStar interrupt controller support")
Assisted-by gpt 5
[ sashal: kept the branch's kzalloc(sizeof(*cd), GFP_KERNEL) allocation line instead of upstream's kzalloc_obj(*cd) as the patch context. ]
---
 drivers/irqchip/irq-mst-intc.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/irqchip/irq-mst-intc.c +3 -0
index d771eb0346128..be6e37badb359 100644
@@ -263,6 +263,9 @@ static int __init mst_intc_of_init(struct device_node *dn,
 	    of_property_read_u32_index(dn, "mstar,irqs-map-range", 1, &irq_end))
 		return -EINVAL;
 
+	if (irq_end < irq_start || irq_end - irq_start >= MST_INTC_MAX_IRQS)
+		return -EINVAL;
+
 	cd = kzalloc(sizeof(*cd), GFP_KERNEL);
 	if (!cd)
 		return -ENOMEM;
Signature · 1 line
2.53.0
author maintainer
#504 lore raw

PATCH 500/816 ASoC: rt5645: Shut down the button timer on removal

In reply to Greg Kroah-Hartman

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

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

From: Myeonghun Pak <[email protected]>

[ Upstream commit f0ecc305442f20a6df2575943e9897825d80cc5d ]

jack_detect_work can rearm btn_check_timer, and the timer callback can queue jack_detect_work. Deleting the timer before cancelling the work does not break this cycle: an already running worker can rearm the timer after timer_delete_sync() returns. The timer can then outlive removal.

Use timer_shutdown_sync() before cancelling the delayed work so that subsequent attempts to rearm the timer are ignored. The IRQ producer has already been removed at this point. Keep the restartable timer deletion in the suspend path.

This issue was identified as part of our ongoing research while reviewing kernel code.

Fixes 7ff6319e7da5 ("ASoC: rt5645: use polling to support HS button")
Assisted-by LLM
[ sashal: Replaced del_timer_sync() with the older name in context, since the timer_delete_sync rename isn't present, while using timer_shutdown_sync() as upstream does. ]
---
 sound/soc/codecs/rt5645.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
sound/soc/codecs/rt5645.c +4 -3
index a7ac9971ae244..c963262056a71 100644
@@ -18,6 +18,7 @@
 #include <linux/acpi.h>
 #include <linux/dmi.h>
 #include <linux/regulator/consumer.h>
+#include <linux/timer.h>
 #include <sound/core.h>
 #include <sound/pcm.h>
 #include <sound/pcm_params.h>
@@ -4287,10 +4288,10 @@ static void rt5645_i2c_remove(struct i2c_client *i2c)
 		free_irq(i2c->irq, rt5645);
 
 	/*
-	 * Since the rt5645_btn_check_callback() can queue jack_detect_work,
-	 * the timer need to be delted first
+	 * The timer and jack_detect_work can rearm each other. Shut down the
+	 * timer before cancelling the work.
 	 */
-	del_timer_sync(&rt5645->btn_check_timer);
+	timer_shutdown_sync(&rt5645->btn_check_timer);
 
 	cancel_delayed_work_sync(&rt5645->jack_detect_work);
 	cancel_delayed_work_sync(&rt5645->rcclock_work);
Signature · 1 line
2.53.0
author maintainer
#505 lore raw

PATCH 501/816 ublk: use global index for reported zones

In reply to Greg Kroah-Hartman

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

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

From: Li RongQing <[email protected]>

[ Upstream commit 80897c7e5ae5c56f37a2eb004328edcb4da7cdd1 ]

ublk_report_zones() may split a zone report into multiple requests when the number of zones exceeds the temporary buffer capacity. The index passed to disk_report_zone() must refer to the zone position in the whole report, rather than the position within the current request.

Currently, the per-request loop index is used as the callback index, causing each chunk after the first one to restart from zero. This can make userspace callbacks receive duplicate zone indices and may result in blk_revalidate_disk_zones() updating incorrect entries in its zone state array.

Use the number of zones already reported as the base index for each request so that zone indices remain continuous across all chunks.

Fixes 29802d7ca33b ("ublk: enable zoned storage support")
[ sashal: Replaced the per-chunk loop index with done_zones in the zone callback, keeping this tree's cb(zone, done_zones, data) form because disk_report_zone() doesn't exist here. ]
---
 drivers/block/ublk_drv.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/block/ublk_drv.c +1 -1
index ae954ee1e3529..443054f89244f 100644
@@ -371,7 +371,7 @@ static int ublk_report_zones(struct gendisk *disk, sector_t sector,
 			if (!zone->len)
 				break;
 
-			ret = cb(zone, i, data);
+			ret = cb(zone, done_zones, data);
 			if (ret)
 				goto out;
 
Signature · 1 line
2.53.0
author maintainer
#506 lore raw

PATCH 502/816 tcp: use the echoed source route in cookie_v4_check()

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit 54d574d4afd9de820c8a017665c8095f0f5fdbaa ]

When the ACK carries a source route option, cookie_v4_check() routes the new socket to opt->faddr, where opt points to the options of the received packet.

ip_options_compile() only fills faddr for options given by setsockopt() (when called without an skb), so on receive faddr is 0 and the lookup is done for daddr 0, which gives a local route.

Use the options echoed by tcp_v4_save_options() instead, as inet_csk_route_req() and inet_csk_route_child_sock() do with ireq->ireq_opt. Read them after security_inet_conn_request(), since CIPSO can replace ireq->ireq_opt there.

The route now goes to the first hop of the source route, so also refuse a strict source route through a gateway, as inet_csk_route_req() does.

Found by sashiko while reviewing the sk_mc_loop() fix.

Fixes 1da177e4c3f4 ("Linux-2.6.12-rc2")
[ sashal: adjusted the conflict context in cookie_v4_check(): dropped the missing treq local from the declarations and kept sk->sk_uid instead of the sk_uid(sk) helper. ]
---
 net/ipv4/syncookies.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
net/ipv4/syncookies.c +10 -2
index 43cf33f282c15..8177725e9dd22 100644
@@ -404,11 +404,11 @@ static struct request_sock *cookie_tcp_check(struct net *net, struct sock *sk,
  */
 struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb)
 {
-	struct ip_options *opt = &TCP_SKB_CB(skb)->header.h4.opt;
 	const struct tcphdr *th = tcp_hdr(skb);
 	struct tcp_sock *tp = tcp_sk(sk);
 	struct inet_request_sock *ireq;
 	struct net *net = sock_net(sk);
+	struct ip_options_rcu *opt;
 	struct request_sock *req;
 	struct sock *ret = sk;
 	struct flowi4 fl4;
@@ -447,6 +447,8 @@ struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb)
 		SKB_DR_SET(reason, SECURITY_HOOK);
 		goto out_free;
 	}
+	/* Load ireq->ireq_opt after the LSM hook, which can replace it. */
+	opt = rcu_dereference_protected(ireq->ireq_opt, true);
 
 	tcp_ao_syncookie(sk, skb, req, AF_INET);
 
@@ -459,7 +461,7 @@ struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb)
 	flowi4_init_output(&fl4, ireq->ir_iif, ireq->ir_mark,
 			   ip_sock_rt_tos(sk), ip_sock_rt_scope(sk),
 			   IPPROTO_TCP, inet_sk_flowi_flags(sk),
-			   opt->srr ? opt->faddr : ireq->ir_rmt_addr,
+			   (opt && opt->opt.srr) ? opt->opt.faddr : ireq->ir_rmt_addr,
 			   ireq->ir_loc_addr, th->source, th->dest, sk->sk_uid);
 	security_req_classify_flow(req, flowi4_to_flowi_common(&fl4));
 	rt = ip_route_output_key(net, &fl4);
@@ -467,6 +469,12 @@ struct sock *cookie_v4_check(struct sock *sk, struct sk_buff *skb)
 		SKB_DR_SET(reason, IP_OUTNOROUTES);
 		goto out_free;
 	}
+	/* Same check as in inet_csk_route_req(). */
+	if (opt && opt->opt.is_strictroute && rt->rt_uses_gateway) {
+		ip_rt_put(rt);
+		SKB_DR_SET(reason, IP_OUTNOROUTES);
+		goto out_free;
+	}
 
 	/* Try to redo what tcp_v4_send_synack did. */
 	req->rsk_window_clamp = READ_ONCE(tp->window_clamp) ? :
Signature · 1 line
2.53.0
author maintainer
#507 lore raw

PATCH 503/816 pinctrl: stm32: Fix the unit of the hwspinlock timeout

In reply to Greg Kroah-Hartman

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

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

From: Ju Nan <[email protected]>

[ Upstream commit 544b3f8042dd7c18baa48dcb1a393ff8b6742322 ]

HWSPNLCK_TIMEOUT is passed to hwspin_lock_timeout_in_atomic(), whose timeout argument is in milliseconds, not microseconds:

  atomic_delay += HWSPINLOCK_RETRY_DELAY_US;
  if (atomic_delay > to * 1000)
          return -ETIMEDOUT;

The hwspinlock core documents this explicitly:

If the mode is HWLOCK_IN_ATOMIC (called from an atomic context) the timeout is handled with busy-waiting delays, hence shall not exceed few msecs.

Fixes 290a9f937e5a ("pinctrl: stm32: use the hwspin_lock_timeout_in_atomic() API")
[ sashal: Dropped the two hunks for stm32_pconf_set_advcfgr() and stm32_pconf_set_skew_delay(), which don't exist here, and adjusted context to rename the macro at the five remaining call sites. ]
---
 drivers/pinctrl/stm32/pinctrl-stm32.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
drivers/pinctrl/stm32/pinctrl-stm32.c +6 -6
index 9e8b8b82c232b..06431e55fa615 100644
@@ -68,7 +68,7 @@
 #define gpio_range_to_bank(chip) \
 		container_of(chip, struct stm32_gpio_bank, range)
 
-#define HWSPNLCK_TIMEOUT	1000 /* usec */
+#define HWSPNLCK_TIMEOUT_MS	1
 
 static const char * const stm32_gpio_functions[] = {
 	"gpio", "af0", "af1",
@@ -436,7 +436,7 @@ static int stm32_gpio_domain_activate(struct irq_domain *d,
 
 	if (pctl->hwlock) {
 		ret = hwspin_lock_timeout_in_atomic(pctl->hwlock,
-						    HWSPNLCK_TIMEOUT);
+						    HWSPNLCK_TIMEOUT_MS);
 		if (ret) {
 			dev_err(pctl->dev, "Can't get hwspinlock\n");
 			return ret;
@@ -770,7 +770,7 @@ static int stm32_pmx_set_mode(struct stm32_gpio_bank *bank,
 
 	if (pctl->hwlock) {
 		err = hwspin_lock_timeout_in_atomic(pctl->hwlock,
-						    HWSPNLCK_TIMEOUT);
+						    HWSPNLCK_TIMEOUT_MS);
 		if (err) {
 			dev_err(pctl->dev, "Can't get hwspinlock\n");
 			goto unlock;
@@ -902,7 +902,7 @@ static int stm32_pconf_set_driving(struct stm32_gpio_bank *bank,
 
 	if (pctl->hwlock) {
 		err = hwspin_lock_timeout_in_atomic(pctl->hwlock,
-						    HWSPNLCK_TIMEOUT);
+						    HWSPNLCK_TIMEOUT_MS);
 		if (err) {
 			dev_err(pctl->dev, "Can't get hwspinlock\n");
 			goto unlock;
@@ -953,7 +953,7 @@ static int stm32_pconf_set_speed(struct stm32_gpio_bank *bank,
 
 	if (pctl->hwlock) {
 		err = hwspin_lock_timeout_in_atomic(pctl->hwlock,
-						    HWSPNLCK_TIMEOUT);
+						    HWSPNLCK_TIMEOUT_MS);
 		if (err) {
 			dev_err(pctl->dev, "Can't get hwspinlock\n");
 			goto unlock;
@@ -1004,7 +1004,7 @@ static int stm32_pconf_set_bias(struct stm32_gpio_bank *bank,
 
 	if (pctl->hwlock) {
 		err = hwspin_lock_timeout_in_atomic(pctl->hwlock,
-						    HWSPNLCK_TIMEOUT);
+						    HWSPNLCK_TIMEOUT_MS);
 		if (err) {
 			dev_err(pctl->dev, "Can't get hwspinlock\n");
 			goto unlock;
Signature · 1 line
2.53.0
author maintainer
#508 lore raw

PATCH 504/816 ALSA: hda/realtek: Fix hiss/crackle on Lenovo Xiaoxin 14 GT (17aa:3912)

In reply to Greg Kroah-Hartman

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

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

From: Viktor Menshin <[email protected]>

[ Upstream commit 2fc28b1186d6fce8b046e6118072cf3ca32f2960 ]

Commit 3a3e810e9108 ("ALSA: hda/realtek: Add quirk for Lenovo Xiaoxin 14 GT") added a quirk mapping SSID 17aa:3912 to ALC287_FIXUP_YOGA9_14IAP7_BASS_SPK_PIN, chosen by analogy with neighboring SSIDs (0x390d, 0x3911, 0x391a) without being verified on hardware, as noted in that commit's own message.

I have since tested it on the actual hardware (Lenovo Xiaoxin Pro 14 ASP10, same 17aa:3912 SSID) and confirmed it does not fix the reported issue. ALC287_FIXUP_YOGA9_14IAP7_BASS_SPK_PIN only repoints pin 0x17 and the preferred DAC pairs for the bass speaker; it does not touch the codec's vendor processing coefficients. The actual symptom - constant electrical hiss/crackle on both the headphone jack and the internal speakers, independent of volume - is unrelated to pin/DAC routing and is also present on stock Windows before the Realtek driver is installed, which points at those coefficients being left at their power-on default.

To find the correct values, I passed the physical HD Audio controller through to a Windows 10 VM (VFIO, with QEMU patched to log CORB verb traffic) and captured the coefficient writes the vendor Realtek driver performs at init. Replaying a single one of them on Linux via hda-verb reproducibly eliminates the headphone jack noise:

    hda-verb /dev/snd/hwC#D0 0x20 SET_COEF_INDEX 0x36
    hda-verb /dev/snd/hwC#D0 0x20 SET_PROC_COEF  0x77d7

This has held up across reboots and kernel updates for several weeks (applied via a small systemd oneshot unit while testing).

Add a dedicated fixup that performs this coefficient write and chains it with the existing ALC287_FIXUP_YOGA9_14IAP7_BASS_SPK_PIN (which may still be relevant for the bass speaker pin wiring on this board), and point the 17aa:3912 quirk entry at it instead.

Honesty note: this fixes the headphone jack. The internal speakers still have noise under certain conditions (notably worse on AC power) that I have not been able to isolate via coefficient-table replay; that part remains open. Sending what is verified to work rather than holding this back.

Fixes 3a3e810e9108 ("ALSA: hda/realtek: Add quirk for Lenovo Xiaoxin 14 GT")
[ sashal: Moved the new function to sit before alc295_fixup_dell_inspiron_top_speakers() since the upstream anchor is missing, and applied the edits to patch_realtek.c with adjusted context. ]
---
 sound/pci/hda/patch_realtek.c | 31 ++++++++++++++++++++++++++++++-
 1 file changed, 30 insertions(+), 1 deletion(-)
sound/pci/hda/patch_realtek.c +30 -1
index b18eb7974c8eb..726fc58b17ee7 100644
@@ -7718,6 +7718,28 @@ static void alc287_fixup_yoga9_14iap7_bass_spk_pin(struct hda_codec *codec,
 	}
 }
 
+/*
+ * The Lenovo Xiaoxin 14 GT (SSID 17aa:3912) uses the same bass-speaker
+ * pin wiring as its 0x390d/0x3911/0x391a siblings, but on this board the
+ * codec's vendor processing coefficients (node 0x20) are left at their
+ * power-on default instead of being programmed the way the vendor
+ * (Windows) driver programs them. That leaves audible hiss/crackle on
+ * both the headphone jack and the internal speakers, independent of
+ * volume, regardless of which pin/DAC routing is used.
+ *
+ * This single coefficient write was captured from the vendor driver's
+ * own init sequence (via a VFIO pass-through of the physical codec to a
+ * Windows VM) and confirmed to eliminate the headphone jack noise.
+ */
+static void alc287_fixup_lenovo_xiaoxin_14gt_hp_noise(struct hda_codec *codec,
+						       const struct hda_fixup *fix, int action)
+{
+	if (action != HDA_FIXUP_ACT_INIT)
+		return;
+
+	alc_write_coef_idx(codec, 0x36, 0x77d7);
+}
+
 static void alc295_fixup_dell_inspiron_top_speakers(struct hda_codec *codec,
 					  const struct hda_fixup *fix, int action)
 {
@@ -8225,6 +8247,7 @@ enum {
 	ALC287_FIXUP_YOGA9_14IAP7_BASS_SPK,
 	ALC287_FIXUP_YOGA9_14IAP7_BASS_SPK_PIN,
 	ALC287_FIXUP_YOGA9_14IMH9_BASS_SPK_PIN,
+	ALC287_FIXUP_LENOVO_XIAOXIN_14GT_HP_NOISE,
 	ALC295_FIXUP_DELL_INSPIRON_TOP_SPEAKERS,
 	ALC236_FIXUP_DELL_DUAL_CODECS,
 	ALC287_FIXUP_CS35L41_I2C_2_THINKPAD_ACPI,
@@ -10552,6 +10575,12 @@ static const struct hda_fixup alc269_fixups[] = {
 		.chained = true,
 		.chain_id = ALC287_FIXUP_CS35L41_I2C_2,
 	},
+	[ALC287_FIXUP_LENOVO_XIAOXIN_14GT_HP_NOISE] = {
+		.type = HDA_FIXUP_FUNC,
+		.v.func = alc287_fixup_lenovo_xiaoxin_14gt_hp_noise,
+		.chained = true,
+		.chain_id = ALC287_FIXUP_YOGA9_14IAP7_BASS_SPK_PIN,
+	},
 	[ALC295_FIXUP_DELL_INSPIRON_TOP_SPEAKERS] = {
 		.type = HDA_FIXUP_FUNC,
 		.v.func = alc295_fixup_dell_inspiron_top_speakers,
@@ -11707,7 +11736,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = {
 	SND_PCI_QUIRK(0x17aa, 0x3902, "Lenovo E50-80", ALC269_FIXUP_DMIC_THINKPAD_ACPI),
 	SND_PCI_QUIRK(0x17aa, 0x390d, "Lenovo Yoga Pro 7 14ASP10", ALC287_FIXUP_YOGA9_14IAP7_BASS_SPK_PIN),
 	SND_PCI_QUIRK(0x17aa, 0x3911, "Lenovo Yoga Pro 7 14IAH10", ALC287_FIXUP_YOGA9_14IAP7_BASS_SPK_PIN),
-	SND_PCI_QUIRK(0x17aa, 0x3912, "Lenovo Xiaoxin 14 GT", ALC287_FIXUP_YOGA9_14IAP7_BASS_SPK_PIN),
+	SND_PCI_QUIRK(0x17aa, 0x3912, "Lenovo Xiaoxin 14 GT", ALC287_FIXUP_LENOVO_XIAOXIN_14GT_HP_NOISE),
 	SND_PCI_QUIRK(0x17aa, 0x3913, "Lenovo 145", ALC236_FIXUP_LENOVO_INV_DMIC),
 	SND_PCI_QUIRK(0x17aa, 0x391f, "Yoga S990-16 pro Quad YC Quad", ALC287_FIXUP_TAS2781_I2C),
 	SND_PCI_QUIRK(0x17aa, 0x3920, "Yoga S990-16 pro Quad VECO Quad", ALC287_FIXUP_TAS2781_I2C),
Signature · 1 line
2.53.0
author maintainer
#509 lore raw

PATCH 505/816 bpf: Use the frame mem type in devmap egress XDP

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit b3ca872947ef322c475ceaa7a76a9ebb3356152e ]

A devmap egress program that removes a whole fragment of a redirected xdp_frame with bpf_xdp_adjust_tail() or bpf_xdp_pull_data() frees it with page_frag_free() whatever the frame's memory type is. For a MEM_TYPE_PAGE_POOL frame from a page_pool based driver this drops the page reference owned by the pool while the pool still accounts the fragment ("page_pool leak" bad page, leaked pp reference).

kernel/bpf/devmap.c:dev_map_bpf_prog_run() points xdp.rxq at an on-stack

    struct xdp_rxq_info rxq = { .dev = rx_dev };

whose mem.type is 0, i.e. MEM_TYPE_PAGE_SHARED, and net/core/filter.c:bpf_xdp_shrink_data() releases frags according to rxq->mem.type. cpumap, which runs programs on xdp_frames the same way, already copies xdpf->mem_type into its private rxq for each frame.

With 9000 byte frames from virtio_net and an egress program that cuts the fragments off:

  BUG: Bad page state in process swapper/3  pfn:10660b
  page dumped because: page_pool leak
   bad_page+0xbd/0x190
   __free_frozen_pages+0x5c7/0x900
   bpf_xdp_adjust_tail+0x3be/0x480
   bpf_prog_dad43f894a3faff7_egress+0x15c/0x1cd
   dev_map_bpf_prog_run+0x288/0x610

The pool waits for these pages for ever when its device is gone. That is the harmless case. A page of the pool can hold more than one fragment while its refcount is 1: the first page_frag_free() frees it under the fragment which is still in use, and the second one runs into

  page dumped because: VM_BUG_ON_PAGE(page_ref_count(page) == 0)
  kernel BUG at include/linux/mm.h:1846!

veth is not affected. It takes references of its own on the pages and redirects the frame as MEM_TYPE_PAGE_SHARED.

Fix by setting rxq.mem.type from each frame before running the devmap program, as cpu_map_bpf_prog_run_xdp() does.

Fixes ca9984c5f0ab ("bpf: devmap: provide rxq after redirect")
[ sashal: Changed rxq.mem.type = xdpf->mem_type; to rxq.mem = xdpf->mem; because this tree's xdp_frame has a struct xdp_mem_info mem member instead of a flat mem_type field. ]
---
 kernel/bpf/devmap.c | 1 +
 1 file changed, 1 insertion(+)
kernel/bpf/devmap.c +1 -0
index 1c64c4cff41ec..368c9d50aa8bb 100644
@@ -348,6 +348,7 @@ static int dev_map_bpf_prog_run(struct bpf_prog *xdp_prog,
 
 		xdp_convert_frame_to_buff(xdpf, &xdp);
 		xdp.txq = &txq;
+		rxq.mem = xdpf->mem;
 		xdp.rxq = &rxq;
 
 		act = bpf_prog_run_xdp(xdp_prog, &xdp);
Signature · 1 line
2.53.0
author maintainer
#510 lore raw

PATCH 506/816 bpf: Dont hand out a linked element as extra element

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit ccb88db8dac8fabde58656d5d4a33711e89c480a ]

When htab_map_update_elem() replaces an element of a preallocated map, alloc_htab_elem() takes the spare element of this cpu and puts the old element into the per-cpu slot right away, long before the old element is unlinked from its bucket. The bucket lock disables interrupts, but it does not keep out an NMI, or a tracing program on the return of alloc_htab_elem(). bpf_prog_active only helps if both programs are kprobe, tracepoint or perf_event programs. A program that updates an existing key in another bucket of the same map gets to use the slot:

htab_map_update_elem(k1) tc, xdp, fentry, raw_tp, ...
alloc_htab_elem()
l_new = *pl_new
*pl_new = l_old still linked in bucket 1
<NMI>
htab_map_update_elem(k2) perf_event program
l_new = *pl_new the l_old of the outer update
hlist_nulls_add_head_rcu(l_new, bucket 2) hlist_nulls_del_rcu(k2's old element)
</NMI>
hlist_nulls_add_head_rcu(l_new, bucket 1) hlist_nulls_del_rcu(l_old)

If l_old was the first element of bucket 1, the outer add points its pprev at l_new, and the delete takes it out of bucket 1 only. l_new->next now leads into bucket 2, where l_old stays with a poisoned pprev, on which a delete of k2 crashes. If it was not the first, the delete takes it out of bucket 2: k2 is gone from the map, and the chain of bucket 1 still contains l_old, whose next pointer leads into bucket 2.

Either way a walk of bucket 1 ends on the nulls value of bucket 2. lookup_nulls_elem_raw() restarts whenever that happens, so every lookup in bucket 1 which does not find its key spins forever:

  rcu: INFO: rcu_preempt detected stalls on CPUs/tasks:
   __htab_map_lookup_elem+0x354/0x4d0

  BUG: KASAN: wild-memory-access in htab_map_delete_elem+0x30c/0x670
  Write of size 8 at addr dead000000000122 by task extra/102

An NMI between the load and the store of the slot makes both updates use the same element, with much the same result.

Empty the slot when the spare element is taken, in a way that is atomic on this cpu, and put the old element in only after it has been unlinked and its timers and the like have been cancelled. A nested update that finds the slot empty, which is the case that corrupted the map, fails with -EBUSY.

Fixes 8c290e60fa2a ("bpf: fix hashmap extra_elems logic")
[ sashal: Context lines adapted to the older tree (check_and_free_fields, old_map_ptr handling, four-argument htab_unlock_bucket), with fix lines identical to upstream. ]
---
 kernel/bpf/hashtab.c | 23 ++++++++++++++++-------
 1 file changed, 16 insertions(+), 7 deletions(-)
kernel/bpf/hashtab.c +16 -7
index 98308f3a7f6e9..a6ffc4a8dc43f 100644
@@ -1114,11 +1114,17 @@ static struct htab_elem *alloc_htab_elem(struct bpf_htab *htab, void *key,
 	if (prealloc) {
 		if (old_elem) {
 			/* if we're updating the existing element,
-			 * use per-cpu extra elems to avoid freelist_pop/push
+			 * use per-cpu extra elems to avoid freelist_pop/push.
+			 * The caller puts old_elem into the slot once it is
+			 * unlinked. Until then the slot is empty for an NMI
+			 * or a kprobe that updates this map on this cpu.
 			 */
 			pl_new = this_cpu_ptr(htab->extra_elems);
-			l_new = *pl_new;
-			*pl_new = old_elem;
+			l_new = READ_ONCE(*pl_new);
+			do {
+				if (!l_new)
+					return ERR_PTR(-EBUSY);
+			} while (!try_cmpxchg_local(pl_new, &l_new, NULL));
 		} else {
 			struct pcpu_freelist_node *l;
 
@@ -1281,16 +1287,19 @@ static long htab_map_update_elem(struct bpf_map *map, void *key, void *value,
 	if (l_old) {
 		hlist_nulls_del_rcu(&l_old->hash_node);
 
-		/* l_old has already been stashed in htab->extra_elems, free
-		 * its special fields before it is available for reuse. Also
-		 * save the old map pointer in htab of maps before unlock
-		 * and release it after unlock.
+		/*
+		 * l_old replaces the extra element that alloc_htab_elem() took.
+		 * Free its special fields first: once it is in the slot, the
+		 * next update on this cpu can reuse it. Also save the old map
+		 * pointer in htab of maps before unlock and release it after
+		 * unlock.
 		 */
 		old_map_ptr = NULL;
 		if (htab_is_prealloc(htab)) {
 			if (map->ops->map_fd_put_ptr)
 				old_map_ptr = fd_htab_map_get_ptr(map, l_old);
 			check_and_free_fields(htab, l_old);
+			WRITE_ONCE(*this_cpu_ptr(htab->extra_elems), l_old);
 		}
 	}
 	htab_unlock_bucket(htab, b, hash, flags);
Signature · 1 line
2.53.0
author maintainer
#511 lore raw

PATCH 507/816 bpf: Keep a program until its bpf_wq callback has ended

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 1e28a5e52d32b7d3f4c9fb24898774f941166d2b ]

bpf_wq_work() runs the callback under rcu_read_lock_trace() only, since the callback may sleep. The program it belongs to need not be sleepable, and such a program is freed behind a plain RCU grace period. The reference that the bpf_wq holds is dropped when the map element goes, or when another callback is set, no matter whether the work is running.

If that was the last reference the program is freed under the running callback, and the worker goes on in the freed JIT image:

  Oops: int3: 0000 [#1] SMP NOPTI
  RIP: 0010:0xffffffffc0600947

All it takes is to close the map and the program while the callback runs.

Note in the program that it has a callback that runs sleepable, and wait for an RCU Tasks Trace grace period, which implies a plain one, before such a program is freed. Let bpf_wq_work() enter its read side critical section before it reads callback_fn.

bpf_task_work holds a reference to the program until the callback is done.

Fixes 8e83da9732d9 ("bpf: add bpf_wq_start")
[ sashal: Replaced the nonexistent is_async_cb_sleepable() call with is_bpf_wq_set_callback_impl_kfunc(insn->imm), and dropped the tramp_linked and rcu_tasks free-path hunk that this tree lacks. ]
---
 include/linux/bpf.h   | 10 ++++++++++
 kernel/bpf/helpers.c  |  9 ++++++---
 kernel/bpf/syscall.c  |  2 +-
 kernel/bpf/verifier.c |  2 ++
 4 files changed, 19 insertions(+), 4 deletions(-)
include/linux/bpf.h +10 -0
index 59661363d08f6..98f816a37d3be 100644
@@ -1508,6 +1508,7 @@ struct bpf_prog_aux {
 	bool offload_requested; /* Program is bound and offloaded to the netdev. */
 	bool attach_btf_trace; /* true if attaching to BTF-enabled raw tp */
 	bool attach_tracing_prog; /* true if tracing another tracing program */
+	bool sleepable_async_cb; /* has a bpf_wq or bpf_task_work callback */
 	bool func_proto_unreliable;
 	bool tail_call_reachable;
 	bool xdp_has_frags;
@@ -1619,6 +1620,15 @@ struct bpf_prog {
 	};
 };
 
+/*
+ * Does the program, or a callback of it, run under RCU Tasks Trace protection
+ * only, outside of any RCU read side critical section?
+ */
+static inline bool bpf_prog_runs_sleepable(const struct bpf_prog *prog)
+{
+	return prog->sleepable || prog->aux->sleepable_async_cb;
+}
+
 struct bpf_array_aux {
 	/* Programs with direct jumps into programs part of this array. */
 	struct list_head poke_progs;
kernel/bpf/helpers.c +6 -3
index bcb2770efac4d..7ae6acfc14d36 100644
@@ -1209,9 +1209,12 @@ static void bpf_wq_work(struct work_struct *work)
 
 	BTF_TYPE_EMIT(struct bpf_wq);
 
+	/* keeps the program that callback_fn belongs to */
+	rcu_read_lock_trace();
+
 	callback_fn = READ_ONCE(cb->callback_fn);
 	if (!callback_fn)
-		return;
+		goto out;
 
 	if (map->map_type == BPF_MAP_TYPE_ARRAY) {
 		struct bpf_array *array = container_of(map, struct bpf_array, map);
@@ -1223,12 +1226,12 @@ static void bpf_wq_work(struct work_struct *work)
 		key = value - round_up(map->key_size, 8);
 	}
 
-        rcu_read_lock_trace();
-        migrate_disable();
+	migrate_disable();
 
 	callback_fn((u64)(long)map, (u64)(long)key, (u64)(long)value, 0, 0);
 
 	migrate_enable();
+out:
 	rcu_read_unlock_trace();
 }
 
kernel/bpf/syscall.c +1 -1
index cbdea70fd93a3..3e084cf77d134 100644
@@ -2212,7 +2212,7 @@ static void __bpf_prog_put_noref(struct bpf_prog *prog, bool deferred)
 		btf_put(prog->aux->attach_btf);
 
 	if (deferred) {
-		if (prog->sleepable)
+		if (bpf_prog_runs_sleepable(prog))
 			call_rcu_tasks_trace(&prog->aux->rcu, __bpf_prog_put_rcu);
 		else
 			call_rcu(&prog->aux->rcu, __bpf_prog_put_rcu);
kernel/bpf/verifier.c +2 -0
index ffd1f13925c29..d8317cef6e8ab 100644
@@ -10174,6 +10174,8 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
 					 is_bpf_wq_set_callback_impl_kfunc(insn->imm));
 		if (IS_ERR(async_cb))
 			return PTR_ERR(async_cb);
+		if (is_bpf_wq_set_callback_impl_kfunc(insn->imm))
+			env->prog->aux->sleepable_async_cb = true;
 		callee = async_cb->frame[0];
 		callee->async_entry_cnt = state->frame[0]->async_entry_cnt + 1;
 
Signature · 1 line
2.53.0
author maintainer
#512 lore raw

PATCH 508/816 bpf: Count sleepable callbacks as sleepable map users

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 927c9c985f3ef4d30c086884b7e0ecb933f742ef ]

map->sleepable_refcnt tells bpf_map_fd_put_ptr() whether an inner map that is taken out of its outer map has to wait for an RCU Tasks Trace grace period as well. It counts the sleepable programs that use the outer map. The bpf_wq or bpf_task_work callback of a program that is not sleepable runs under rcu_read_lock_trace() only, and is not counted.

Such a callback can look an inner map up and keep it while user space deletes it from the outer map. The inner map is freed behind a plain RCU grace period, under the callback:

  BUG: KASAN: slab-use-after-free in array_map_update_elem+0x6bc/0x7d0

Count a program with such a callback. The maps are bound before the verifier meets the callback, so raise the count of those that are bound when it does.

Fixes 8e83da9732d9 ("bpf: add bpf_wq_start")
[ sashal: Adapted to missing helpers by keeping the local is_bpf_wq_set_callback_impl_kfunc() check and is_may_goto_insn() name, and by editing add_used_map_from_fd() without the check_map_prog_compatibility() context. ]
---
 kernel/bpf/core.c     |  2 +-
 kernel/bpf/syscall.c  |  2 +-
 kernel/bpf/verifier.c | 17 +++++++++++++++--
 3 files changed, 17 insertions(+), 4 deletions(-)
kernel/bpf/core.c +1 -1
index df529db44f35c..de2c0ffb30252 100644
@@ -2873,7 +2873,7 @@ void __bpf_free_used_maps(struct bpf_prog_aux *aux,
 	bool sleepable;
 	u32 i;
 
-	sleepable = aux->prog->sleepable;
+	sleepable = bpf_prog_runs_sleepable(aux->prog);
 	for (i = 0; i < len; i++) {
 		map = used_maps[i];
 		if (map->ops->map_poke_untrack)
kernel/bpf/syscall.c +1 -1
index 3e084cf77d134..8fd823047c3a0 100644
@@ -5754,7 +5754,7 @@ static int bpf_prog_bind_map(union bpf_attr *attr)
 	/* The bpf program will not access the bpf map, but for the sake of
 	 * simplicity, increase sleepable_refcnt for sleepable program as well.
 	 */
-	if (prog->sleepable)
+	if (bpf_prog_runs_sleepable(prog))
 		atomic64_inc(&map->sleepable_refcnt);
 	memcpy(used_maps_new, used_maps_old,
 	       sizeof(used_maps_old[0]) * prog->aux->used_map_cnt);
kernel/bpf/verifier.c +15 -2
index d8317cef6e8ab..1404e842580ba 100644
@@ -547,6 +547,19 @@ static bool is_async_callback_calling_insn(struct bpf_insn *insn)
 	       (bpf_pseudo_kfunc_call(insn) && is_async_callback_calling_kfunc(insn->imm));
 }
 
+/* From here on the maps of the program count it as a sleepable user. */
+static void mark_sleepable_async_cb(struct bpf_verifier_env *env)
+{
+	int i;
+
+	if (bpf_prog_runs_sleepable(env->prog))
+		return;
+
+	env->prog->aux->sleepable_async_cb = true;
+	for (i = 0; i < env->used_map_cnt; i++)
+		atomic64_inc(&env->used_maps[i]->sleepable_refcnt);
+}
+
 static bool is_may_goto_insn(struct bpf_insn *insn)
 {
 	return insn->code == (BPF_JMP | BPF_JCOND) && insn->src_reg == BPF_MAY_GOTO;
@@ -10175,7 +10188,7 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
 		if (IS_ERR(async_cb))
 			return PTR_ERR(async_cb);
 		if (is_bpf_wq_set_callback_impl_kfunc(insn->imm))
-			env->prog->aux->sleepable_async_cb = true;
+			mark_sleepable_async_cb(env);
 		callee = async_cb->frame[0];
 		callee->async_entry_cnt = state->frame[0]->async_entry_cnt + 1;
 
@@ -19651,7 +19664,7 @@ static int add_used_map_from_fd(struct bpf_verifier_env *env, int fd, bool *reus
 		return -E2BIG;
 	}
 
-	if (env->prog->sleepable)
+	if (bpf_prog_runs_sleepable(env->prog))
 		atomic64_inc(&map->sleepable_refcnt);
 
 	/* hold the map. If the program is rejected by verifier,
Signature · 1 line
2.53.0
author maintainer
#513 lore raw

PATCH 509/816 bpf: Assume no bounds for buffers behind a tail call

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 7fa323d77688e8b62b2f0bf6c3208a2c96d4a5e7 ]

The bpf_map_elem, bpf_sk_storage_map and sockmap iterators hand the key and the value of an element to the program as buffers. The verifier notes how far a program reaches into them, and the iterator compares that with the map when the program is attached. A program that does not touch the buffers passes. It can tail-call another program of the same target, which gets the same context, and whose reach nobody compares with the map:

  BUG: KASAN: slab-out-of-bounds in ___bpf_prog_run+0xa46a/0xae80

The program array can be filled at any time, so there is nothing to look at when the link is made. For the same reason a program with a tail call is taken to use the whole stack and the whole packet. Take it to reach as far as can be into the buffers as well, so that these iterators refuse it with -EACCES.

Fixes d6c4503cc296 ("bpf: Implement bpf iterator for hash maps")
Fixes 5ce6e77c7edf ("bpf: Implement bpf iterator for sock local storage map")
Fixes 0365351524d7 ("net: Allow iterating sockmap and sockhash")
[ sashal: Adapted the hunk to the older code layout, where the tail-call fixup lives in do_misc_fixups() in the verifier source, with the same two added lines. ]
---
 kernel/bpf/verifier.c | 2 ++
 1 file changed, 2 insertions(+)
kernel/bpf/verifier.c +2 -0
index 1404e842580ba..15a02a4c08d22 100644
@@ -21566,6 +21566,8 @@ static int do_misc_fixups(struct bpf_verifier_env *env)
 			if (!allow_tail_call_in_subprogs(env))
 				prog->aux->stack_depth = MAX_BPF_STACK;
 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
+			prog->aux->max_rdonly_access = U32_MAX;
+			prog->aux->max_rdwr_access = U32_MAX;
 
 			/* mark bpf_tail_call as different opcode to avoid
 			 * conditional branch in the interpreter for every normal
Signature · 1 line
2.53.0
author maintainer
#514 lore raw

PATCH 510/816 bpf: Assume no bounds for a writable tp with tail calls

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit cd0490e671d70326d70c7d36e82388939fd9b071 ]

A writable raw tracepoint hands a buffer to the program. The verifier notes how far the program reaches into it, and bpf_probe_register() refuses a program that reaches further than the tracepoint allows. A program that does not touch the buffer passes, and can tail-call one of its type that reads and writes behind it.

Take a BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE program with a tail call to reach as far as can be, as for the stack, the packet and the buffers of iterators. It cannot be attached any more. Plain raw tracepoint programs, for which the limit is zero, cannot get at the buffer, and a tail call stays within one type: they are left alone.

Fixes 9df1c28bb752 ("bpf: add writable context for raw tracepoints")
[ sashal: Moved the tail_call fixup hunk from fixups.c's bpf_do_misc_fixups() to verifier.c's do_misc_fixups(), since this tree has no fixups.c. ]
---
 kernel/bpf/verifier.c | 2 ++
 1 file changed, 2 insertions(+)
kernel/bpf/verifier.c +2 -0
index 15a02a4c08d22..34b82d3eff66f 100644
@@ -21568,6 +21568,8 @@ static int do_misc_fixups(struct bpf_verifier_env *env)
 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
 			prog->aux->max_rdonly_access = U32_MAX;
 			prog->aux->max_rdwr_access = U32_MAX;
+			if (prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE)
+				prog->aux->max_tp_access = U32_MAX;
 
 			/* mark bpf_tail_call as different opcode to avoid
 			 * conditional branch in the interpreter for every normal
Signature · 1 line
2.53.0
author maintainer
#515 lore raw

PATCH 511/816 bpf: Dont let an extension reach further into the context than its target

In reply to Greg Kroah-Hartman

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

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

From: Alexei Starovoitov <[email protected]>

[ Upstream commit fcbfa99aa657627528b75e7dc1023bcb0b84e558 ]

How large the context of a raw tracepoint, tracepoint or syscall program is depends on what the program is attached to, or is run with. bpf_probe_register(), perf_event_set_bpf_prog() and the test runs compare that with max_ctx_offset of the program.

An extension of the program, or of one of its global functions, gets the same context. How far it reaches is noted in its own max_ctx_offset, which nobody looks at. On a tracepoint with one argument it reads the stack behind the arguments, in a test run the memory behind the context, or from NULL if there is none:

  BUG: KASAN: stack-out-of-bounds in bpf_prog_954b5d2051843629_ts28_ext_far+0x7e/0x113
  Read of size 8 at addr ffffc90000def7b8 by task ts28/104

  BUG: KASAN: slab-out-of-bounds in bpf_prog_954b5d2051843629_ts28_ext_far+0x7e/0x113
  Read of size 8 at addr ffff88810712c3e8 by task ts28/104

Refuse to attach an extension that reaches further than the program which it extends. A program that leaves the context to its extensions has to touch as much of it as they do.

Fixes be8704ff07d2 ("bpf: Introduce dynamic program extensions")
[ sashal: Dropped the missing kprobe_write_ctx context block, so the new max_ctx_offset check for EXT programs is inserted after the trampoline/tgt_prog selection instead. ]
---
 kernel/bpf/syscall.c | 13 +++++++++++++
 1 file changed, 13 insertions(+)
kernel/bpf/syscall.c +13 -0
index 8fd823047c3a0..2626189f746ba 100644
@@ -3452,6 +3452,19 @@ static int bpf_tracing_prog_attach(struct bpf_prog *prog,
 		tr = prog->aux->dst_trampoline;
 		tgt_prog = prog->aux->dst_prog;
 	}
+	/*
+	 * The size of these contexts depends on what the program is attached
+	 * to, or run with. That is compared with max_ctx_offset of the program,
+	 * and nobody looks at the one of its extensions.
+	 */
+	if (prog->type == BPF_PROG_TYPE_EXT &&
+	    (tgt_prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT ||
+	     tgt_prog->type == BPF_PROG_TYPE_TRACEPOINT ||
+	     tgt_prog->type == BPF_PROG_TYPE_SYSCALL) &&
+	    prog->aux->max_ctx_offset > tgt_prog->aux->max_ctx_offset) {
+		err = -EINVAL;
+		goto out_unlock;
+	}
 
 	err = bpf_link_prime(&link->link.link, &link_primer);
 	if (err)
Signature · 1 line
2.53.0
author maintainer
#516 lore raw

PATCH 512/816 bpf, cpumap: Hold the device of frames in the queue

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit f99351272933ba2e1221484a5e53b7a5d2c035f0 ]

A frame that is redirected to another CPU waits in the queue of the cpumap entry with a plain pointer to the device it came from, and an skb from generic XDP with skb->dev. Nothing keeps that device. Closing and unregistering it waits for its NAPI and for RCU, but not for the kthread of the entry. If the kthread is late by more than that, since its CPU is busy with something of a higher priority, it builds skbs for a device that has been freed and hands them to the stack:

  BUG: KASAN: use-after-free in dev_gro_receive+0x1f51/0x2b30
  Read of size 8 at addr ffff88800a7340b0 by task cpumap/1/map:1/54

Take a reference to the device for each entry of the queue. The kthread cannot drop it at the end of the batch, since its GRO node may keep the skb for longer. Let it note the devices and drop the references behind a full GRO flush, which it does whenever the queue is empty, and from now on also when it has noted about 2048 of them.

A device whose frames are stuck in a queue is now unregistered only when the kthread has got to them. RTNL is not held meanwhile, but if the device goes with its network namespace, the cleanup of all namespaces waits.

Fixes 1c601d829ab0 ("bpf: cpumap xdp_buff to skb conversion and allocation")
Fixes 11941f8a8536 ("bpf: cpumap: Implement generic cpumap")
[ sashal: Sized the held-device array to CPUMAP_BATCH (8) instead of upstream's 2048, and drop the references right after netif_receive_skb_list(), since this tree's cpumap has no GRO. ]
---
 kernel/bpf/cpumap.c | 30 ++++++++++++++++++++++++------
 1 file changed, 24 insertions(+), 6 deletions(-)
kernel/bpf/cpumap.c +24 -6
index a2f46785ac3b3..c3a994112a470 100644
@@ -44,6 +44,7 @@
  */
 
 #define CPU_MAP_BULK_SIZE 8  /* 8 == one cacheline on 64-bit archs */
+#define CPUMAP_BATCH 8
 struct bpf_cpu_map_entry;
 struct bpf_cpu_map;
 
@@ -71,6 +72,13 @@ struct bpf_cpu_map_entry {
 
 	struct completion kthread_running;
 	struct rcu_work free_work;
+
+	/*
+	 * Every frame and skb in the queue holds a reference to its device.
+	 * The kthread keeps it until the batch has been handed to the stack.
+	 */
+	struct net_device *held[CPUMAP_BATCH];
+	u32 nr_held;
 };
 
 struct bpf_cpu_map {
@@ -126,9 +134,11 @@ static void __cpu_map_ring_cleanup(struct ptr_ring *ring)
 		WARN_ON_ONCE(1);
 		if (unlikely(__ptr_test_bit(0, &ptr))) {
 			__ptr_clear_bit(0, &ptr);
+			dev_put(((struct sk_buff *)ptr)->dev);
 			kfree_skb(ptr);
 			continue;
 		}
+		dev_put(((struct xdp_frame *)ptr)->dev_rx);
 		xdp_return_frame(ptr);
 	}
 }
@@ -232,8 +242,6 @@ static int cpu_map_bpf_prog_run_xdp(struct bpf_cpu_map_entry *rcpu,
 	return nframes;
 }
 
-#define CPUMAP_BATCH 8
-
 static int cpu_map_bpf_prog_run(struct bpf_cpu_map_entry *rcpu, void **frames,
 				int xdp_n, struct xdp_cpumap_stats *stats,
 				struct list_head *list)
@@ -314,10 +322,12 @@ static int cpu_map_kthread_run(void *data)
 				struct sk_buff *skb = f;
 
 				__ptr_clear_bit(0, &skb);
+				rcpu->held[rcpu->nr_held++] = skb->dev;
 				list_add_tail(&skb->list, &list);
 				continue;
 			}
 
+			rcpu->held[rcpu->nr_held++] = ((struct xdp_frame *)f)->dev_rx;
 			frames[xdp_n++] = f;
 			page = virt_to_page(f);
 
@@ -362,6 +372,8 @@ static int cpu_map_kthread_run(void *data)
 					 sched, &stats);
 
 		netif_receive_skb_list(&list);
+		while (rcpu->nr_held)
+			dev_put(rcpu->held[--rcpu->nr_held]);
 		local_bh_enable(); /* resched point, may call do_softirq() */
 	}
 	__set_current_state(TASK_RUNNING);
@@ -686,12 +698,14 @@ static void bq_flush_to_queue(struct xdp_bulk_queue *bq)
 
 	for (i = 0; i < bq->count; i++) {
 		struct xdp_frame *xdpf = bq->q[i];
-		int err;
 
-		err = __ptr_ring_produce(q, xdpf);
-		if (err) {
+		if (__ptr_ring_full(q)) {
 			drops++;
 			xdp_return_frame_rx_napi(xdpf);
+		} else {
+			/* The device cannot go before the flush, from now on it can */
+			dev_hold(xdpf->dev_rx);
+			__ptr_ring_produce(q, xdpf);
 		}
 		processed++;
 	}
@@ -749,11 +763,15 @@ int cpu_map_generic_redirect(struct bpf_cpu_map_entry *rcpu,
 
 	__skb_pull(skb, skb->mac_len);
 	skb_set_redirected(skb, false);
+	dev_hold(skb->dev);
 	__ptr_set_bit(0, &skb);
 
 	ret = ptr_ring_produce(rcpu->queue, skb);
-	if (ret < 0)
+	if (ret < 0) {
+		__ptr_clear_bit(0, &skb);
+		dev_put(skb->dev);
 		goto trace;
+	}
 
 	wake_up_process(rcpu->kthread);
 trace:
Signature · 1 line
2.53.0
author maintainer
#517 lore raw

PATCH 513/816 bpf: Let bpf_dynptr_write() mark a global function

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 589998616e0f9190ba6f6644a19532c5b2ba66d0 ]

The caller of a global function loses its packet pointers if the function may change packet data. That is found out by a scan for calls of the helpers which bpf_helper_changes_pkt_data() lists.

bpf_dynptr_write() is not on the list, because it depends on the type of the dynptr: check_helper_call() looks at it. The scan cannot do that, and so a global function which makes a dynptr from the skb, or gets one as an argument, and writes through it counts as harmless. The write can reallocate the head of the skb, and the caller goes on with pointers into the old one, which has been freed.

Let every call of bpf_dynptr_write() mark the function, as a tail call does. The same mark decides whether a program may replace a function.

Fixes 51081a3f25c7 ("bpf: track changes_pkt_data property for global functions")
[ sashal: Ported the change to the CFG code in verifier.c, since cfg.c doesn't exist here, and wrapped the condition in a bpf_helper_call(insn) check because there is no src_reg if/else split. ]
---
 kernel/bpf/verifier.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
kernel/bpf/verifier.c +4 -1
index 34b82d3eff66f..9818cdbfb9724 100644
@@ -17089,7 +17089,10 @@ static int visit_insn(int t, struct bpf_verifier_env *env)
 			mark_prune_point(env, t);
 			mark_jmp_point(env, t);
 		}
-		if (bpf_helper_call(insn) && bpf_helper_changes_pkt_data(insn->imm))
+		/* nobody knows yet whether the dynptr is that of an skb */
+		if (bpf_helper_call(insn) &&
+		    (bpf_helper_changes_pkt_data(insn->imm) ||
+		     insn->imm == BPF_FUNC_dynptr_write))
 			mark_subprog_changes_pkt_data(env, t);
 		if (insn->src_reg == BPF_PSEUDO_KFUNC_CALL) {
 			struct bpf_kfunc_call_arg_meta meta;
Signature · 1 line
2.53.0
author maintainer
#518 lore raw

PATCH 514/816 bpf: Dont take a dynptr argument for a local dynptr

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit b7f97db88948aa511bcd989978f181e1367e0e8b ]

A global function is verified on its own. A dynptr which it gets as an argument is assumed to be of type BPF_DYNPTR_TYPE_LOCAL, but the callers may pass one of any type, that of an skb for example.

The type decides whether a write through the dynptr invalidates packet pointers, and whether a slice of it is invalidated together with them. Inside of the function neither happens. It can take a packet pointer from its context argument, or a slice from the dynptr, write through the dynptr and go on using the pointer, although the write may have reallocated the head of the skb.

Assume the type of an skb dynptr instead. Nothing becomes forbidden for the dynptr itself, and a clone inherits the caution. The dynptr which the callback of bpf_user_ringbuf_drain() gets is known to be local, and stays so.

Fixes a64bfe618665 ("bpf: add support for passing dynptr pointer to global subprog")
[ sashal: adjusted context for the older tree: dropped the trailing 0 argument to __mark_dynptr_reg() and kept the existing ARG_PTR_TO_DYNPTR | MEM_RDONLY guard and do_check_common() signature. ]
---
 kernel/bpf/verifier.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
kernel/bpf/verifier.c +6 -2
index 9818cdbfb9724..dd7445537b1e3 100644
@@ -22372,8 +22372,12 @@ static int do_check_common(struct bpf_verifier_env *env, int subprog)
 				reg->type = SCALAR_VALUE;
 				mark_reg_unknown(env, regs, i);
 			} else if (arg->arg_type == (ARG_PTR_TO_DYNPTR | MEM_RDONLY)) {
-				/* assume unspecial LOCAL dynptr type */
-				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_LOCAL, true, ++env->id_gen);
+				/*
+				 * The callers may hand in a dynptr of any type.
+				 * Take it for that of an skb, so that a write
+				 * through it and its slices are treated with care.
+				 */
+				__mark_dynptr_reg(reg, BPF_DYNPTR_TYPE_SKB, true, ++env->id_gen);
 			} else if (base_type(arg->arg_type) == ARG_PTR_TO_MEM) {
 				reg->type = PTR_TO_MEM;
 				if (arg->arg_type & PTR_MAYBE_NULL)
Signature · 1 line
2.53.0
author maintainer
#519 lore raw

PATCH 515/816 bpf: Follow the head if an skb is written from a slice

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 1c19f2b3b2f3b55c8017092257634cb8229b7d97 ]

The source of bpf_dynptr_write() may be a slice of the skb which is written to, that is a pointer into its head. bpf_dynptr_copy() does it by itself for a copy inside of one skb, if the source is linear and the destination is not.

__bpf_skb_store_bytes() and __bpf_skb_meta_store_bytes() make the skb writable first. If that reallocates the head, the source points to the old one, and freed memory is copied into the packet.

The offsets in the head do not change when it is reallocated here. Move the source along with the head.

Fixes 2012c867c800 ("bpf: verifier: Accept dynptr mem as mem in helpers")
Fixes f38499ff45f5 ("bpf: Unclone skb head on bpf_dynptr_write to skb metadata")
[ sashal: Dropped the hunk that modifies __bpf_skb_meta_store_bytes() because that function doesn't exist here, and kept the helper and the bpf_skb_store_bytes() change. ]
---
 net/core/filter.c | 20 +++++++++++++++++++-
 1 file changed, 19 insertions(+), 1 deletion(-)
net/core/filter.c +19 -1
index 9c53e79d87501..3b8ea2ba5c312 100644
@@ -1720,6 +1720,24 @@ static inline void bpf_pull_mac_rcsum(struct sk_buff *skb)
 		skb_postpull_rcsum(skb, skb_mac_header(skb), skb->mac_len);
 }
 
+/*
+ * The source of a write through a dynptr may be a slice of the same skb.
+ * Making the skb writable can move its head: follow the move.
+ */
+static int bpf_try_make_writable_from(struct sk_buff *skb, u32 write_len,
+				      const void **from)
+{
+	const void *head = skb->head;
+	bool in_head = *from >= head &&
+		       *from < (const void *)skb_end_pointer(skb);
+	int err;
+
+	err = bpf_try_make_writable(skb, write_len);
+	if (!err && in_head)
+		*from = skb->head + (*from - head);
+	return err;
+}
+
 BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset,
 	   const void *, from, u32, len, u64, flags)
 {
@@ -1729,7 +1747,7 @@ BPF_CALL_5(bpf_skb_store_bytes, struct sk_buff *, skb, u32, offset,
 		return -EINVAL;
 	if (unlikely(offset > INT_MAX))
 		return -EFAULT;
-	if (unlikely(bpf_try_make_writable(skb, offset + len)))
+	if (unlikely(bpf_try_make_writable_from(skb, offset + len, &from)))
 		return -EFAULT;
 
 	ptr = skb->data + offset;
Signature · 1 line
2.53.0
author maintainer
#520 lore raw

PATCH 516/816 locking/atomic: arc, hexagon, openrisc: Define arch_cmpxchg_local()

In reply to Greg Kroah-Hartman

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

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

[ Upstream commit 8cebaa3be829c88a59957900f8de98fed09daefe ]

Commit ccb88db8dac8 ("bpf: Don't hand out a linked element as extra element") made alloc_htab_elem() take the per-cpu spare element with try_cmpxchg_local(), the first caller of cmpxchg_local() outside of architecture code. It doesn't build on arc, hexagon and openrisc:

include/linux/atomic/atomic-arch-fallback.h:384:27: error: implicit declaration of function 'arch_cmpxchg_local'; did you mean 'raw_cmpxchg_local'? [-Werror=implicit-function-declaration]

raw_cmpxchg_local() maps to arch_cmpxchg_local() unconditionally, but these three architectures don't define it, and unlike nios2 and microblaze they don't get it from asm-generic/cmpxchg.h either.

cmpxchg_local() only has to be atomic with respect to the local CPU, so an architecture's own arch_cmpxchg() can serve for the sizes it supports. arc uses its relaxed LLOCK/SCOND variant when ARC_HAS_LLSC is set and its atomic_ops_lock() variant otherwise, and openrisc uses its LL/SC arch_cmpxchg(), the way arm64, riscv and s390 alias theirs. The hexagon arch_cmpxchg() only handles 32-bit words, so hexagon uses the generic version that disables interrupts, like sh, sparc32 and xtensa do. Linux has no NMIs on hexagon, so that is sufficient there.

---
 arch/arc/include/asm/cmpxchg.h      | 4 ++++
 arch/hexagon/include/asm/cmpxchg.h  | 6 ++++++
 arch/openrisc/include/asm/cmpxchg.h | 2 ++
 3 files changed, 12 insertions(+)
arch/arc/include/asm/cmpxchg.h +4 -0
index 76f43db0890fc..07d7a01d26de0 100644
@@ -59,6 +59,8 @@
 	_prev_;								\
 })
 
+#define arch_cmpxchg_local	arch_cmpxchg_relaxed
+
 #else
 
 #define arch_cmpxchg(ptr, old, new)				        \
@@ -80,6 +82,8 @@
 	_prev_;								\
 })
 
+#define arch_cmpxchg_local	arch_cmpxchg
+
 #endif
 
 /*
arch/hexagon/include/asm/cmpxchg.h +6 -0
index 9c58fb81f7fd6..e6114e713db9f 100644
@@ -8,6 +8,8 @@
 #ifndef _ASM_CMPXCHG_H
 #define _ASM_CMPXCHG_H
 
+#include <asm-generic/cmpxchg-local.h>
+
 /*
  * __arch_xchg - atomically exchange a register and a memory location
  * @x: value to swap
@@ -72,4 +74,8 @@ __arch_xchg(unsigned long x, volatile void *ptr, int size)
 	__oldval;						\
 })
 
+#define arch_cmpxchg_local(ptr, o, n)					\
+	((__typeof__(*(ptr)))__generic_cmpxchg_local((ptr),		\
+			(unsigned long)(o), (unsigned long)(n), sizeof(*(ptr))))
+
 #endif /* _ASM_CMPXCHG_H */
arch/openrisc/include/asm/cmpxchg.h +2 -0
index 8ee151c072e41..fcf1bc8db8fe9 100644
@@ -140,6 +140,8 @@ static inline unsigned long __cmpxchg(volatile void *ptr, unsigned long old,
 					       sizeof(*(ptr)));		\
 	})
 
+#define arch_cmpxchg_local	arch_cmpxchg
+
 /*
  * This function doesn't exist, so you'll get a linker error if
  * something tries to do an invalidly-sized xchg().
Signature · 1 line
2.53.0
author maintainer
#521 lore raw

PATCH 517/816 bpf: Zero-extend the index in inlined bpf_get_func_arg()

In reply to Greg Kroah-Hartman

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

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

From: Woojin Ji <[email protected]>

[ Upstream commit 1c1dda9ba9f3af9cd511a197dcc86de2465d8fe5 ]

bpf_get_func_arg() takes a u32 index, but the inlined expansion compared only the low 32 bits of R2 with the argument count and then shifted the full 64-bit register to compute the context address. R2 is ARG_ANYTHING, so nothing guarantees that its upper bits are zero: an index of 1ULL << 32 passes the bounds check as index zero while the load is performed at ctx + (1ULL << 35).

Shift the index as a 32-bit value. When the 32-bit bounds check passes, the low 32 bits of R2 are below R0, and R0 is at most 255: the trampoline arm masks the argument count with 0xFF and the raw_tp arm uses the BTF argument count minus one, which the verifier caps at MAX_BPF_FUNC_ARGS. The 3-bit shift therefore cannot overflow and it clears the upper bits of the register. Widening the comparison instead would reject indices whose low 32 bits are valid. The check itself is unchanged, so this cannot change which programs are accepted, only the address that is computed.

Fixes f92c1e183604 ("bpf: Add get_func_[arg|ret|arg_cnt] helpers")
[ sashal: Changed the inlined bpf_get_func_arg() shift to BPF_ALU32_IMM in do_misc_fixups() in verifier.c, since the fixups file doesn't exist here and only the tracing arm is present. ]
---
 kernel/bpf/verifier.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
kernel/bpf/verifier.c +1 -1
index dd7445537b1e3..a5ffecbaa7bf9 100644
@@ -21867,7 +21867,7 @@ static int do_misc_fixups(struct bpf_verifier_env *env)
 			/* Load nr_args from ctx - 8 */
 			insn_buf[0] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_1, -8);
 			insn_buf[1] = BPF_JMP32_REG(BPF_JGE, BPF_REG_2, BPF_REG_0, 6);
-			insn_buf[2] = BPF_ALU64_IMM(BPF_LSH, BPF_REG_2, 3);
+			insn_buf[2] = BPF_ALU32_IMM(BPF_LSH, BPF_REG_2, 3);
 			insn_buf[3] = BPF_ALU64_REG(BPF_ADD, BPF_REG_2, BPF_REG_1);
 			insn_buf[4] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_2, 0);
 			insn_buf[5] = BPF_STX_MEM(BPF_DW, BPF_REG_3, BPF_REG_0, 0);
Signature · 1 line
2.53.0
author maintainer
#522 lore raw

PATCH 518/816 gpiolib: clear the event clock flags when a line is released

In reply to Greg Kroah-Hartman

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

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

From: Adrian Ambrozewicz <[email protected]>

[ Upstream commit d35f61581ee67f8d4d58c325bac813cea528b6b9 ]

gpiod_free_commit() clears the flags that a request sets on a line, but not GPIOD_FLAG_EVENT_CLOCK_REALTIME and GPIOD_FLAG_EVENT_CLOCK_HTE, which gpio_v2_line_config_flags_to_desc_flags() sets from the uAPI v2 line config. Once a line requested with GPIO_V2_LINE_FLAG_EVENT_CLOCK_REALTIME or GPIO_V2_LINE_FLAG_EVENT_CLOCK_HTE is released, GPIO_V2_GET_LINEINFO_IOCTL and the line info changed events, the "released" one included, keep reporting that event clock for the free line:

GPIO_V2_GET_LINE_IOCTL, line 1, input, event clock realtime: ok close()
GPIO_V2_GET_LINEINFO_IOCTL, line 1: input, event clock realtime

The flags are set before edge detection is set up, so a request that fails in hte_ts_get(), for instance because no HTE provider handles the line, leaves GPIOD_FLAG_EVENT_CLOCK_HTE behind as well. The next uAPI v2 request rewrites both flags, but requests through uAPI v1, sysfs exports and in-kernel consumers do not, and the line info then shows the event clock of an earlier user for them too.

Clear both flags together with the other flags of the request.

Reproduced under QEMU with a test GPIO chip: after a released request with the realtime event clock, and on a kernel with CONFIG_HTE=y but no HTE provider after a failed request with the HTE event clock, the line info of the free line still reports that event clock. With this change it reports none.

Fixes 26d060e47e25 ("gpiolib: cdev: allow edge event timestamps to be configured as REALTIME")
Fixes 2068339a6c35 ("gpiolib: cdev: Add hardware timestamp clock type")
[ sashal: Replaced upstream's GPIOD_FLAG_EVENT_CLOCK_REALTIME/HTE names with the older unprefixed FLAG_EVENT_CLOCK_REALTIME/HTE names used in this tree. ]
---
 drivers/gpio/gpiolib.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/gpio/gpiolib.c +2 -0
index 02a322f8330c2..28a1a184e580d 100644
@@ -2436,6 +2436,8 @@ static void gpiod_free_commit(struct gpio_desc *desc)
 		clear_bit(FLAG_BIAS_DISABLE, &flags);
 		clear_bit(FLAG_EDGE_RISING, &flags);
 		clear_bit(FLAG_EDGE_FALLING, &flags);
+		clear_bit(FLAG_EVENT_CLOCK_REALTIME, &flags);
+		clear_bit(FLAG_EVENT_CLOCK_HTE, &flags);
 		clear_bit(FLAG_IS_HOGGED, &flags);
 #ifdef CONFIG_OF_DYNAMIC
 		WRITE_ONCE(desc->hog, NULL);
Signature · 1 line
2.53.0
author maintainer
#523 lore raw

PATCH 519/816 netfilter: flowtable: reset transport header after nf_flow_encap_pop()

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Bianconi <[email protected]>

[ Upstream commit 08f7882637f2db5b98f521498eeaf94770383a6e ]

nf_flow_encap_pop() pulls vlan/pppoe or ip tunnel headers and resets the network header, but leaves the transport header pointing into the removed outer header. Reset the transport header to the inner L4 header, otherwise later consumers (e.g. GSO segmentation) parse a bogus header.

Fixes 4cd91f7c290f ("netfilter: flowtable: add vlan support")
[ sashal: Adapted the IPv6 hunk context to this tree's two-argument nf_flow_encap_pop(skb, tuplehash) call instead of the three-argument form with ctx. ]
---
 net/netfilter/nf_flow_table_ip.c | 2 ++
 1 file changed, 2 insertions(+)
net/netfilter/nf_flow_table_ip.c +2 -0
index 1855ee828421f..91c82d513bbc0 100644
@@ -418,6 +418,7 @@ static int nf_flow_offload_forward(struct nf_flowtable_ctx *ctx,
 
 	nf_flow_encap_pop(skb, tuplehash);
 	thoff -= ctx->offset;
+	skb_set_transport_header(skb, thoff);
 
 	iph = ip_hdr(skb);
 	nf_flow_nat_ip(flow, skb, thoff, dir, iph);
@@ -700,6 +701,7 @@ static int nf_flow_offload_ipv6_forward(struct nf_flowtable_ctx *ctx,
 	flow_offload_refresh(flow_table, flow, false);
 
 	nf_flow_encap_pop(skb, tuplehash);
+	skb_set_transport_header(skb, sizeof(*ip6h));
 
 	ip6h = ipv6_hdr(skb);
 	nf_flow_nat_ipv6(flow, skb, dir, ip6h);
Signature · 1 line
2.53.0
author maintainer
#524 lore raw

PATCH 520/816 ALSA: aloop: Keep shared timer callbacks alive through close

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit a7d4d780f34b9e43eefab6a7e6c9f4101f2c144e ]

The shared sound-timer callback must finish using the selected PCM runtimes before a close can detach them. loopback_snd_timer_period_elapsed() saves the active substreams under cable->lock, then drops the lock before calling snd_pcm_period_elapsed() or snd_pcm_stop_xrun(). The sound-timer backend has no per-stream close drain, and free_cable() keeps the timer open when the paired endpoint remains attached.

With both directions running on a shared sound timer, playback can be dropped and closed while a notification is pending. Capture keeps the timer alive, allowing this order:

Timer callback Playback owner
-------------- --------------
select playback under cable->lock
unlock; delay notification

                                       DROP; HW_FREE -> OPEN
                                       close: snd_pcm_drop(); unlock
                                       free_cable(); peer stays alive

snd_pcm_period_elapsed()
lock stream; cache runtime
snd_pcm_detach_substream()
free runtime and its fasync
read runtime->fasync

The stream lock taken by snd_pcm_drop() cannot protect a notification that starts after it returns, and detach does not take it. The callback can therefore read runtime->fasync after the runtime has been freed, and an escaped notification can also reach a replacement runtime if the same substream slot is reopened before the notification resumes.

Take the existing cable->stop_count reference under cable->lock when selecting the targets and release it after the PCM callbacks finish, including the XRUN path. free_cable() already removes the closing endpoint under that lock and waits for stop_count before returning, so runtime detach and slot reuse cannot overtake the notification.

Fixes 26c53379f98d ("ALSA: aloop: Support selection of snd_timer instead of jiffies")
Assisted-by LLM
[ sashal: Replaced snd_refcount get/put with atomic_inc/atomic_dec_and_test plus wake_up on the existing stop_count, and adapted the function body to the spin_lock_irqsave form instead of scoped_guard. ]
---
 sound/drivers/aloop.c | 12 +++++++++---
 1 file changed, 9 insertions(+), 3 deletions(-)
sound/drivers/aloop.c +9 -3
index fa8d2877516d9..7c69f5141ed2e 100644
@@ -98,7 +98,7 @@ struct loopback_ops {
 struct loopback_cable {
 	spinlock_t lock;
 	struct loopback_pcm *streams[2];
-	/* in-flight peer stops running outside cable->lock */
+	/* in-flight PCM callbacks running outside cable->lock */
 	atomic_t stop_count;
 	wait_queue_head_t stop_wait;
 	struct snd_pcm_hardware hw;
@@ -809,6 +809,8 @@ static void loopback_snd_timer_period_elapsed(struct loopback_cable *cable,
 	valid_runtime = (running & (1 << SNDRV_PCM_STREAM_PLAYBACK)) ?
 				dpcm_play->substream->runtime :
 				dpcm_capt->substream->runtime;
+	/* Keep runtimes alive through the PCM callbacks. */
+	atomic_inc(&cable->stop_count);
 
 	/* resolution is only valid for SNDRV_TIMER_EVENT_TICK events */
 	if (event == SNDRV_TIMER_EVENT_TICK) {
@@ -823,7 +825,7 @@ static void loopback_snd_timer_period_elapsed(struct loopback_cable *cable,
 				snd_pcm_stop_xrun(substream_play);
 			if (substream_capt)
 				snd_pcm_stop_xrun(substream_capt);
-			return;
+			goto exit;
 		}
 	}
 
@@ -847,6 +849,10 @@ static void loopback_snd_timer_period_elapsed(struct loopback_cable *cable,
 		snd_pcm_period_elapsed(substream_play);
 	if (substream_capt)
 		snd_pcm_period_elapsed(substream_capt);
+
+exit:
+	if (atomic_dec_and_test(&cable->stop_count))
+		wake_up(&cable->stop_wait);
 }
 
 static void loopback_snd_timer_function(struct snd_timer_instance *timeri,
@@ -1092,7 +1098,7 @@ static void free_cable(struct snd_pcm_substream *substream)
 		other_alive = cable->streams[!substream->stream];
 	}
 
-	/* Pair with the stop_count increment in loopback_check_format(). */
+	/* Wait for PCM callbacks running outside cable->lock. */
 	wait_event(cable->stop_wait, !atomic_read(&cable->stop_count));
 	if (other_alive)
 		return;
Signature · 1 line
2.53.0
author maintainer
#525 lore raw

PATCH 521/816 cgroup/cpuset: Do housekeeping check before converting invalid partition to valid

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit 2c0a5742fc459cd8416607acff4a38a1abcb2e1b ]

When a hotplug event happens or when update_cpumasks_hier() is called, an invalid partition may be converted back to valid. However check against housekeeping conflict isn't being done which can lead to a partition state that violates the housekeeping rules. Update the code to allow reviving an invalid partition only if it can pass the housekeeping check.

Fixes 4a74e418881f ("cgroup/cpuset: Check partition conflict with housekeeping setup")
[ sashal: Adapted the call to the older two-argument prstate_housekeeping_conflict() helper, passing the negated partition_root_state so an invalid isolated partition is checked as isolated. ]
---
 kernel/cgroup/cpuset.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
kernel/cgroup/cpuset.c +8 -2
index 3662acc2cff89..b1af98c19891e 100644
@@ -1850,9 +1850,15 @@ static int update_parent_effective_cpumask(struct cpuset *cs, int cmd,
 			bool exclusive = true;
 
 			/*
-			 * Convert invalid partition to valid has to
-			 * pass the cpu exclusivity test.
+			 * Convert invalid partition to valid has to pass the
+			 * cpu exclusivity test as well as the housekeeping
+			 * check.
 			 */
+			if (prstate_housekeeping_conflict(-cs->partition_root_state,
+							  xcpus)) {
+				part_error = PERR_HKEEPING;
+				goto write_error;
+			}
 			rcu_read_lock();
 			cpuset_for_each_child(child, css, parent) {
 				if (child == cs)
Signature · 1 line
2.53.0
author maintainer
#526 lore raw

PATCH 522/816 RDMA/mlx5: Validate priority in STEERING_ANCHOR_CREATE handler

In reply to Greg Kroah-Hartman

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

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

From: Serhat Kumral <[email protected]>

[ Upstream commit bb75e5580b15cd23ededf15683a5ad67d7b61aab ]

In MLX5_IB_METHOD_STEERING_ANCHOR_CREATE, the user-supplied u16 priority is passed directly to _get_flow_table() without an upper bound check. This can lead to out-of-bounds array accesses on dev->flow_db priority tables.

Check that priority does not exceed MLX5_IB_FLOW_LAST_PRIO before calling _get_flow_table(), matching the existing validation in raw_fs_rule_add() and mlx5_ib_create_flow().

Fixes 0c6ab0ca9a66 ("RDMA/mlx5: Expose steering anchor to userspace")
[ sashal: kept the local kzalloc(sizeof(*obj), GFP_KERNEL) line as context since kzalloc_obj() isn't available; the added priority check is identical to upstream. ]
---
 drivers/infiniband/hw/mlx5/fs.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/infiniband/hw/mlx5/fs.c +3 -0
index 186085cfb4e9b..369cea6b31857 100644
@@ -2427,6 +2427,9 @@ static int UVERBS_HANDLER(MLX5_IB_METHOD_STEERING_ANCHOR_CREATE)(
 	if (err)
 		return err;
 
+	if (priority > MLX5_IB_FLOW_LAST_PRIO)
+		return -EINVAL;
+
 	obj = kzalloc(sizeof(*obj), GFP_KERNEL);
 	if (!obj)
 		return -ENOMEM;
Signature · 1 line
2.53.0
author maintainer
#527 lore raw

PATCH 523/816 xsk: freeze deferred pool teardown without blocking unregister

In reply to Greg Kroah-Hartman

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

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

From: James Hilliard <[email protected]>

[ Upstream commit fece8420e76fe53ee84f0439f18d026b4c7641da ]

Deferred pool destruction calls ndo_bpf() under RTNL. system_wq is not frozen during system sleep, so that callback can run after a device has suspended and gated its clocks. Use system_freezable_wq so running destruction finishes before device suspend and new work waits until process thaw.

Keep assigned pools visible to NETDEV_UNREGISTER independently of the socket list. A released socket has already left that list, but its final pool put can queue destruction after workqueues freeze. A resume-time unregister would then wait for a device reference whose release cannot run until the resume completes.

Track assigned pools per netdev with netdev operations locking and detach remaining pools after the notifier socket walk, including copy-mode pools. This also covers leased queues without scanning pools from unrelated devices or network namespaces. Remove the entry on assignment failure and normal teardown. The deferred worker still owns the pool and later observes the cleared device pointer, avoiding a second driver detach or put.

The lifetime problem was identified by code inspection of the deferred release and system-sleep paths.

Fixes 1c1efc2af158 ("xsk: Create and free buffer pool independently from umem")
[ sashal: Dropped netdev ops locking calls (netdev_lock_ops and friends) since they don't exist here, relying on RTNL with ASSERT_RTNL() instead, and adjusted the comments to say RTNL protected. ]
---
 include/linux/netdevice.h   |  5 +++++
 include/net/xsk_buff_pool.h |  3 +++
 net/xdp/xsk.c               |  5 +++++
 net/xdp/xsk_buff_pool.c     | 43 +++++++++++++++++++++++++++++++------
 4 files changed, 50 insertions(+), 6 deletions(-)
include/linux/netdevice.h +5 -0
index 4d1e0b91402d1..8dc5666795841 100644
@@ -2390,6 +2390,11 @@ struct net_device {
 	/* protected by rtnl_lock */
 	struct bpf_xdp_entity	xdp_state[__MAX_XDP_MODE];
 
+#ifdef CONFIG_XDP_SOCKETS
+	/** @xsk_pools: assigned AF_XDP pools, RTNL protected */
+	struct hlist_head	xsk_pools;
+#endif
+
 	u8 dev_addr_shadow[MAX_ADDR_LEN];
 	netdevice_tracker	linkwatch_dev_tracker;
 	netdevice_tracker	watchdog_dev_tracker;
include/net/xsk_buff_pool.h +3 -0
index 4fce4bd826b9c..c58795a6d8c20 100644
@@ -48,6 +48,8 @@ struct xsk_buff_pool {
 	struct device *dev;
 	struct net_device *netdev;
 	struct list_head xsk_tx_list;
+	/* Assigned pools, including deferred releases; RTNL protected. */
+	struct hlist_node dev_node;
 	/* Protects modifications to the xsk_tx_list */
 	spinlock_t xsk_tx_list_lock;
 	refcount_t users;
@@ -118,6 +120,7 @@ bool xp_put_pool(struct xsk_buff_pool *pool);
 void xp_clear_dev(struct xsk_buff_pool *pool);
 void xp_add_xsk(struct xsk_buff_pool *pool, struct xdp_sock *xs);
 void xp_del_xsk(struct xsk_buff_pool *pool, struct xdp_sock *xs);
+void xp_clear_dev_all(struct net_device *dev);
 
 /* AF_XDP, and XDP core. */
 void xp_free(struct xdp_buff_xsk *xskb);
net/xdp/xsk.c +5 -0
index 8dd43f06d6ed1..1bc966669ec96 100644
@@ -1890,6 +1890,11 @@ static int xsk_notifier(struct notifier_block *this,
 			mutex_unlock(&xs->mutex);
 		}
 		mutex_unlock(&net->xdp.lock);
+		/*
+		 * A released socket is no longer on xdp.list. Its pool can still
+		 * hold a device reference on the frozen release workqueue.
+		 */
+		xp_clear_dev_all(dev);
 		break;
 	}
 	return NOTIFY_DONE;
net/xdp/xsk_buff_pool.c +37 -6

71 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#528 lore raw

PATCH 524/816 ip6mr: clear skb->cb[] in reg_vif_xmit()

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit 238164201431a425e48dfcb8e9a59de63caf175b ]

reg_vif_xmit() hands the skb to ip6mr_cache_report() as an MRT6MSG_WHOLEPKT report. skb_realloc_headroom() copies skb->cb[] into the report, which is queued to the mroute socket, where rawv6_recvmsg() reads it as IP6CB.

By the time the pim6reg device transmits the packet, skb->cb[] is not IP6CB anymore: qdisc_pkt_len_init() overwrites iif and ra, and any qdisc installed on the device (fq, fq_codel, pie, cake...) or a tc BPF program writing skb->cb[] fills the area holding dst0, srcrt, dst1, lastopt and flags.

Since commit dd433671fef3 ("ipv6: validate extension header length before copying to cmsg") these stale offsets can no longer cause out-of-bounds reads, but the mroute socket can still receive bogus IPV6_PKTINFO ifindex and extension header ancillary data.

Clear IP6CB before building the report. The skb is freed right after, so nothing else depends on its control block.

Fixes 14fb64e1f449 ("[IPV6] MROUTE: Support PIM-SM (SSM).")
[ sashal: Placed the memset after the branch's existing rcu_read_lock() in reg_vif_xmit(), since the surrounding context differs, but the added code and comment are identical to upstream. ]
---
 net/ipv6/ip6mr.c | 7 +++++++
 1 file changed, 7 insertions(+)
net/ipv6/ip6mr.c +7 -0
index c608fc0a771aa..c962409a61e10 100644
@@ -625,6 +625,13 @@ static netdev_tx_t reg_vif_xmit(struct sk_buff *skb,
 	DEV_STATS_ADD(dev, tx_bytes, skb->len);
 	DEV_STATS_INC(dev, tx_packets);
 	rcu_read_lock();
+
+	/* skb->cb[] holds qdisc/tc state at this point, not IP6CB.
+	 * ip6mr_cache_report() copies it to the report delivered to
+	 * the mroute socket, where it is read as IP6CB.
+	 */
+	memset(IP6CB(skb), 0, sizeof(*IP6CB(skb)));
+
 	ip6mr_cache_report(mrt, skb, READ_ONCE(mrt->mroute_reg_vif_num),
 			   MRT6MSG_WHOLEPKT);
 	rcu_read_unlock();
Signature · 1 line
2.53.0
author maintainer
#529 lore raw

PATCH 525/816 exfat: fix used_clusters accounting during cluster allocation

In reply to Greg Kroah-Hartman

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

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

From: Chi Zhiling <[email protected]>

[ Upstream commit cb9dbf8a4e34b4fdf311598835ab4d76ed7e07c1 ]

In the current exfat_alloc_cluster(), p_chain->size is incremented as each cluster is allocated so that the partially allocated chain can be freed by __exfat_free_cluster() on the error path.

However, sbi->used_clusters is still updated only after all clusters have been allocated, while __exfat_free_cluster() unconditionally subtracts the number of freed clusters from sbi->used_clusters. Therefore, when allocation fails partway through, the partially allocated clusters are subtracted from sbi->used_clusters even though they were never added to it. This corrupts the free-space accounting and can cause sbi->used_clusters to underflow.

Increment sbi->used_clusters together with p_chain->size as each cluster is allocated. This keeps the accounting consistent with __exfat_free_cluster() on both the success and error paths.

This issue is caught by generic/476 with 256k cluster size:

Ran: generic/476
Failures: generic/476
Failed 1 of 1 tests

*** fsck.exfat output ***
ERROR: <path>: more clusters are allocated. truncate to N bytes
...
/dev/vdc: corrupted. directories 331, files 526 /dev/vdc: files corrupted 9, files fixed 0
*** end fsck.exfat output ***

Fixes d5c514b6a0c0 ("exfat: fix the newly allocated clusters are not freed in error handling")
[ sashal: Dropped the done: label from the context and removed this tree's used_clusters += num_alloc; line plus its blank line, where upstream removes used_clusters += p_chain->size;. ]
---
 fs/exfat/fatent.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
fs/exfat/fatent.c +1 -2
index 2c3ab6313cc98..5cde58a4a503c 100644
@@ -402,13 +402,12 @@ int exfat_alloc_cluster(struct inode *inode, unsigned int num_alloc,
 			}
 		}
 		p_chain->size++;
+		sbi->used_clusters++;
 
 		last_clu = new_clu;
 
 		if (p_chain->size == num_alloc) {
 			sbi->clu_srch_ptr = hint_clu;
-			sbi->used_clusters += num_alloc;
-
 			mutex_unlock(&sbi->bitmap_lock);
 			return 0;
 		}
Signature · 1 line
2.53.0
author maintainer
#530 lore raw

PATCH 526/816 exfat: take bitmap_lock at the start of exfat_alloc_cluster()

In reply to Greg Kroah-Hartman

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

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

From: Chi Zhiling <[email protected]>

[ Upstream commit 48acff2eedef7fecdfbd39be1b6f4463a9e43e3e ]

exfat_alloc_cluster() checks sbi->used_clusters against the total number of data clusters before acquiring sbi->bitmap_lock. A concurrent allocation can update sbi->used_clusters after the check but before the lock is acquired, making the check stale. This can allow the allocation to proceed even though there are not enough free clusters, causing it to fail partway through.

Acquire sbi->bitmap_lock before checking sbi->used_clusters so that the free-space check and subsequent cluster allocation are serialized with concurrent allocations.

Fixes f55c096f62f1 ("exfat: do not zero the extended part")
---
 fs/exfat/fatent.c | 17 ++++++++++-------
 1 file changed, 10 insertions(+), 7 deletions(-)
fs/exfat/fatent.c +10 -7
index 5cde58a4a503c..d855d4b4c720f 100644
@@ -326,19 +326,22 @@ int exfat_alloc_cluster(struct inode *inode, unsigned int num_alloc,
 	struct super_block *sb = inode->i_sb;
 	struct exfat_sb_info *sbi = EXFAT_SB(sb);
 
+	mutex_lock(&sbi->bitmap_lock);
+
 	total_cnt = EXFAT_DATA_CLUSTER_COUNT(sbi);
 
 	if (unlikely(total_cnt < sbi->used_clusters)) {
 		exfat_fs_error_ratelimit(sb,
 			"%s: invalid used clusters(t:%u,u:%u)\n",
 			__func__, total_cnt, sbi->used_clusters);
-		return -EIO;
+		ret = -EIO;
+		goto unlock;
 	}
 
-	if (num_alloc > total_cnt - sbi->used_clusters)
-		return -ENOSPC;
-
-	mutex_lock(&sbi->bitmap_lock);
+	if (num_alloc > total_cnt - sbi->used_clusters) {
+		ret = -ENOSPC;
+		goto unlock;
+	}
 
 	hint_clu = p_chain->dir;
 	/* find new cluster */
@@ -408,8 +411,8 @@ int exfat_alloc_cluster(struct inode *inode, unsigned int num_alloc,
 
 		if (p_chain->size == num_alloc) {
 			sbi->clu_srch_ptr = hint_clu;
-			mutex_unlock(&sbi->bitmap_lock);
-			return 0;
+			ret = 0;
+			goto unlock;
 		}
 
 		hint_clu = new_clu + 1;
Signature · 1 line
2.53.0
author maintainer
#531 lore raw

PATCH 527/816 ksmbd: fix iface_list use-after-free during server reset

In reply to Greg Kroah-Hartman

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

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

From: Henry Hu <[email protected]>

[ Upstream commit d34d38ab0c62fe4eb9e746420c554e6d0e6f54db ]

ksmbd_find_netdev_name_iface_list() walks iface_list for fsctl_query_iface_info_ioctl(), which holds RTNL. But during server reset, ksmbd_tcp_destroy() unlinks and frees the entries without RTNL, and queued SMB requests can still be running at that point. So an FSCTL_QUERY_NETWORK_INTERFACE_INFO request can therefore race with interface destruction and dereference a freed entry. With debug-only instrumentation to make the race deterministic, KASAN reports:

   BUG: KASAN: slab-use-after-free in
   ksmbd_find_netdev_name_iface_list

ksmbd_find_netdev_name_iface_list
fsctl_query_iface_info_ioctl
smb2_ioctl
handle_ksmbd_work

Freed by:
kfree
ksmbd_tcp_destroy
ksmbd_conn_transport_destroy
kill_server_store

The fix is to detach iface_list to a temporary list under RTNL, then drop RTNL before cleanup because the following cleanup may block and hold RTNL for a long time.

Fixes b2d99376c5d6 ("ksmbd: browse interfaces list on FSCTL_QUERY_INTERFACE_INFO IOCTL")
Assisted-by LLM
[ sashal: Dropped the ksmbd_tcp_stop_listener() context line from the cleanup loop, since that helper doesn't exist here, so the loop starts at list_del(). ]
---
 fs/smb/server/transport_tcp.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
fs/smb/server/transport_tcp.c +6 -1
index 65705c8993be0..6dfd70f44cceb 100644
@@ -682,10 +682,15 @@ static void tcp_stop_kthread(struct task_struct *kthread)
 void ksmbd_tcp_destroy(void)
 {
 	struct interface *iface, *tmp;
+	LIST_HEAD(iface_list_to_free);
 
 	unregister_netdevice_notifier(&ksmbd_netdev_notifier);
 
-	list_for_each_entry_safe(iface, tmp, &iface_list, entry) {
+	rtnl_lock();
+	list_splice_init(&iface_list, &iface_list_to_free);
+	rtnl_unlock();
+
+	list_for_each_entry_safe(iface, tmp, &iface_list_to_free, entry) {
 		list_del(&iface->entry);
 		kfree(iface->name);
 		kfree(iface);
Signature · 1 line
2.53.0
author maintainer
#532 lore raw

PATCH 528/816 ksmbd: disconnect on invalid encryption transform flags

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 0882f124ae329eefb66b00e63b9043f24c006b0e ]

MS-SMB2 3.3.5.2.1.1 requires the Flags/EncryptionAlgorithm field in an SMB2 transform header to be 0x0001. The server must disconnect the connection when it has any other value.

smb3_decrypt_req() currently ignores this field. A client with the session key can therefore send a correctly authenticated encrypted request with invalid flags and have it processed. Check the field before looking up the session key or decrypting the request. The caller aborts the connection when this check fails.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
[ sashal: Added the transform-header Flags check to smb3_decrypt_req() unchanged, but adjusted the surrounding context because this older code lacks original_msg_size and the compression-header size check. ]
---
 fs/smb/server/smb2pdu.c | 6 ++++++
 1 file changed, 6 insertions(+)
fs/smb/server/smb2pdu.c +6 -0
index e65fe5858a51d..5492e7490a26b 100644
@@ -9572,6 +9572,12 @@ int smb3_decrypt_req(struct ksmbd_work *work)
 		return -ECONNABORTED;
 	}
 
+	if (tr_hdr->Flags != cpu_to_le16(TRANSFORM_FLAG_ENCRYPTED)) {
+		pr_err_ratelimited("Invalid transform flags 0x%04x\n",
+				   le16_to_cpu(tr_hdr->Flags));
+		return -ECONNABORTED;
+	}
+
 	if (buf_data_size < le32_to_cpu(tr_hdr->OriginalMessageSize)) {
 		pr_err("Transform message is broken\n");
 		return -ECONNABORTED;
Signature · 1 line
2.53.0
author maintainer
#533 lore raw

PATCH 529/816 ksmbd: cache the resolved share path for durable reconnects

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 2a90ba573d41efa82e075ba9ac532bb3ec0519c4 ]

A share configured as /a/link/b, with /a/link pointing to /real, is opened relative to share->vfs_path at /real/b. However, ksmbd_validate_name_reconnect() compares the file's d_path() result against the original /a/link/b string and rejects a valid reconnect.

Render share->vfs_path with d_path() after the existing kern_path() lookup and cache a copy in real_path along with its length. Use the resolved string for durable reconnect name validation. Keep path and path_sz as the configured spelling for existing consumers, including the volume serial calculation and path lookups.

Fixes c8efcc786146 ("ksmbd: add support for durable handles v1/v2")
[ sashal: Dropped the scoped_with_init_fs() wrapper around the share_config_resolve_path() call because this tree lacks it, and adjusted the include context where <linux/fs_struct.h> is absent. ]
---
 fs/smb/server/mgmt/share_config.c | 43 +++++++++++++++++++++++++++++--
 fs/smb/server/mgmt/share_config.h |  2 ++
 fs/smb/server/vfs_cache.c         | 12 +++++----
 3 files changed, 50 insertions(+), 7 deletions(-)
fs/smb/server/mgmt/share_config.c +41 -2
index 04e8c11e865e9..fee0b784e2f1c 100644
@@ -8,6 +8,7 @@
 #include <linux/slab.h>
 #include <linux/rwsem.h>
 #include <linux/parser.h>
+#include <linux/dcache.h>
 #include <linux/namei.h>
 #include <linux/sched.h>
 #include <linux/mm.h>
@@ -50,6 +51,7 @@ static void kill_share(struct ksmbd_share_config *share)
 		path_put(&share->vfs_path);
 	kfree(share->name);
 	kfree(share->path);
+	kfree(share->real_path);
 	kfree(share);
 }
 
@@ -124,6 +126,43 @@ static int parse_veto_list(struct ksmbd_share_config *share,
 	return 0;
 }
 
+static int share_config_resolve_path(struct ksmbd_share_config *share)
+{
+	char *buf, *path;
+	int ret;
+
+	ret = kern_path(share->path, 0, &share->vfs_path);
+	if (ret)
+		return ret;
+
+	buf = kmalloc(PATH_MAX, KSMBD_DEFAULT_GFP);
+	if (!buf) {
+		ret = -ENOMEM;
+		goto out;
+	}
+
+	path = d_path(&share->vfs_path, buf, PATH_MAX);
+	if (IS_ERR(path)) {
+		ret = PTR_ERR(path);
+		goto out_buf;
+	}
+
+	path = kstrdup(path, KSMBD_DEFAULT_GFP);
+	if (!path) {
+		ret = -ENOMEM;
+		goto out_buf;
+	}
+
+	share->real_path = path;
+	share->real_path_sz = strlen(path);
+out_buf:
+	kfree(buf);
+out:
+	if (ret)
+		path_put(&share->vfs_path);
+	return ret;
+}
+
 static struct ksmbd_share_config *share_config_request(struct ksmbd_work *work,
 						       const char *name)
 {
@@ -212,12 +251,12 @@ static struct ksmbd_share_config *share_config_request(struct ksmbd_work *work,
 				goto out;
 			}
 
-			ret = kern_path(share->path, 0, &share->vfs_path);
+			ret = share_config_resolve_path(share);
 			ksmbd_revert_fsids(work);
 			if (ret) {
 				ksmbd_debug(SMB, "failed to access '%s'\n",
 					    share->path);
-				/* Avoid put_path() */
+				/* No path reference is retained on failure. */
 				kfree(share->path);
 				share->path = NULL;
 			}
fs/smb/server/mgmt/share_config.h +2 -0
index d4ac2dd4de204..baa9f9ed91cde 100644
@@ -16,8 +16,10 @@ struct ksmbd_work;
 struct ksmbd_share_config {
 	char			*name;
 	char			*path;
+	char			*real_path;
 
 	unsigned int		path_sz;
+	unsigned int		real_path_sz;
 	unsigned int		flags;
 	struct list_head	veto_list;
 
fs/smb/server/vfs_cache.c +7 -5
index 2621d2cffe619..b1ee76949a2ea 100644
@@ -1355,6 +1355,8 @@ void ksmbd_free_global_file_table(void)
 int ksmbd_validate_name_reconnect(struct ksmbd_share_config *share,
 				  struct ksmbd_file *fp, char *name)
 {
+	const char *share_path = share->real_path;
+	size_t share_path_sz = share->real_path_sz;
 	char *pathname, *ab_pathname;
 	int ret = 0;
 
@@ -1371,14 +1373,14 @@ int ksmbd_validate_name_reconnect(struct ksmbd_share_config *share,
 	if (name) {
 		size_t len = strlen(ab_pathname);
 
-		if (len == share->path_sz && !strncmp(ab_pathname, share->path, len)) {
+		if (len == share_path_sz && !strncmp(ab_pathname, share_path, len)) {
 			/* the durable fp is the share root itself */
 			if (name[0])
 				ret = -EINVAL;
-		} else if (len <= share->path_sz ||
-			   strncmp(ab_pathname, share->path, share->path_sz) ||
-			   ab_pathname[share->path_sz] != '/' ||
-			   strcmp(&ab_pathname[share->path_sz + 1], name)) {
+		} else if (len <= share_path_sz ||
+			   strncmp(ab_pathname, share_path, share_path_sz) ||
+			   ab_pathname[share_path_sz] != '/' ||
+			   strcmp(&ab_pathname[share_path_sz + 1], name)) {
 			ret = -EINVAL;
 		}
 		if (ret)
Signature · 1 line
2.53.0
author maintainer
#534 lore raw

PATCH 530/816 ksmbd: fix durable reconnects for root shares

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 25e36df831a47597c03c6239fbc71285e7d714c2 ]

When a share exports "/", ksmbd_validate_name_reconnect() expects another slash after the share path. For a file at /foo, this rejects the valid reconnect name "foo" even though the file is in the share.

Compare the requested name with the rendered file path after its leading slash when the resolved share root is "/". Keep the exact-root/empty-name check and reject rendered paths without an initial slash.

Fixes c8efcc786146 ("ksmbd: add support for durable handles v1/v2")
---
 fs/smb/server/vfs_cache.c | 4 ++++
 1 file changed, 4 insertions(+)
fs/smb/server/vfs_cache.c +4 -0
index b1ee76949a2ea..52389fff3d4a0 100644
@@ -1377,6 +1377,10 @@ int ksmbd_validate_name_reconnect(struct ksmbd_share_config *share,
 			/* the durable fp is the share root itself */
 			if (name[0])
 				ret = -EINVAL;
+		} else if (share_path_sz == 1 && share_path[0] == '/') {
+			if (ab_pathname[0] != '/' ||
+			    strcmp(ab_pathname + 1, name))
+				ret = -EINVAL;
 		} else if (len <= share_path_sz ||
 			   strncmp(ab_pathname, share_path, share_path_sz) ||
 			   ab_pathname[share_path_sz] != '/' ||
Signature · 1 line
2.53.0
author maintainer
#535 lore raw

PATCH 531/816 selftests/proc: proc-pid-vm: fix unused variable warning on non-x86

In reply to Greg Kroah-Hartman

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

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

[ Upstream commit c4d9005e7e1ee6ce277f47cf53d44fc5b90b287b ]

g_vsyscall is only used by the x86_64 test, so clang builds for other architectures get:

proc-pid-vm.c:224:21: warning: unused variable 'g_vsyscall' [-Wunused-variable]

The vsyscall strings next to it had the same problem and were marked __maybe_unused for it. Move all of the vsyscall variables into the __x86_64__ block that uses them instead, and drop those annotations along with the local __maybe_unused fallback that was added for them.

Fixes 17415606f9d8 ("tools/testing/selftests/proc/proc-pid-vm.c: test with vsyscall in mind")
Assisted-by LLM
Cc Shuah Khan <[email protected]>
Cc Alexey Dobriyan <[email protected]>
[ sashal: Kept this tree's #include "../kselftest.h" and skipped the __maybe_unused removals, since that fallback and those annotations were never present here. ]
---
 tools/testing/selftests/proc/proc-pid-vm.c | 2 --
 1 file changed, 2 deletions(-)
tools/testing/selftests/proc/proc-pid-vm.c +0 -2
index d04685771952a..2ec6e0fd20e01 100644
@@ -210,7 +210,6 @@ static int make_exe(const uint8_t *payload, size_t len)
 
 	return fd1;
 }
-#endif
 
 /*
  * 0: vsyscall VMA doesn't exist	vsyscall=none
@@ -226,7 +225,6 @@ static const char str_vsyscall_1[] =
 static const char str_vsyscall_2[] =
 "ffffffffff600000-ffffffffff601000 r-xp 00000000 00:00 0                  [vsyscall]\n";
 
-#ifdef __x86_64__
 static void sigaction_SIGSEGV(int _, siginfo_t *__, void *___)
 {
 	_exit(g_vsyscall);
Signature · 1 line
2.53.0
author maintainer
#536 lore raw

PATCH 532/816 ALSA: hda/realtek: Add mute and mic-mute LEDs for HP ENVY 16 (103c:8be5)

In reply to Greg Kroah-Hartman

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

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

From: Ajanesh Lal <[email protected]>

[ Upstream commit ed7995e4ec3789a90e37eb826bfccf43cc85d2fd ]

The HP ENVY Laptop 16-h1xxx (PCI SSID 103c:8be5) uses an ALC245 codec with CS35L41 I2C speaker amplifiers. No LED fixup is applied for this subsystem ID, so the speaker mute LED and the microphone mute LED are never driven and do not follow their keys.

Add a fixup that calls the existing ALC245 mute LED COEF helper and the GPIO mic-mute LED helper directly, then chains to the CS35L41 I2C amplifier setup so the speakers keep working. Use it for 103c:8be5.

Tested on an HP ENVY Laptop 16-h1xxx running kernel 7.2.11: the hda::mute and hda::micmute LEDs appear and follow their keys, and the speaker amplifiers still bind (CS35L41 Bound in dmesg). The mic LED GPIO pin and polarity are not verified on other hardware.

Fixes aa8e3ef4fe53 ("ALSA: hda/realtek: Add quirks for various HP ENVY models")
Assisted-by Claude:claude-haiku-5-5
[ sashal: Ported the four hunks by hand to the older file path, placing the enum value and fixup entry after existing neighbors because the upstream anchor entry is missing. ]
---
 sound/pci/hda/patch_realtek.c | 17 ++++++++++++++++-
 1 file changed, 16 insertions(+), 1 deletion(-)
sound/pci/hda/patch_realtek.c +16 -1
index 726fc58b17ee7..f2673ed691d73 100644
@@ -4797,6 +4797,14 @@ static void alc245_fixup_hp_mute_led_coefbit(struct hda_codec *codec,
 	}
 }
 
+/* mute LED via COEF bit and mic-mute LED via GPIO, called directly */
+static void alc245_fixup_cs35l41_mute_micmute(struct hda_codec *codec,
+					      const struct hda_fixup *fix, int action)
+{
+	alc245_fixup_hp_mute_led_coefbit(codec, fix, action);
+	alc245_fixup_hp_gpio_led(codec, fix, action);
+}
+
 static void alc245_fixup_hp_mute_led_v1_coefbit(struct hda_codec *codec,
 					  const struct hda_fixup *fix,
 					  int action)
@@ -8235,6 +8243,7 @@ enum {
 	ALC287_FIXUP_CS35L41_I2C_2,
 	ALC287_FIXUP_CS35L41_I2C_2_HP_GPIO_LED,
 	ALC287_FIXUP_CS35L41_I2C_2_HP_MUTE_LEDS,
+	ALC245_FIXUP_CS35L41_I2C_2_MUTE_MICMUTE_LED,
 	ALC287_FIXUP_CS35L41_I2C_4,
 	ALC245_FIXUP_CS35L41_SPI_1,
 	ALC245_FIXUP_CS35L41_SPI_2,
@@ -10444,6 +10453,12 @@ static const struct hda_fixup alc269_fixups[] = {
 		.chained = true,
 		.chain_id = ALC245_FIXUP_HP_X360_MUTE_LEDS,
 	},
+	[ALC245_FIXUP_CS35L41_I2C_2_MUTE_MICMUTE_LED] = {
+		.type = HDA_FIXUP_FUNC,
+		.v.func = alc245_fixup_cs35l41_mute_micmute,
+		.chained = true,
+		.chain_id = ALC287_FIXUP_CS35L41_I2C_2,
+	},
 	[ALC287_FIXUP_CS35L41_I2C_4] = {
 		.type = HDA_FIXUP_FUNC,
 		.v.func = cs35l41_fixup_i2c_four,
@@ -11180,7 +11195,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = {
 	SND_PCI_QUIRK(0x103c, 0x8be1, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2),
 	SND_PCI_QUIRK(0x103c, 0x8be2, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2),
 	SND_PCI_QUIRK(0x103c, 0x8be3, "HP Envy 15", ALC287_FIXUP_CS35L41_I2C_2),
-	SND_PCI_QUIRK(0x103c, 0x8be5, "HP Envy 16", ALC287_FIXUP_CS35L41_I2C_2),
+	SND_PCI_QUIRK(0x103c, 0x8be5, "HP Envy 16", ALC245_FIXUP_CS35L41_I2C_2_MUTE_MICMUTE_LED),
 	SND_PCI_QUIRK(0x103c, 0x8be6, "HP Envy 16", ALC287_FIXUP_CS35L41_I2C_2),
 	SND_PCI_QUIRK(0x103c, 0x8be7, "HP Envy 17", ALC287_FIXUP_CS35L41_I2C_2),
 	SND_PCI_QUIRK(0x103c, 0x8be8, "HP Envy 17", ALC287_FIXUP_CS35L41_I2C_2_HP_MUTE_LEDS),
Signature · 1 line
2.53.0
author maintainer
#537 lore raw

PATCH 533/816 perf lock contention: Filter events before creating lock_stat

In reply to Greg Kroah-Hartman

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

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

From: Ian Rogers <[email protected]>

[ Upstream commit c58d1598e79554cc8f587668ab2ebcaeb616b076 ]

In report_lock_contention_begin_event(), lock_stat_findnew() was called before checking filters.nr_types (-Y), filters.nr_addrs (-L), and match_callstack_filter() (-S).

When a filtered-out lock event (such as a mutex contention when running with -Y spinlock) shared the same aggregation key as a subsequent matching event (for example, contention on the mutex's internal wait_lock spinlock from the same caller), the first event created the lock_stat entry with the filtered-out lock's flags and the second event reused that entry, causing non-spinlock entries to appear in -Y spinlock output.

Check the type, address, and callstack filters before looking up or creating the lock_stat entry.

Fixes b4a7eff93c39f985 ("perf lock contention: Add -Y/--type-filter option")
[ sashal: adjusted the lock_contention_caller() call to pass the extra evsel argument, and kept the existing -ENOMEM return on get_callstack() failure instead of 0. ]
---
 tools/perf/builtin-lock.c | 61 +++++++++++++++++++++------------------
 1 file changed, 33 insertions(+), 28 deletions(-)
tools/perf/builtin-lock.c +33 -28
index 3d490ea46551b..1de2ee1464fee 100644
@@ -1070,6 +1070,7 @@ static int report_lock_contention_begin_event(struct evsel *evsel,
 	struct machine *machine = &session->machines.host;
 	struct map *kmap;
 	struct symbol *sym;
+	u64 *callstack = NULL;
 
 	ret = get_key_by_aggr_mode(&key, addr, evsel, sample);
 	if (ret < 0)
@@ -1105,33 +1106,6 @@ static int report_lock_contention_begin_event(struct evsel *evsel,
 		}
 	}
 
-	ls = lock_stat_find(key);
-	if (!ls) {
-		char buf[128];
-		const char *name = "";
-
-		switch (aggr_mode) {
-		case LOCK_AGGR_ADDR:
-			sym = machine__find_kernel_symbol(machine, key, &kmap);
-			if (sym)
-				name = sym->name;
-			break;
-		case LOCK_AGGR_CALLER:
-			name = buf;
-			if (lock_contention_caller(evsel, sample, buf, sizeof(buf)) < 0)
-				name = "Unknown";
-			break;
-		case LOCK_AGGR_CGROUP:
-		case LOCK_AGGR_TASK:
-		default:
-			break;
-		}
-
-		ls = lock_stat_findnew(key, name, flags);
-		if (!ls)
-			return -ENOMEM;
-	}
-
 	if (filters.nr_types) {
 		bool found = false;
 
@@ -1161,7 +1135,7 @@ static int report_lock_contention_begin_event(struct evsel *evsel,
 	}
 
 	if (needs_callstack()) {
-		u64 *callstack = get_callstack(sample, max_stack_depth);
+		callstack = get_callstack(sample, max_stack_depth);
 		if (callstack == NULL)
 			return -ENOMEM;
 
@@ -1169,7 +1143,38 @@ static int report_lock_contention_begin_event(struct evsel *evsel,
 			free(callstack);
 			return 0;
 		}
+	}
+
+	ls = lock_stat_find(key);
+	if (!ls) {
+		char buf[128];
+		const char *name = "";
+
+		switch (aggr_mode) {
+		case LOCK_AGGR_ADDR:
+			sym = machine__find_kernel_symbol(machine, key, &kmap);
+			if (sym)
+				name = sym->name;
+			break;
+		case LOCK_AGGR_CALLER:
+			name = buf;
+			if (lock_contention_caller(evsel, sample, buf, sizeof(buf)) < 0)
+				name = "Unknown";
+			break;
+		case LOCK_AGGR_CGROUP:
+		case LOCK_AGGR_TASK:
+		default:
+			break;
+		}
+
+		ls = lock_stat_findnew(key, name, flags);
+		if (!ls) {
+			free(callstack);
+			return -ENOMEM;
+		}
+	}
 
+	if (callstack) {
 		if (ls->callstack == NULL)
 			ls->callstack = callstack;
 		else
Signature · 1 line
2.53.0
author maintainer
#538 lore raw

PATCH 534/816 gpiolib: Propagate emulated drive errors when setting arrays

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit 15665047024e30f9c2227563d03034061c99ac2c ]

gpiod_set_array_value_complex() ignores errors from the open-drain and open-source emulation helpers. If a direction change fails, GPIO_V2_LINE_SET_VALUES_IOCTL still reports success, including when updating a single line.

Return the first emulation error after freeing the temporary bitmaps. Keep updates already made to earlier lines and stop processing the remaining lines, as for errors from gpiochip_set_multiple().

Fixes 8ce258f62f90 ("gpiolib: make value setters have return values")

Signed-off-by:

[ sashal: adjusted context to use the older FLAG_OPEN_DRAIN/FLAG_OPEN_SOURCE names and added the cleanup_bitmap label in this tree's function layout. ]
---
 drivers/gpio/gpiolib.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
drivers/gpio/gpiolib.c +7 -2
index 28a1a184e580d..c9dae5cf4db34 100644
@@ -3572,9 +3572,13 @@ int gpiod_set_array_value_complex(bool raw, bool can_sleep,
 			 * open drain and open source outputs are set individually
 			 */
 			if (test_bit(FLAG_OPEN_DRAIN, &desc->flags) && !raw) {
-				gpio_set_open_drain_value_commit(desc, value);
+				ret = gpio_set_open_drain_value_commit(desc, value);
+				if (ret)
+					goto cleanup_bitmap;
 			} else if (test_bit(FLAG_OPEN_SOURCE, &desc->flags) && !raw) {
-				gpio_set_open_source_value_commit(desc, value);
+				ret = gpio_set_open_source_value_commit(desc, value);
+				if (ret)
+					goto cleanup_bitmap;
 			} else {
 				__set_bit(hwgpio, mask);
 				__assign_bit(hwgpio, bits, value);
@@ -3592,6 +3596,7 @@ int gpiod_set_array_value_complex(bool raw, bool can_sleep,
 		if (count != 0)
 			ret = gpiochip_set_multiple(guard.gc, mask, bits);
 
+cleanup_bitmap:
 		if (mask != fastpath_mask)
 			bitmap_free(mask);
 		if (bits != fastpath_bits)
Signature · 1 line
2.53.0
author maintainer
#539 lore raw

PATCH 535/816 zram: fix short reads from block_state

In reply to Greg Kroah-Hartman

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

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

From: Pooyan Azad <[email protected]>

[ Upstream commit 372012202260db088b489ed00059c4571a602552 ]

read_block_state() formats each entry directly into the buffer supplied by read(). If the remaining buffer is too small for one complete record, snprintf() returns the full record length and the function stops without copying data or advancing the file position. A read from this debugfs file which is smaller than a record therefore returns zero at a non-EOF position and cannot make progress.

Convert block_state to seq_file so formatted records are buffered independently of the userspace read size. Keep dev_lock held across each seq_file iteration and continue to protect individual entries with their slot locks.

[ sashal: adjusted context to use the older init_lock, zram_slot_lock() and timespec64 helpers in this tree. ]

---
 drivers/block/zram/zram_drv.c | 105 +++++++++++++++++-----------------
 1 file changed, 53 insertions(+), 52 deletions(-)
drivers/block/zram/zram_drv.c +53 -52
index db059577fc5bd..1d2a686f4d125 100644
@@ -856,72 +856,73 @@ static void zram_debugfs_destroy(void)
 	debugfs_remove_recursive(zram_debugfs_root);
 }
 
-static ssize_t read_block_state(struct file *file, char __user *buf,
-				size_t count, loff_t *ppos)
+static void *zram_block_state_start(struct seq_file *seq, loff_t *pos)
 {
-	char *kbuf;
-	ssize_t index, written = 0;
-	struct zram *zram = file->private_data;
+	struct zram *zram = seq->private;
 	unsigned long nr_pages;
 
-	kbuf = kvmalloc(count, GFP_KERNEL);
-	if (!kbuf)
-		return -ENOMEM;
-
 	down_read(&zram->init_lock);
-	if (!init_done(zram)) {
-		up_read(&zram->init_lock);
-		kvfree(kbuf);
-		return -EINVAL;
-	}
+	if (!init_done(zram))
+		return ERR_PTR(-EINVAL);
 
 	nr_pages = zram->disksize >> PAGE_SHIFT;
+	if (*pos >= nr_pages)
+		return NULL;
 
-	for (index = *ppos; index < nr_pages; index++) {
-		int copied;
-		struct timespec64 ts;
+	return pos;
+}
 
-		zram_slot_lock(zram, index);
-		if (!zram_allocated(zram, index))
-			goto next;
+static void *zram_block_state_next(struct seq_file *seq, void *v, loff_t *pos)
+{
+	struct zram *zram = seq->private;
+	unsigned long nr_pages = zram->disksize >> PAGE_SHIFT;
 
-		ts = ktime_to_timespec64(zram->table[index].ac_time);
-		copied = snprintf(kbuf + written, count,
-			"%12zd %12lld.%06lu %c%c%c%c%c%c\n",
-			index, (s64)ts.tv_sec,
-			ts.tv_nsec / NSEC_PER_USEC,
-			zram_test_flag(zram, index, ZRAM_SAME) ? 's' : '.',
-			zram_test_flag(zram, index, ZRAM_WB) ? 'w' : '.',
-			zram_test_flag(zram, index, ZRAM_HUGE) ? 'h' : '.',
-			zram_test_flag(zram, index, ZRAM_IDLE) ? 'i' : '.',
-			zram_get_priority(zram, index) ? 'r' : '.',
-			zram_test_flag(zram, index,
-				       ZRAM_INCOMPRESSIBLE) ? 'n' : '.');
-
-		if (count <= copied) {
-			zram_slot_unlock(zram, index);
-			break;
-		}
-		written += copied;
-		count -= copied;
-next:
-		zram_slot_unlock(zram, index);
-		*ppos += 1;
-	}
+	++*pos;
+	if (*pos >= nr_pages)
+		return NULL;
+
+	return pos;
+}
+
+static void zram_block_state_stop(struct seq_file *seq, void *v)
+{
+	struct zram *zram = seq->private;
 
 	up_read(&zram->init_lock);
-	if (copy_to_user(buf, kbuf, written))
-		written = -EFAULT;
-	kvfree(kbuf);
+}
 
-	return written;
+static int zram_block_state_show(struct seq_file *seq, void *v)
+{
+	struct zram *zram = seq->private;
+	ssize_t index = *(loff_t *)v;
+	struct timespec64 ts;
+
+	zram_slot_lock(zram, index);
+	if (zram_allocated(zram, index)) {
+		ts = ktime_to_timespec64(zram->table[index].ac_time);
+		seq_printf(seq, "%12zd %12lld.%06lu %c%c%c%c%c%c\n",
+			   index, (s64)ts.tv_sec,
+			   ts.tv_nsec / NSEC_PER_USEC,
+			   zram_test_flag(zram, index, ZRAM_SAME) ? 's' : '.',
+			   zram_test_flag(zram, index, ZRAM_WB) ? 'w' : '.',
+			   zram_test_flag(zram, index, ZRAM_HUGE) ? 'h' : '.',
+			   zram_test_flag(zram, index, ZRAM_IDLE) ? 'i' : '.',
+			   zram_get_priority(zram, index) ? 'r' : '.',
+			   zram_test_flag(zram, index,
+					  ZRAM_INCOMPRESSIBLE) ? 'n' : '.');
+	}
+	zram_slot_unlock(zram, index);
+
+	return 0;
 }
 
-static const struct file_operations proc_zram_block_state_op = {
-	.open = simple_open,
-	.read = read_block_state,
-	.llseek = default_llseek,
+static const struct seq_operations zram_block_state_sops = {
+	.start = zram_block_state_start,
+	.next = zram_block_state_next,
+	.stop = zram_block_state_stop,
+	.show = zram_block_state_show,
 };
+DEFINE_SEQ_ATTRIBUTE(zram_block_state);
 
 static void zram_debugfs_register(struct zram *zram)
 {
@@ -931,7 +932,7 @@ static void zram_debugfs_register(struct zram *zram)
 	zram->debugfs_dir = debugfs_create_dir(zram->disk->disk_name,
 						zram_debugfs_root);
 	debugfs_create_file("block_state", 0400, zram->debugfs_dir,
-				zram, &proc_zram_block_state_op);
+				zram, &zram_block_state_fops);
 }
 
 static void zram_debugfs_unregister(struct zram *zram)
Signature · 1 line
2.53.0
author maintainer
#540 lore raw

PATCH 536/816 ceph: wait for pending fscache write in write_folio_nounlock()

In reply to Greg Kroah-Hartman

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

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

From: Tal Zussman <[email protected]>

[ Upstream commit 3f7655f0d9186656c6f1cbc012a39c866d4aaabf ]

write_folio_nounlock() marks the folio with PG_private_2 via ceph_set_page_fscache() and starts an async write to the cache via ceph_fscache_write_to_cache(). PG_private_2 is only cleared once that write completes.

If the OSD write fails, the error paths return without waiting for the cache write. On retry, ceph_find_incompatible() would wait for writeback, but not for PG_private_2, before calling write_folio_nounlock() again, which would trip the VM_BUG_ON_FOLIO() in folio_start_private_2().

Wait for any pending cache write before starting writeback on the folio. Do so before bumping the writeback congestion count and allocating the possibly mempool-backed OSD request, so that a thread sleeping on the cache I/O does not hold either while it waits. Add ceph_folio_wait_fscache(), a wrapper for folio_wait_private_2(), and use it.

Fixes 1702e7973410 ("ceph: add fscache writeback support")
[ sashal: Adjusted the context line so the new helper is inserted above ceph_fscache_write_terminated(), which already takes the extra was_async parameter. ]
---
 fs/ceph/addr.c | 12 ++++++++++++
 1 file changed, 12 insertions(+)
fs/ceph/addr.c +12 -0
index 7ad96fcdcd20c..01c9800bd8d07 100644
@@ -560,6 +560,11 @@ static void ceph_set_page_fscache(struct page *page)
 	folio_start_private_2(page_folio(page)); /* [DEPRECATED] */
 }
 
+static void ceph_folio_wait_fscache(struct folio *folio)
+{
+	folio_wait_private_2(folio); /* [DEPRECATED] */
+}
+
 static void ceph_fscache_write_terminated(void *priv, ssize_t error, bool was_async)
 {
 	struct inode *inode = priv;
@@ -581,6 +586,10 @@ static inline void ceph_set_page_fscache(struct page *page)
 {
 }
 
+static inline void ceph_folio_wait_fscache(struct folio *folio)
+{
+}
+
 static inline void ceph_fscache_write_to_cache(struct inode *inode, u64 off, u64 len, bool caching)
 {
 }
@@ -784,6 +793,9 @@ static int write_folio_nounlock(struct folio *folio,
 	      ceph_vinop(inode), folio, folio->index, page_off, wlen, snapc,
 	      snapc->seq);
 
+	/* wait for a cache write left pending by a previously failed attempt */
+	ceph_folio_wait_fscache(folio);
+
 	if (atomic_long_inc_return(&fsc->writeback_count) >
 	    CONGESTION_ON_THRESH(fsc->mount_options->congestion_kb))
 		fsc->write_congested = true;
Signature · 1 line
2.53.0
author maintainer
#541 lore raw

PATCH 537/816 cgroup/cpuset: Prevent recursive call of remote_cpus_update() via update_cpumasks_hier()

In reply to Greg Kroah-Hartman

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

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

From: Waiman Long <[email protected]>

[ Upstream commit 10a6f00d82544a1baa901de8d28f41f28c364995 ]

Guopeng reports that changing the cpumask of a remote partition root may set the effective_cpus of the top_cpuset incorrectly. It is due to the following call sequence:

update_cpumask()
-> partition_cpus_change()

    -> remote_cpus_update()
     -> update_sibling_cpumasks()
      -> update_cpumasks_hier()
       -> remote_cpus_update()

The second remote_cpus_update() call passes in the cs->effective_xcpus instead of the trialcs->effective_xcpus of the first remote_cpus_update() call. As a result, the second call can revert what has been done in the first call leading to incorrect effective_cpus of the top_cpuset as well as subpartitions_cpus.

Fix that by adding a new remote_partition_updating flag into the cpuset structure to indicate that a remote partition is being updated and update_cpumasks_hier() should skip the whole subtree as update_cpumask() or update_exclusive_cpumask() which calls partition_cpus_change() will eventually calls update_cpumasks_hier() for that subtree anyway.

This new flag is currently set only in remote_cpus_update() to prevent recursive call of remote_cpus_update() on the same cpuset.

A test case is added to test_cpuset_prs.sh to verify this change.

Fixes f62a5d39368e ("cgroup/cpuset: Remove remote_partition_check() & make update_cpumasks_hier() handle remote partition")
[ sashal: Selftest row adapted to C1-6:X1-4:S+ for A1 (instead of CX1-6) so setup passes this tree's validation, and the kernel context uses the local compute_effective_exclusive_cpumask() and partition_xcpus_add() signatures. ]
---
 kernel/cgroup/cpuset-internal.h                   |  5 +++++
 kernel/cgroup/cpuset.c                            | 13 +++++++++----
 tools/testing/selftests/cgroup/test_cpuset_prs.sh |  1 +
 3 files changed, 15 insertions(+), 4 deletions(-)
kernel/cgroup/cpuset-internal.h +5 -0
index 6c9916e85efd1..1f3fef06ee45b 100644
@@ -162,6 +162,11 @@ struct cpuset {
 	/* partition root state */
 	int partition_root_state;
 
+	/*
+	 * Set to true when a remote partition is undergoing update.
+	 */
+	bool remote_partition_updating;
+
 	/*
 	 * number of SCHED_DEADLINE tasks attached to this cpuset, so that we
 	 * know when to rebuild associated root domain bandwidth information.
kernel/cgroup/cpuset.c +9 -4
index b1af98c19891e..99f8d505bea3a 100644
@@ -1590,6 +1590,7 @@ static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus,
 			goto invalidate;
 	}
 
+	cs->remote_partition_updating = true;
 	spin_lock_irq(&callback_lock);
 	if (adding)
 		isolcpus_updated += partition_xcpus_add(prs, NULL, tmp->addmask);
@@ -1612,6 +1613,7 @@ static void remote_cpus_update(struct cpuset *cs, struct cpumask *xcpus,
 	 */
 	cpuset_update_tasks_cpumask(&top_cpuset, tmp->new_cpus);
 	update_sibling_cpumasks(&top_cpuset, NULL, tmp);
+	cs->remote_partition_updating = false;
 	return;
 
 invalidate:
@@ -2075,16 +2077,19 @@ static void update_cpumasks_hier(struct cpuset *cs, struct tmpmasks *tmp,
 		old_prs = new_prs = cp->partition_root_state;
 
 		/*
-		 * For child remote partition root (!= cs), we need to call
-		 * remote_cpus_update() if effective_xcpus will be changed.
-		 * Otherwise, we can skip the whole subtree.
+		 * For a child remote partition with remote_partition_updating
+		 * set, we can skip the whole subtree as the this function will
+		 * be called eventually. We can also skip the subtree if the
+		 * effective_xcpus isn't going to be changed. Otherwise, we
+		 * will have to call remote_cpus_update().
 		 *
 		 * remote_cpus_update() will reuse tmp->new_cpus only after
 		 * its value is being processed.
 		 */
 		if (remote && (cp != cs)) {
 			compute_effective_exclusive_cpumask(cp, tmp->new_cpus, NULL);
-			if (cpumask_equal(cp->effective_xcpus, tmp->new_cpus)) {
+			if (cp->remote_partition_updating ||
+			    cpumask_equal(cp->effective_xcpus, tmp->new_cpus)) {
 				pos_css = css_rightmost_descendant(pos_css);
 				continue;
 			}
tools/testing/selftests/cgroup/test_cpuset_prs.sh +1 -0
index f6bc762705abc..f52678bb2efee 100755
@@ -275,6 +275,7 @@ TEST_MATRIX=(
 	" C0-3:S+ C1-3:S+ C2-3    C4    X2-3   X2-3  X2-3:P2 P2:C4-5 0 A3:2-3|B1:4-5 A3:P2|B1:P2 2-5"
 	" C4:X0-3:S+ X1-3:S+ X2-3  .      .      P2     .      .     0 A1:4|A2:1-3|A3:1-3 A2:P2 1-3"
 	" C4:X0-3:S+ X1-3:S+ X2-3  .      .      .      P2     .     0 A1:4|A2:4|A3:2-3 A3:P2 2-3"
+	"  C1-6:X1-4:S+ C1-4:P1 .   C4-5     .    C1-3     .      .     0 A1:4-6|A2:1-3|B1:4-5 A2:P1"
 
 	# Nested remote/local partition tests
 	" C0-3:S+ C1-3:S+ C2-3   C4-5   X2-3  X2-3:P1   P2     P1    0 A1:0-1|A2:|A3:2-3|B1:4-5 \
Signature · 1 line
2.53.0
author maintainer
#542 lore raw

PATCH 538/816 net: dsa: mt7530: trap frames to conduit in MFC on EN7581 and AN7583

In reply to Greg Kroah-Hartman

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

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

From: Tao Gong <[email protected]>

[ Upstream commit a58b221496dd576191095d12996f39cee58cf6a8 ]

On EN7581, STP BPDUs received on switch user ports never reach the CPU.

Like MT7531 and MT7988, EN7581 and AN7583 only set the CPU port bitmap in MT7531_CFC and are skipped by mt753x_conduit_state_change(). On EN7581 this is not enough: trapped BPDUs reach the CPU only when MT7530_CPU_EN and MT7530_CPU_PORT are also set in MT753X_MFC. Add EN7581 and AN7583 to mt753x_conduit_state_change().

Tested on an AN7581 board (Gemtek W1700K, airoha,en7581-switch), where only lan3 and lan4 are switch user ports. With RSTP BPDUs arriving on lan4:
- without this patch, none reached the CPU;
- setting CPU_EN and CPU_PORT by hand delivered them, and clearing them stopped them;
- with this patch, they are received from boot.

Only BPDUs were tested. AN7583 is untested and is included because the driver sets it up like EN7581.

Fixes 2b0229f67932 ("net: dsa: mt7530: Add EN7581 support")
Fixes d76556db10bf ("net: dsa: mt7530: Add AN7583 support")
[ sashal: Dropped the ID_EN7528 and ID_AN7583 references, which don't exist here, so the condition only adds ID_EN7581, and removed the AN7583 sentence from the comment. ]
---
 drivers/net/dsa/mt7530.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
drivers/net/dsa/mt7530.c +4 -2
index 8c9eafb6af7be..8db1095720c1e 100644
@@ -3137,9 +3137,11 @@ mt753x_conduit_state_change(struct dsa_switch *ds,
 
 	/* Set the CPU port to trap frames to for MT7530. Trapped frames will be
 	 * forwarded to the numerically smallest CPU port whose conduit
-	 * interface is up.
+	 * interface is up. On EN7581, trapped BPDUs do not reach the CPU port
+	 * without this, even with the CPU port bitmap set.
 	 */
-	if (priv->id != ID_MT7530 && priv->id != ID_MT7621)
+	if (priv->id != ID_MT7530 && priv->id != ID_MT7621 &&
+	    priv->id != ID_EN7581)
 		return;
 
 	mask = BIT(cpu_dp->index);
Signature · 1 line
2.53.0
author maintainer
#543 lore raw

PATCH 539/816 tcp: Fix fastreuse cache initialization on first bind

In reply to Greg Kroah-Hartman

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

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

From: Zhewei Yuan <[email protected]>

[ Upstream commit 947ccedf683ed6cc53c1f88ac9eb8747e4567ed6 ]

inet_csk_update_fastreuse() initializes the reuse caches only when tb->bhash2 is empty, but both inet_csk_get_port() and __inet_inherit_port() link tb2 before calling it, so the first-bind branch is never taken.

As a result, SO_REUSEADDR binds never get fastreuse=1 and keep scanning existing owners, and SO_REUSEPORT starts in STRICT instead of ANY.

Initialize the caches when tb2 is the only entry in tb->bhash2 and has no owners. Timewait sockets are also linked on tb2->owners, so this is equivalent to the old hlist_empty(&tb->owners) test.

Found by manual code inspection and confirmed with GDB. Binding 16000 SO_REUSEADDR sockets to one address/port in a KVM guest takes 4.18 s before and 19.4 ms after this patch. Existing bind/reuse selftests pass. Analysis and testing were assisted by an AI tool (Codex).

Fixes 8002d44fe84d ("tcp: Check hlist_empty(&tb->bhash2) instead of hlist_empty(&tb->owners).")
[ sashal: Added a tb2 parameter to inet_csk_update_fastreuse() and its two callers, since the older tree's function lacks it, so the new singular-bhash2 and empty-owners check can use it. ]
---
 include/net/inet_connection_sock.h | 1 +
 net/ipv4/inet_connection_sock.c    | 6 ++++--
 net/ipv4/inet_hashtables.c         | 2 +-
 3 files changed, 6 insertions(+), 3 deletions(-)
include/net/inet_connection_sock.h +1 -0
index 2ff01a8fbef2b..d97561e4bef8f 100644
@@ -326,6 +326,7 @@ void inet_csk_addr2sockaddr(struct sock *sk, struct sockaddr *uaddr);
 
 /* update the fast reuse flag when adding a socket */
 void inet_csk_update_fastreuse(struct inet_bind_bucket *tb,
+			       struct inet_bind2_bucket *tb2,
 			       struct sock *sk);
 
 struct dst_entry *inet_csk_update_pmtu(struct sock *sk, u32 mtu);
net/ipv4/inet_connection_sock.c +4 -2
index 5b6436e6f242c..c869986442ef3 100644
@@ -443,12 +443,14 @@ static inline int sk_reuseport_match(struct inet_bind_bucket *tb,
 }
 
 void inet_csk_update_fastreuse(struct inet_bind_bucket *tb,
+			       struct inet_bind2_bucket *tb2,
 			       struct sock *sk)
 {
 	kuid_t uid = sock_i_uid(sk);
 	bool reuse = sk->sk_reuse && sk->sk_state != TCP_LISTEN;
 
-	if (hlist_empty(&tb->bhash2)) {
+	if (hlist_is_singular_node(&tb2->bhash_node, &tb->bhash2) &&
+	    hlist_empty(&tb2->owners)) {
 		tb->fastreuse = reuse;
 		if (sk->sk_reuseport) {
 			tb->fastreuseport = FASTREUSEPORT_ANY;
@@ -572,7 +574,7 @@ int inet_csk_get_port(struct sock *sk, unsigned short snum)
 	}
 
 success:
-	inet_csk_update_fastreuse(tb, sk);
+	inet_csk_update_fastreuse(tb, tb2, sk);
 
 	if (!inet_csk(sk)->icsk_bind_hash)
 		inet_bind_hash(sk, tb, tb2, port);
net/ipv4/inet_hashtables.c +1 -1
index a597c176a5e45..ca6726a8c4a1d 100644
@@ -277,7 +277,7 @@ int __inet_inherit_port(const struct sock *sk, struct sock *child)
 		}
 	}
 	if (update_fastreuse)
-		inet_csk_update_fastreuse(tb, child);
+		inet_csk_update_fastreuse(tb, tb2, child);
 	inet_bind_hash(child, tb, tb2, port);
 	spin_unlock(&head2->lock);
 	spin_unlock(&head->lock);
Signature · 1 line
2.53.0
author maintainer
#544 lore raw

PATCH 540/816 tls: keep TX and RX hardware offload on the same device

In reply to Greg Kroah-Hartman

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

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

From: Rishikesh Jethwani <[email protected]>

[ Upstream commit 1c8a70075235cd733095532a97f2405037c52a7b ]

After TX is offloaded on device A, a route change, or a change in the usable-slave set of an 802.3ad or balance-xor (layer3+4) bond, can make RX setup program device B. tls_device_attach() sees the existing TLS destructor and keeps ctx->netdev pointing at A. The RX driver state on B is then untracked: tls_dev_resync() and tls_dev_del() are invoked on A for a context it never created, and neither socket close nor NETDEV_DOWN on B calls tls_dev_del() for B, so the driver context leaks. The reverse setup order has the same problem.

Check the shared device binding under device_offload_lock before each tls_dev_add(). Permit the first attachment and a second direction on the same device. Reject a different device, including when the old binding was cleared by NETDEV_DOWN: the TLS destructor remains installed and tls_device_attach() cannot establish a new binding. Setup then falls back to software for the requested direction.

The RX check precedes allocation and software setup. TX uses its existing resource unwind path without calling the driver. Document the shared binding and clarify that fallback is per direction.

This issue was discovered during code review and subsequently reproduced on hardware using mlx5 and TLS 1.2 AES-GCM-128.

Changing the route between TX and RX setup installed the second direction on a different device. Driver traces showed successful adds on both devices, but both deletes at socket close targeted the first device, leaving an orphaned context on the second. Both setup orders reproduced the leak, even though all current core TLS context counters returned to zero. No crash was observed.

With the fix, the same tests correctly fall back to software for the second direction and leave no orphaned hardware context.

Fixes 4799ac81e52a ("tls: Add rx inline crypto offload")
[ sashal: Replaced kzalloc_obj(*context) with kzalloc(sizeof(*context), GFP_KERNEL) in tls_set_device_offload_rx() because the kzalloc_obj helper is not available. ]
---
 Documentation/networking/tls-offload.rst | 16 ++++++++++------
 net/tls/tls_device.c                     | 24 ++++++++++++++++++++++++
 2 files changed, 34 insertions(+), 6 deletions(-)
Documentation/networking/tls-offload.rst +10 -6
index 5f0dea3d571e3..371cbd2824c65 100644
@@ -76,12 +76,16 @@ During driver initialization device sets the ``NETIF_F_HW_TLS_RX`` and
 pointer in the :c:member:`tlsdev_ops` member of the
 :c:type:`struct net_device <net_device>`.
 
-When TLS cryptographic connection state is installed on a ``ktls`` socket
-(note that it is done twice, once for RX and once for TX direction,
-and the two are completely independent), the kernel checks if the underlying
-network device is offload-capable and attempts the offload. In case offload
-fails the connection is handled entirely in software using the same mechanism
-as if the offload was never tried.
+TLS cryptographic connection state is installed separately for RX and TX
+on a ``ktls`` socket. For each direction, the kernel checks if the underlying
+network device is offload-capable and attempts the offload. If offload fails,
+that direction is handled in software as if offload had never been tried.
+
+Both hardware directions share one device binding. Once one direction is
+offloaded, the other direction must use the same device. If a route change
+selects a different device, or ``NETDEV_DOWN`` has cleared the binding,
+hardware offload of the other direction is declined and it uses software
+instead.
 
 Offload request is performed via the :c:member:`tls_dev_add` callback of
 :c:type:`struct tlsdev_ops <tlsdev_ops>`:
net/tls/tls_device.c +24 -0
index 099cf5d093689..02a77f2a7a55f 100644
@@ -1030,6 +1030,20 @@ int tls_device_decrypted(struct sock *sk, struct tls_context *tls_ctx)
 	return tls_device_reencrypt(sk, tls_ctx);
 }
 
+/* Both directions share ctx->netdev. A second direction must use that
+ * device; after NETDEV_DOWN clears it, no new direction can be offloaded.
+ */
+static bool tls_device_can_attach(struct tls_context *ctx, struct sock *sk,
+				  struct net_device *netdev)
+{
+	struct net_device *ctx_netdev;
+
+	ctx_netdev = rcu_dereference_protected(ctx->netdev,
+					       lockdep_is_held(&device_offload_lock));
+	return sk->sk_destruct != tls_device_sk_destruct ||
+	       ctx_netdev == netdev;
+}
+
 static void tls_device_attach(struct tls_context *ctx, struct sock *sk,
 			      struct net_device *netdev)
 {
@@ -1165,6 +1179,11 @@ int tls_set_device_offload(struct sock *sk)
 		goto release_lock;
 	}
 
+	if (!tls_device_can_attach(ctx, sk, netdev)) {
+		rc = -EOPNOTSUPP;
+		goto release_lock;
+	}
+
 	ctx->priv_ctx_tx = offload_ctx;
 	rc = netdev->tlsdev_ops->tls_dev_add(netdev, sk, TLS_OFFLOAD_CTX_DIR_TX,
 					     &ctx->crypto_send.info,
@@ -1235,6 +1254,11 @@ int tls_set_device_offload_rx(struct sock *sk, struct tls_context *ctx)
 		goto release_lock;
 	}
 
+	if (!tls_device_can_attach(ctx, sk, netdev)) {
+		rc = -EOPNOTSUPP;
+		goto release_lock;
+	}
+
 	context = kzalloc(sizeof(*context), GFP_KERNEL);
 	if (!context) {
 		rc = -ENOMEM;
Signature · 1 line
2.53.0
author maintainer
#545 lore raw

PATCH 541/816 ksmbd: return complete and aligned stream information

In reply to Greg Kroah-Hartman

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

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

From: Namjae Jeon <[email protected]>

[ Upstream commit 206fc30f71b005156085fd8523ccc84a2c67791b ]

FILE_STREAM_INFORMATION responses are assembled without aligning entries and truncated to the client buffer length after the fact. A short query can therefore return STATUS_BUFFER_OVERFLOW with an incomplete entry and a nonzero NextEntryOffset, which clients may reject as an invalid network response. Standalone queries can also exhaust the server response buffer and silently omit streams while reporting success.

Allocate the same large response buffer used by other variable-length QUERY_INFO classes for stream queries. Pack only complete entries within the requested output length and available response space, aligning each entry to eight bytes and sizing names after UTF-16 conversion. Return STATUS_BUFFER_OVERFLOW when more entries remain, using an SMB2 error response if no entry fits.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
Fixes 6b8b79226bc3 ("ksmbd: fix partial file information responses")
[ sashal: Dropped the FILE_NORMALIZED_NAME_INFORMATION context from the smb2_allocate_rsp_buf() check, since this tree lacks it, and kept only the added FILE_STREAM_INFORMATION condition. ]
---
 fs/smb/server/smb2pdu.c | 183 +++++++++++++++++++++++++---------------
 1 file changed, 115 insertions(+), 68 deletions(-)
fs/smb/server/smb2pdu.c +115 -68
index 5492e7490a26b..115960cc93994 100644
@@ -554,7 +554,8 @@ int smb2_allocate_rsp_buf(struct ksmbd_work *work)
 		req = smb_get_msg(work->request_buf);
 		if ((req->InfoType == SMB2_O_INFO_FILE &&
 		     (req->FileInfoClass == FILE_FULL_EA_INFORMATION ||
-		     req->FileInfoClass == FILE_ALL_INFORMATION)) ||
+		     req->FileInfoClass == FILE_ALL_INFORMATION ||
+		     req->FileInfoClass == FILE_STREAM_INFORMATION)) ||
 		    req->InfoType == SMB2_O_INFO_SECURITY)
 			sz = large_sz;
 	}
@@ -5225,41 +5226,107 @@ static void get_file_alternate_info(struct ksmbd_work *work,
 		cpu_to_le32(struct_size(file_info, FileName, conv_len));
 }
 
+struct smb2_stream_info_buffer {
+	struct smb2_query_info_rsp *rsp;
+	struct smb2_file_stream_info *last;
+	const struct nls_table *local_nls;
+	unsigned int length;
+	unsigned int capacity;
+};
+
+static int smb2_add_stream_info(struct smb2_stream_info_buffer *buf,
+				const char *name, loff_t size, u64 allocation_size)
+{
+	struct smb2_file_stream_info *file_info;
+	__le16 *utf16_name;
+	size_t name_len = strlen(name);
+	unsigned int offset = ALIGN(buf->length, 8), name_bytes;
+	int conv_len, ret = 0;
+
+	if (offset > buf->capacity ||
+	    buf->capacity - offset < sizeof(*file_info))
+		return -ENOSPC;
+
+	utf16_name = kmalloc_array(name_len + 1, sizeof(*utf16_name),
+				   KSMBD_DEFAULT_GFP);
+	if (!utf16_name)
+		return -ENOMEM;
+
+	conv_len = smbConvertToUTF16(utf16_name, name, name_len,
+				     buf->local_nls, 0);
+	if (conv_len < 0) {
+		ret = conv_len;
+		goto out;
+	}
+
+	name_bytes = conv_len * sizeof(*utf16_name);
+	if (name_bytes > buf->capacity - offset - sizeof(*file_info)) {
+		ret = -ENOSPC;
+		goto out;
+	}
+
+	file_info = (struct smb2_file_stream_info *)&buf->rsp->Buffer[offset];
+	if (buf->last) {
+		memset(&buf->rsp->Buffer[buf->length], 0, offset - buf->length);
+		buf->last->NextEntryOffset =
+			cpu_to_le32((char *)file_info - (char *)buf->last);
+	}
+	file_info->NextEntryOffset = 0;
+	file_info->StreamNameLength = cpu_to_le32(name_bytes);
+	file_info->StreamSize = cpu_to_le64(size);
+	file_info->StreamAllocationSize = cpu_to_le64(allocation_size);
+	memcpy(file_info->StreamName, utf16_name, name_bytes);
+
+	buf->last = file_info;
+	buf->length = offset + sizeof(*file_info) + name_bytes;
+out:
+	kfree(utf16_name);
+	return ret;
+}
+
 static int get_file_stream_info(struct ksmbd_work *work,
+				struct smb2_query_info_req *req,
 				struct smb2_query_info_rsp *rsp,
-				struct ksmbd_file *fp,
-				void *rsp_org)
+				struct ksmbd_file *fp)
 {
-	struct ksmbd_conn *conn = work->conn;
-	struct smb2_file_stream_info *file_info;
+	struct smb2_stream_info_buffer buf = {
+		.rsp = rsp,
+		.local_nls = work->conn->local_nls,
+	};
 	char *stream_name, *xattr_list = NULL, *stream_buf;
 	struct kstat stat;
 	const struct path *path = &fp->filp->f_path;
 	ssize_t xattr_list_len;
 	ssize_t slen;
 	loff_t ssize;
-	int nbytes = 0, streamlen, stream_name_len, next, idx = 0;
+	unsigned int req_output_len = le32_to_cpu(req->OutputBufferLength);
+	int streamlen, idx = 0;
 	int buf_free_len;
 	int ret;
 
+	if (req_output_len < FILE_STREAM_INFORMATION_SIZE) {
+		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
+		return -EINVAL;
+	}
+
+	buf_free_len = smb2_calc_max_out_buf_len(work,
+						 offsetof(struct smb2_query_info_rsp, Buffer),
+						 req_output_len);
+	if (buf_free_len < 0)
+		return buf_free_len;
+	buf.capacity = buf_free_len;
+
 	ret = vfs_getattr(&fp->filp->f_path, &stat, STATX_BASIC_STATS,
 			  AT_STATX_SYNC_AS_STAT);
 	if (ret)
 		return ret;
 
-	file_info = (struct smb2_file_stream_info *)rsp->Buffer;
-
-	buf_free_len = smb2_resp_buf_len(work,
-			offsetof(struct smb2_query_info_rsp, Buffer));
-	if (buf_free_len < 0)
-		goto out;
-
 	xattr_list_len = ksmbd_vfs_listxattr(path->dentry, &xattr_list);
 	if (xattr_list_len < 0) {
-		goto out;
+		goto default_stream;
 	} else if (!xattr_list_len) {
 		ksmbd_debug(SMB, "empty xattr in the file\n");
-		goto out;
+		goto default_stream;
 	}
 
 	while (idx < xattr_list_len) {
@@ -5269,69 +5336,49 @@ static int get_file_stream_info(struct ksmbd_work *work,
 
 		ksmbd_debug(SMB, "%s, len %d\n", stream_name, streamlen);
 
-		if (strncmp(&stream_name[XATTR_USER_PREFIX_LEN],
-			    STREAM_PREFIX, STREAM_PREFIX_LEN))
+		if (strncmp(stream_name, XATTR_NAME_STREAM,
+			    XATTR_NAME_STREAM_LEN))
 			continue;
 
-		stream_name_len = streamlen - (XATTR_USER_PREFIX_LEN +
-				STREAM_PREFIX_LEN);
-		streamlen = stream_name_len;
-
-		/* plus : size */
-		streamlen += 1;
-		stream_buf = kmalloc(streamlen + 1, KSMBD_DEFAULT_GFP);
-		if (!stream_buf)
-			break;
-
-		streamlen = snprintf(stream_buf, streamlen + 1,
-				     ":%s", &stream_name[XATTR_NAME_STREAM_LEN]);
-
-		next = sizeof(struct smb2_file_stream_info) + streamlen * 2;
-		/* smbConvertToUTF16() also writes a terminating UTF-16 unit. */
-		if (next + sizeof(__le16) > buf_free_len) {
-			kfree(stream_buf);
-			break;
+		stream_buf = kasprintf(KSMBD_DEFAULT_GFP, ":%s",
+				       &stream_name[XATTR_NAME_STREAM_LEN]);
+		if (!stream_buf) {
+			ret = -ENOMEM;
+			goto out;
 		}
-
-		file_info = (struct smb2_file_stream_info *)&rsp->Buffer[nbytes];
-		streamlen  = smbConvertToUTF16((__le16 *)file_info->StreamName,
-					       stream_buf, streamlen,
-					       conn->local_nls, 0);
-		streamlen *= 2;
-		kfree(stream_buf);
-		file_info->StreamNameLength = cpu_to_le32(streamlen);
 		slen = ksmbd_vfs_xattr_len(file_mnt_idmap(fp->filp),
 					   path->dentry, stream_name);
 		ssize = slen < 0 ? 0 : (loff_t)slen;
-		file_info->StreamSize = cpu_to_le64(ssize);
-		file_info->StreamAllocationSize = cpu_to_le64(ssize);
+		ret = smb2_add_stream_info(&buf, stream_buf, ssize, ssize);
+		kfree(stream_buf);
+		if (ret == -ENOSPC)
+			goto overflow;
+		if (ret)
+			goto out;
+	}
 
-		nbytes += next;
-		buf_free_len -= next;
-		file_info->NextEntryOffset = cpu_to_le32(next);
+default_stream:
+	if (!S_ISDIR(stat.mode)) {
+		ret = smb2_add_stream_info(&buf, "::$DATA", stat.size,
+					   stat.blocks << 9);
+		if (ret == -ENOSPC)
+			goto overflow;
+		if (ret)
+			goto out;
 	}
 
+	ret = 0;
+	goto out;
+
+overflow:
+	rsp->hdr.Status = STATUS_BUFFER_OVERFLOW;
+	/* An empty overflow needs an SMB2 error response. */
+	ret = buf.length ? 0 : -EOVERFLOW;
 out:
-	if (!S_ISDIR(stat.mode) &&
-	    buf_free_len >= sizeof(struct smb2_file_stream_info) + (7 + 1) * 2) {
-		file_info = (struct smb2_file_stream_info *)
-			&rsp->Buffer[nbytes];
-		streamlen = smbConvertToUTF16((__le16 *)file_info->StreamName,
-					      "::$DATA", 7, conn->local_nls, 0);
-		streamlen *= 2;
-		file_info->StreamNameLength = cpu_to_le32(streamlen);
-		file_info->StreamSize = cpu_to_le64(stat.size);
-		file_info->StreamAllocationSize = cpu_to_le64(stat.blocks << 9);
-		nbytes += sizeof(struct smb2_file_stream_info) + streamlen;
-	}
-
-	/* last entry offset should be 0 */
-	file_info->NextEntryOffset = 0;
+	if (!ret)
+		rsp->OutputBufferLength = cpu_to_le32(buf.length);
 	kvfree(xattr_list);
-
-	rsp->OutputBufferLength = cpu_to_le32(nbytes);
-
-	return 0;
+	return ret;
 }
 
 static int get_file_internal_info(struct smb2_query_info_rsp *rsp,
@@ -5606,7 +5653,7 @@ static int smb2_get_info_file(struct ksmbd_work *work,
 		break;
 
 	case FILE_STREAM_INFORMATION:
-		rc = get_file_stream_info(work, rsp, fp, work->response_buf);
+		rc = get_file_stream_info(work, req, rsp, fp);
 		break;
 
 	case FILE_INTERNAL_INFORMATION:
Signature · 1 line
2.53.0
author maintainer
#546 lore raw

PATCH 542/816 block: dont enter reclaim under rq_qos_mutex

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 045cbfc369f5929ed473f7c200dc2e8146569ce5 ]

ioc_qos_write() and the wbt_lat_usec writers take rq_qos_mutex with the queue frozen, blkcg_deactivate_policy() does the same with blkcg_mutex, so nothing holding either may wait for IO. blkg_conf_prep() got GFP_NOIO for the blkg in commit 5d726c4dbeed, but the radix_tree_preload() right after it, the policy init functions and the GFP_KERNEL fallback in blkcg_activate_policy() can still enter reclaim there. lockdep reports the cycle on the first write to io.max.

Use GFP_NOIO for all of them.

Fixes 9730763f4756 ("block: correct locking order for protecting blk-wbt parameters")
Fixes 5d726c4dbeed ("blk-cgroup: fix possible deadlock while configuring policy")
Cc Tejun Heo <[email protected]>
[ sashal: Replaced kzalloc_obj(*ioc, GFP_NOIO) and the kzalloc_obj(*blkiolat, GFP_NOIO) call with plain kzalloc(sizeof(...), GFP_NOIO), since kzalloc_obj doesn't exist here. ]
---
 block/blk-cgroup.c    | 13 +++++++++----
 block/blk-iocost.c    |  5 +++--
 block/blk-iolatency.c |  3 ++-
 block/blk-throttle.c  |  3 ++-
 4 files changed, 16 insertions(+), 8 deletions(-)
block/blk-cgroup.c +9 -4
index d1f3d3491bd36..9e8a89b439611 100644
@@ -884,7 +884,11 @@ int blkg_conf_prep(struct blkcg *blkcg, const struct blkcg_policy *pol,
 			parent = blkcg_parent(parent);
 		}
 
-		/* Drop locks to do new blkg allocation with GFP_KERNEL. */
+		/*
+		 * Drop the spinlock to allocate the new blkg. rq_qos_mutex and
+		 * blkcg_mutex stay held, and both are taken with the queue
+		 * frozen elsewhere: GFP_NOIO.
+		 */
 		spin_unlock_irq(&q->queue_lock);
 
 		new_blkg = blkg_alloc(pos, disk, GFP_NOIO);
@@ -893,7 +897,7 @@ int blkg_conf_prep(struct blkcg *blkcg, const struct blkcg_policy *pol,
 			goto fail_exit;
 		}
 
-		if (radix_tree_preload(GFP_KERNEL)) {
+		if (radix_tree_preload(GFP_NOIO)) {
 			blkg_free(new_blkg);
 			ret = -ENOMEM;
 			goto fail_exit;
@@ -1598,7 +1602,8 @@ int blkcg_activate_policy(struct gendisk *disk, const struct blkcg_policy *pol)
 		if (!pd) {
 			/*
 			 * GFP_NOWAIT failed.  Free the existing one and
-			 * prealloc for @blkg w/ GFP_KERNEL.
+			 * prealloc for @blkg w/ GFP_NOIO: blkcg_mutex is held,
+			 * and a bio based queue has not been frozen above.
 			 */
 			if (pinned_blkg)
 				blkg_put(pinned_blkg);
@@ -1610,7 +1615,7 @@ int blkcg_activate_policy(struct gendisk *disk, const struct blkcg_policy *pol)
 			if (pd_prealloc)
 				pol->pd_free_fn(pd_prealloc);
 			pd_prealloc = pol->pd_alloc_fn(disk, blkg->blkcg,
-						       GFP_KERNEL);
+						       GFP_NOIO);
 			if (pd_prealloc)
 				goto retry;
 			else
block/blk-iocost.c +3 -2
index c7097b5c39c3a..29bfbfdb43750 100644
@@ -2982,11 +2982,12 @@ static int blk_iocost_init(struct gendisk *disk)
 	struct ioc *ioc;
 	int i, cpu, ret;
 
-	ioc = kzalloc(sizeof(*ioc), GFP_KERNEL);
+	/* The caller holds rq_qos_mutex, which is taken with the queue frozen */
+	ioc = kzalloc(sizeof(*ioc), GFP_NOIO);
 	if (!ioc)
 		return -ENOMEM;
 
-	ioc->pcpu_stat = alloc_percpu(struct ioc_pcpu_stat);
+	ioc->pcpu_stat = alloc_percpu_gfp(struct ioc_pcpu_stat, GFP_NOIO);
 	if (!ioc->pcpu_stat) {
 		kfree(ioc);
 		return -ENOMEM;
block/blk-iolatency.c +2 -1
index a82ee8c408c2f..3e3667159624f 100644
@@ -761,7 +761,8 @@ static int blk_iolatency_init(struct gendisk *disk)
 	struct blk_iolatency *blkiolat;
 	int ret;
 
-	blkiolat = kzalloc(sizeof(*blkiolat), GFP_KERNEL);
+	/* The caller holds rq_qos_mutex, which is taken with the queue frozen */
+	blkiolat = kzalloc(sizeof(*blkiolat), GFP_NOIO);
 	if (!blkiolat)
 		return -ENOMEM;
 
block/blk-throttle.c +2 -1
index 35b35b34cad5f..3e950426c6643 100644
@@ -1211,7 +1211,8 @@ static int blk_throtl_init(struct gendisk *disk)
 	struct throtl_data *td;
 	int ret;
 
-	td = kzalloc_node(sizeof(*td), GFP_KERNEL, q->node);
+	/* The caller holds rq_qos_mutex, which is taken with the queue frozen */
+	td = kzalloc_node(sizeof(*td), GFP_NOIO, q->node);
 	if (!td)
 		return -ENOMEM;
 
Signature · 1 line
2.53.0
author maintainer
#547 lore raw

PATCH 543/816 tls: Honor O_NONBLOCK in tls_sw_splice_read()

In reply to Greg Kroah-Hartman

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

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

From: Chuck Lever <[email protected]>

[ Upstream commit 78ded647d43e335891f981f68c5992a2e763cfcc ]

tls_sw_splice_read() takes its blocking behavior from SPLICE_F_NONBLOCK alone. When splicing from a socket to a pipe, do_splice() sets that flag from the pipe's O_NONBLOCK, not the socket's. On a nonblocking socket, a splice(2) call without SPLICE_F_NONBLOCK therefore sleeps in tls_rx_rec_wait() until a record arrives. tcp_splice_read() instead reads sock->file->f_flags and returns -EAGAIN.

Polling first does not avoid the sleep once tls_sw_splice_read() consumes zero-length records, as it does after a later patch in this series. tls_sw_sock_is_readable() reports the socket readable while any record sits on rx_list, including a zero-length record that delivers no bytes to the pipe. For TLS 1.3 the strparser announces a record before decryption, when its plaintext length is still unknown, so the readiness test cannot screen such a record out. A splice that consumes the record and waits for the next stalls every connection an event loop multiplexes.

An LLM audit of the TLS read paths found this defect.

Treat the socket's O_NONBLOCK as nonblocking too. A caller that sets O_NONBLOCK on the socket and splices without SPLICE_F_NONBLOCK now gets -EAGAIN where the splice blocked before. sendfile(2) from a TLS socket changes the same way, because do_sendfile() leaves the input file's O_NONBLOCK out of the splice flags. Both now behave as they do on a plain TCP socket.

Fixes c46234ebb4d1 ("tls: RX path for ktls")
[ sashal: Adapted the tls_rx_rec_wait() call to keep this tree's extra NULL psock argument while passing the new nonblock variable. ]
---
 net/tls/tls_sw.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
net/tls/tls_sw.c +6 -3
index bc2848d79c7d8..1b188f8fe45dc 100644
@@ -2298,10 +2298,14 @@ ssize_t tls_sw_splice_read(struct socket *sock,  loff_t *ppos,
 	struct tls_msg *tlm;
 	struct sk_buff *skb;
 	ssize_t copied = 0;
+	bool nonblock;
 	int chunk;
 	int err;
 
-	err = tls_rx_reader_lock(sk, ctx, flags & SPLICE_F_NONBLOCK);
+	nonblock = flags & SPLICE_F_NONBLOCK ||
+		   sock->file->f_flags & O_NONBLOCK;
+
+	err = tls_rx_reader_lock(sk, ctx, nonblock);
 	if (err < 0)
 		return err;
 
@@ -2315,8 +2319,7 @@ ssize_t tls_sw_splice_read(struct socket *sock,  loff_t *ppos,
 	} else {
 		struct tls_decrypt_arg darg;
 
-		err = tls_rx_rec_wait(sk, NULL, flags & SPLICE_F_NONBLOCK,
-				      true, false);
+		err = tls_rx_rec_wait(sk, NULL, nonblock, true, false);
 		if (err <= 0)
 			goto splice_read_end;
 
Signature · 1 line
2.53.0
author maintainer
#548 lore raw

PATCH 544/816 ppp: linearize and segment bridged packets when required

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit 0de4e69cd021c99d0aa13e1f30aafd13ad74a2a5 ]

PPP channel bridging hands packets received on one channel directly to the start_xmit() of another. Packets received by PPPoE can be non-linear, GSO since commit 55a5d8fca836 ("net: pppoe: implement GRO/GSO support"), or CHECKSUM_PARTIAL when injected with a virtio_net_hdr. The regular transmit path never sees such packets, and only PPPoE, which uses dev_queue_xmit(), handles them:

- PPP Async reads the whole packet through skb->data, transmitting unrelated memory for non-linear packets.
- PPP Async and Sync send GSO packets as single frames of up to 64KB, and CHECKSUM_PARTIAL packets with a bad L4 checksum.
- PPTP and L2TP cannot segment a TCP GSO packet once their GRE or UDP header is pushed, and do not finish pending checksums.

Add a xmit_offload flag to struct ppp_channel, set for PPPoE. For other channels, segment GSO packets in software, using the PPP protocol field as the L2 header, finish CHECKSUM_PARTIAL checksums (including SCTP CRC32c), and linearize packets for channels without direct_xmit, as ppp_push() does. Packets are dropped if any step fails, or if the channel is busy, as before.

skb->dev is NULL at this point for PPPoE (cleared by __sk_receive_skb()), and tunnel and IPv6 UFO GSO handlers dereference it: only TCP, UDP L4 and fraglist GSO packets without encapsulation are segmented, others are dropped.

Receive paths like L2TP pull headers without updating the checksum state, possibly leaving a CHECKSUM_PARTIAL state with csum_start before skb->data. Reset it to CHECKSUM_NONE, as skb_postpull_rcsum() does, so that skb_checksum_help() does not warn, and so that PPPoE does not offload a checksum at a wrong offset.

Tested in a VM by bridging PPPoE (on a TAP with IFF_NAPI_FRAGS, or on veth) to PPP Async on a PTY, PPPoL2TP and PPPoE: non-linear packets no longer leak garbage, GSO packets (including fraglist GRO) are sent as valid segments for IPv4 and IPv6, CHECKSUM_PARTIAL packets get a valid checksum, and PPPoE still receives GSO packets unchanged.

Fixes 4cf476ced45d ("ppp: add PPPIOCBRIDGECHAN and PPPIOCUNBRIDGECHAN ioctls")
Fixes 55a5d8fca836 ("net: pppoe: implement GRO/GSO support")
Cc Felix Fietkau <[email protected]>
Cc Pablo Neira Ayuso <[email protected]>
[ sashal: Dropped SKB_GSO_TCP_ACCECN from the GSO whitelist because it isn't defined here, and adjusted includes and the pppoe_connect() prototype context (struct sockaddr). ]
---
 drivers/net/ppp/ppp_generic.c | 95 ++++++++++++++++++++++++++++++++++-
 drivers/net/ppp/pppoe.c       |  1 +
 include/linux/ppp_channel.h   |  1 +
 3 files changed, 95 insertions(+), 2 deletions(-)
drivers/net/ppp/ppp_generic.c +93 -2
index 4d4591ea443a9..84212fd05968b 100644
@@ -46,6 +46,7 @@
 #include <linux/slab.h>
 #include <linux/file.h>
 #include <linux/unaligned.h>
+#include <net/gso.h>
 #include <net/slhc_vj.h>
 #include <linux/atomic.h>
 #include <linux/refcount.h>
@@ -2274,6 +2275,73 @@ static bool ppp_decompress_proto(struct sk_buff *skb)
 	return pskb_may_pull(skb, 2);
 }
 
+#define PPP_BRIDGE_GSO_TYPES (SKB_GSO_TCPV4 | SKB_GSO_TCPV6 |		\
+			      SKB_GSO_TCP_ECN |					\
+			      SKB_GSO_TCP_FIXEDID | SKB_GSO_UDP_L4 |	\
+			      SKB_GSO_FRAGLIST | SKB_GSO_DODGY)
+
+/* Segment a GSO packet (built by PPPoE GRO, or injected with a
+ * virtio_net_hdr) before sending it to a bridged channel that does
+ * not accept GSO packets.
+ * skb->data points to the PPP protocol field, which is replicated
+ * in front of each segment.
+ * Returns a list of segments, or NULL if the packet was dropped.
+ */
+static struct sk_buff *ppp_bridge_gso_segment(struct sk_buff *skb,
+					      netdev_features_t features)
+{
+	struct sk_buff *segs;
+
+	/* skb->dev is NULL here (cleared by __sk_receive_skb() for PPPoE),
+	 * and some GSO handlers (tunnels, IPv6 UFO) dereference it.
+	 */
+	if (skb->encapsulation ||
+	    (skb_shinfo(skb)->gso_type & ~PPP_BRIDGE_GSO_TYPES))
+		goto drop;
+
+	if (!pskb_may_pull(skb, PPP_PROTO_LEN))
+		goto drop;
+
+	switch (get_unaligned((__be16 *)skb->data)) {
+	case htons(PPP_IP):
+		skb->protocol = htons(ETH_P_IP);
+		break;
+	case htons(PPP_IPV6):
+		skb->protocol = htons(ETH_P_IPV6);
+		break;
+	default:
+		goto drop;
+	}
+	skb_set_network_header(skb, PPP_PROTO_LEN);
+
+	/* No checksum offload: skb_segment() computes the checksums. */
+	segs = skb_gso_segment(skb, features);
+	if (IS_ERR_OR_NULL(segs))
+		goto drop;
+
+	consume_skb(skb);
+	return segs;
+
+drop:
+	kfree_skb(skb);
+	return NULL;
+}
+
+static void ppp_bridge_xmit(struct ppp_channel *chan, struct sk_buff *skb)
+{
+	if (!chan->direct_xmit && skb_linearize(skb))
+		goto drop;
+
+	if (!chan->xmit_offload && skb->ip_summed == CHECKSUM_PARTIAL &&
+	    skb_csum_hwoffload_help(skb, 0))
+		goto drop;
+
+	if (chan->ops->start_xmit(chan, skb))
+		return;
+drop:
+	kfree_skb(skb);
+}
+
 /* Attempt to handle a frame via. a bridged channel, if one exists.
  * If the channel is bridged, the frame is consumed by the bridge.
  * If not, the caller must handle the frame by normal recv mechanisms.
@@ -2281,6 +2349,8 @@ static bool ppp_decompress_proto(struct sk_buff *skb)
  */
 static bool ppp_channel_bridge_input(struct channel *pch, struct sk_buff *skb)
 {
+	struct sk_buff *segs, *next;
+	struct ppp_channel *chan;
 	struct channel *pchb;
 
 	rcu_read_lock();
@@ -2296,8 +2366,29 @@ static bool ppp_channel_bridge_input(struct channel *pch, struct sk_buff *skb)
 	}
 
 	skb_scrub_packet(skb, !net_eq(pch->chan_net, pchb->chan_net));
-	if (!pchb->chan->ops->start_xmit(pchb->chan, skb))
-		kfree_skb(skb);
+
+	/* Receive paths such as L2TP pull headers without updating
+	 * the checksum state: drop a stale CHECKSUM_PARTIAL state
+	 * pointing before skb->data, as skb_postpull_rcsum() does.
+	 */
+	if (skb->ip_summed == CHECKSUM_PARTIAL &&
+	    skb_checksum_start_offset(skb) < 0)
+		skb->ip_summed = CHECKSUM_NONE;
+
+	chan = pchb->chan;
+	if (!chan->xmit_offload && skb_is_gso(skb)) {
+		/* Channels needing linear packets get linear segments,
+		 * others keep references to the original pages.
+		 */
+		segs = ppp_bridge_gso_segment(skb, chan->direct_xmit ?
+						   NETIF_F_SG : 0);
+		skb_list_walk_safe(segs, skb, next) {
+			skb_mark_not_on_list(skb);
+			ppp_bridge_xmit(chan, skb);
+		}
+	} else {
+		ppp_bridge_xmit(chan, skb);
+	}
 
 outl:
 	spin_unlock_bh(&pchb->downl);
drivers/net/ppp/pppoe.c +1 -0
index 97eb18dbc312e..0a7d5f756f41a 100644
@@ -698,6 +698,7 @@ static int pppoe_connect(struct socket *sock, struct sockaddr *uservaddr,
 		po->chan.private = sk;
 		po->chan.ops = &pppoe_chan_ops;
 		po->chan.direct_xmit = true;
+		po->chan.xmit_offload = true;
 
 		error = ppp_register_net_channel(dev_net(dev), &po->chan);
 		if (error) {
include/linux/ppp_channel.h +1 -0
index f73fbea0dbc23..d0646c2518b2a 100644
@@ -43,6 +43,7 @@ struct ppp_channel {
 	void		*ppp;		/* opaque to channel */
 	int		speed;		/* transfer rate (bytes/second) */
 	bool		direct_xmit;	/* no qdisc, xmit directly */
+	bool		xmit_offload;	/* accepts GSO and CHECKSUM_PARTIAL skbs */
 };
 
 #ifdef __KERNEL__
Signature · 1 line
2.53.0
author maintainer
#549 lore raw

PATCH 545/816 blk-mq: dont trust the cookie in blk_mq_poll()

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 24974185999fd80b676fbe2a6c7a97bbd38aaf3a ]

blk_mq_poll() indexes queue_hw_ctx[] with bio->bi_cookie unchecked. Zone write plugging keeps the segment count of a plugged write in __bi_nr_segments, which shares a union with the cookie, and clears REQ_POLLED, but bio_poll() only looks at the cookie. A plugged polled write with more segments than there are hardware queues reads past the array. The bio is also SLAB_TYPESAFE_BY_RCU, so a cookie from a bio reused for another device can meet the wrong array as well.

Ignore a cookie that is out of range or doesn't name a poll queue.

Fixes 3e08773c3841 ("block: switch polling to be bio based")
Fixes dd291d77cc90 ("block: Introduce zone write plugging")
---
 block/blk-mq.c | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)
block/blk-mq.c +14 -1
index 65a08aec007d2..63480b913e352 100644
@@ -5150,9 +5150,22 @@ static int blk_hctx_poll(struct request_queue *q, struct blk_mq_hw_ctx *hctx,
 int blk_mq_poll(struct request_queue *q, blk_qc_t cookie,
 		struct io_comp_batch *iob, unsigned int flags)
 {
+	struct blk_mq_hw_ctx *hctx;
+
 	if (!blk_mq_can_poll(q))
 		return 0;
-	return blk_hctx_poll(q, xa_load(&q->hctx_table, cookie), iob, flags);
+
+	/*
+	 * The cookie is no more than a hint. iocb_bio_iopoll() may have read it
+	 * from a bio that was reused for another queue right afterwards, and
+	 * zone write plugging keeps the number of segments in the same field.
+	 */
+	if (cookie >= q->nr_hw_queues)
+		return 0;
+	hctx = xa_load(&q->hctx_table, cookie);
+	if (!hctx || hctx->type != HCTX_TYPE_POLL)
+		return 0;
+	return blk_hctx_poll(q, hctx, iob, flags);
 }
 
 int blk_rq_poll(struct request *rq, struct io_comp_batch *iob,
Signature · 1 line
2.53.0
author maintainer
#550 lore raw

PATCH 546/816 netdev-genl: ignore NETDEV_UNREGISTER rebroadcasts

In reply to Greg Kroah-Hartman

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

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

From: Naman Gulati <[email protected]>

[ Upstream commit fd0909e963ed8f36967bd072ed484be7babe46de ]

netdev_wait_allrefs_any() re-sends NETDEV_UNREGISTER every second while it waits for the last references on a device to be dropped. By then netdev_run_todo() has already marked the device NETREG_UNREGISTERED and RTNL has been dropped at least once since the initial notification sent by unregister_netdevice_many_notify().

netdev_genl_netdevice_event() does not tell these rebroadcasts apart from the initial notification and sends a NETDEV_CMD_DEV_DEL_NTF multicast for each of them. At best this spams NETDEV_NLGRP_MGMT listeners with duplicate notifications; at worst the pernet state of the netns the device belongs to is already gone and the handler dereferences a NULL pointer.

default_device_exit_batch() only unregisters the devices still listed in the exiting netns; it does not wait for in-flight unregistrations of devices that were already unlisted (the barrier doing that was removed by commit 8a4fc54b07d7 ("net: get rid of rtnl_lock_unregistering()")). So when a device is unregistered by something other than the cleanup_net() of its own netns while references on it are still held, e.g. a veth whose peer in another netns gets deleted, and that netns exits while the device is stuck in netdev_wait_allrefs_any(), the remaining pernet exit handlers run and genl_pernet_exit() sets net->genl_sock to NULL. The next rebroadcast then crashes in genl_has_listeners():

  BUG: KASAN: null-ptr-deref in netlink_has_listeners+0x3d/0x3f0 net/netlink/af_netlink.c:1388
  Read of size 8 at addr 0000000000000578 by task syz.0.0/5325
  Call Trace:
   <TASK>
   netlink_has_listeners+0x3d/0x3f0 net/netlink/af_netlink.c:1388
   genl_has_listeners include/net/genetlink.h:644 [inline]
   netdev_genl_dev_notify+0x161/0x450 net/core/netdev-genl.c:93
   netdev_genl_netdevice_event+0x98/0x3c0 net/core/netdev-genl.c:1491
   notifier_call_chain+0x1a5/0x3d0 kernel/notifier.c:85
   netdev_wait_allrefs_any net/core/dev.c:11690 [inline]
   netdev_run_todo+0x731/0x1060 net/core/dev.c:11808
   rtnl_unlock net/core/rtnetlink.c:157 [inline]
   rtnl_dellink+0x68f/0x810 net/core/rtnetlink.c:3707

syzbot hit this by moving one end of a veth pair into a short-lived netns while netdevsim's deferred FIB event processing still held a reference on it, and then deleting the other end (repro [1]). While the source of this bug is netdevsim deferring FIB processing for and holding onto the device reference for O(seconds) which is being fixed separately [2], any driver may introduce such a delay and trigger the null-ptr-deref.

Skip the rebroadcasts, which are the only NETDEV_UNREGISTER events delivered with reg_state == NETREG_UNREGISTERED. The notifications sent by unregister_netdevice_many_notify() and, for a device leaving a netns, by __dev_change_net_namespace() are issued under RTNL in the same critical section that unlists the device, before its netns can be torn down, and keep being handled. This mirrors what ip6_route_dev_notify() already does to cope with the rebroadcasts.

This change should not break the UAPI spec as it defines dev-del-ntf as a "Notification about device disappearing." which is a single event. The rebroadcast in netdev_wait_allrefs_any() exists to re-kick in-kernel subsystems holding references; netdev-genl happens to be on the notifier chain and forwards it.

[1] https://gist.github.com/NamanGulati/2d1b49b8757f9a88b0bd6e55018c02ae
[2] https://lore.kernel.org/r/[email protected]

Fixes d3d854fd6a1d ("netdev-genl: create a simple family for netdev stuff")
Reported-by [email protected]
[ sashal: Added the upstream guard and comment to the NETDEV_UNREGISTER case, but without the netdev_lock()/netdev_unlock() context lines, which this tree lacks. ]
---
 net/core/netdev-genl.c | 6 ++++++
 1 file changed, 6 insertions(+)
net/core/netdev-genl.c +6 -0
index 12c6f7d5add09..7578686165515 100644
@@ -897,6 +897,12 @@ static int netdev_genl_netdevice_event(struct notifier_block *nb,
 		netdev_genl_dev_notify(netdev, NETDEV_CMD_DEV_ADD_NTF);
 		break;
 	case NETDEV_UNREGISTER:
+		/* netdev_wait_allrefs_any() rebroadcasts NETDEV_UNREGISTER
+		 * while waiting for the last references to be dropped; the
+		 * netns may already be torn down by then. Notify only once.
+		 */
+		if (READ_ONCE(netdev->reg_state) == NETREG_UNREGISTERED)
+			break;
 		netdev_genl_dev_notify(netdev, NETDEV_CMD_DEV_DEL_NTF);
 		break;
 	case NETDEV_XDP_FEAT_CHANGE:
Signature · 1 line
2.53.0
author maintainer
#551 lore raw

PATCH 547/816 eth: bnxt: dont leak buffers when XDP agg buffer allocation fails

In reply to Greg Kroah-Hartman

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

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

From: Jakub Kicinski <[email protected]>

[ Upstream commit 1b2f02fb4ba92d01603c8261c94be8d348de65b0 ]

If a replacement agg buffer can't be allocated for a packet received with XDP attached, bnxt_rx_pkt() drops the packet without returning its head buffer to the ring. The head buffer leaks, and since rx_prod still advances, the device gets a BD with a stale DMA address which points at a buffer the driver no longer owns. When that BD completes the driver finds no buffer in the slot.

The agg buffers consumed before the failing one have already been replaced on the agg ring, they are referenced only by the frags of the xdp_buff, which nobody frees. bnxt_xdp_buff_frags_free() would skip them since the frags flag is set only on success, so set it upfront.

Pointed out in LLM review of the first patch of the series. Tested on a BCM57504 at MTU 9000 with a frags-capable XDP_PASS program, receiving 8000B ICMPv6 echo requests (a head and two agg buffers each) while page_pool_alloc_netmems() called from bnxt_rx_agg_netmems_xdp() failed half of the time (bpftrace override()). 44.7k packets were dropped, the page pools' inflight count stayed flat and there were no KASAN or DEBUG_PAGEALLOC splats.

Fixes 4c6c123c9af9 ("bnxt: adding bnxt_rx_agg_pages_xdp for aggregated xdp")
[ sashal: Replaced netmem-based helper names and &bnxt_xdp.xdp with the page-based __bnxt_rx_agg_pages()/bnxt_rx_agg_pages_xdp() calls and the local &xdp variable. ]
---
 drivers/net/ethernet/broadcom/bnxt/bnxt.c | 17 +++++++++++------
 1 file changed, 11 insertions(+), 6 deletions(-)
drivers/net/ethernet/broadcom/bnxt/bnxt.c +11 -6
index 5d6f24044fb63..51272fb72dca6 100644
@@ -1297,16 +1297,19 @@ static u32 bnxt_rx_agg_pages_xdp(struct bnxt *bp,
 	struct skb_shared_info *shinfo = xdp_get_shared_info_from_buff(xdp);
 	u32 total_frag_len = 0;
 
-	if (!xdp_buff_has_frags(xdp))
+	if (!xdp_buff_has_frags(xdp)) {
+		xdp_buff_set_frags_flag(xdp);
 		shinfo->nr_frags = 0;
+	}
 
 	total_frag_len = __bnxt_rx_agg_pages(bp, cpr, shinfo,
 					     idx, agg_bufs, tpa, xdp);
-	if (total_frag_len) {
-		xdp_buff_set_frags_flag(xdp);
-		shinfo->nr_frags = agg_bufs;
-		shinfo->xdp_frags_size = total_frag_len;
+	if (!total_frag_len) {
+		bnxt_xdp_buff_frags_free(cpr->bnapi->rx_ring, xdp);
+		return 0;
 	}
+	shinfo->nr_frags = agg_bufs;
+	shinfo->xdp_frags_size = total_frag_len;
 	return total_frag_len;
 }
 
@@ -2179,8 +2182,10 @@ static int bnxt_rx_pkt(struct bnxt *bp, struct bnxt_cp_ring_info *cpr,
 			u32 frag_len = bnxt_rx_agg_pages_xdp(bp, cpr, &xdp,
 							     cp_cons, agg_bufs,
 							     false);
-			if (!frag_len)
+			if (!frag_len) {
+				bnxt_reuse_rx_data(rxr, cons, data);
 				goto oom_next_rx;
+			}
 
 		}
 		xdp_active = true;
Signature · 1 line
2.53.0
author maintainer
#552 lore raw

PATCH 548/816 tun: clear stale skb->protocol of NAPI frags skbs

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit 3287cd714a853d9443c4a743eca010aedcfbbcdd ]

With IFF_NAPI_FRAGS, tun_napi_alloc_frags() gets its skb from napi_get_frags(). If GRO merged the previous frame with GRO_MERGED_FREE, that skb was recycled by napi_reuse_skb(), which does not reset skb->protocol set by napi_frags_skb() for the previous frame.

tun_get_user() calls tun_vnet_hdr_tnl_to_skb() before eth_type_trans(), so the virtio header checks see the protocol of the previous frame:
GSO packets without VIRTIO_NET_HDR_F_NEEDS_CSUM are dissected with the wrong protocol. A following change checks the outer protocol of UDP tunnel GSO packets, which would then reject a valid frame when the two ethertypes differ.

This needs GRO to hold packets across writes, and IFF_NAPI_FRAGS needs CAP_NET_ADMIN.

Clear skb->protocol in tun_napi_alloc_frags(), like skbs allocated by tun_alloc_skb() or build_skb(). eth_type_trans() sets it later.

---
 drivers/net/tun.c | 6 ++++++
 1 file changed, 6 insertions(+)
drivers/net/tun.c +6 -0
index 893746d4c8d0f..e8b4d988cd330 100644
@@ -1484,6 +1484,12 @@ static struct sk_buff *tun_napi_alloc_frags(struct tun_file *tfile,
 	if (!skb)
 		return ERR_PTR(-ENOMEM);
 
+	/* An skb recycled by napi_reuse_skb() keeps the protocol of a
+	 * previous frame. eth_type_trans() sets it after the virtio
+	 * header checks, which must not see a stale one.
+	 */
+	skb->protocol = 0;
+
 	linear = iov_iter_single_seg_count(it);
 	err = __skb_grow(skb, linear);
 	if (err)
Signature · 1 line
2.53.0
author maintainer
#553 lore raw

PATCH 549/816 tracing/eprobe: Install the trigger for every instance that enables the eprobe

In reply to Greg Kroah-Hartman

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

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

From: David Carlier <[email protected]>

commit be94710b1f6ba1bea33e73129c110af80e999b2d upstream.

The eprobe trigger lives in the instance of the enabling file, but it is only added when the eprobe is first enabled and only removed when the last file goes away. A second instance then records nothing, and the first instance's trigger is left behind once the eprobe is disabled there, so the eprobe can be deleted while that trigger still uses it.

Add and remove the trigger for each file. The file is never NULL here, so warn if it is and drop the dead perf paths.

Fixes 7491e2c44278 ("tracing: Add a probe that attaches to trace events")
---
 kernel/trace/trace_eprobe.c |   58 ++++++++++++++------------------------------
 1 file changed, 19 insertions(+), 39 deletions(-)
kernel/trace/trace_eprobe.c +19 -39
@@ -636,37 +636,32 @@ static int enable_trace_eprobe(struct tr
 {
 	struct trace_probe *tp;
 	struct trace_eprobe *ep;
-	bool enabled;
 	int ret = 0;
 	int cnt = 0;
 
+	if (WARN_ON_ONCE(!file))
+		return -EINVAL;
+
 	tp = trace_probe_primary_from_call(call);
 	if (WARN_ON_ONCE(!tp))
 		return -ENODEV;
-	enabled = trace_probe_is_enabled(tp);
 
 	/* This also changes "enabled" state */
-	if (file) {
-		ret = trace_probe_add_file(tp, file);
-		if (ret)
-			return ret;
-	} else
-		trace_probe_set_flag(tp, TP_FLAG_PROFILE);
-
-	if (enabled)
-		return 0;
+	ret = trace_probe_add_file(tp, file);
+	if (ret)
+		return ret;
 
+	/* The trigger lives in the instance of the file, add it for each file */
 	for_each_trace_eprobe_tp(ep, tp) {
 		ret = enable_eprobe(ep, file);
 		if (ret)
 			break;
-		enabled = true;
 		cnt++;
 	}
 
 	if (ret) {
 		/* Failed to enable one of them. Roll back all */
-		if (enabled) {
+		if (cnt) {
 			/*
 			 * It's a bug if one failed for something other than memory
 			 * not being available but another eprobe succeeded.
@@ -679,10 +674,7 @@ static int enable_trace_eprobe(struct tr
 					break;
 			}
 		}
-		if (file)
-			trace_probe_remove_file(tp, file);
-		else
-			trace_probe_clear_flag(tp, TP_FLAG_PROFILE);
+		trace_probe_remove_file(tp, file);
 	}
 
 	return ret;
@@ -694,33 +686,21 @@ static int disable_trace_eprobe(struct t
 	struct trace_probe *tp;
 	struct trace_eprobe *ep;
 
+	if (WARN_ON_ONCE(!file))
+		return -EINVAL;
+
 	tp = trace_probe_primary_from_call(call);
 	if (WARN_ON_ONCE(!tp))
 		return -ENODEV;
 
-	if (file) {
-		if (!trace_probe_get_file_link(tp, file))
-			return -ENOENT;
-		if (!trace_probe_has_single_file(tp))
-			goto out;
-		trace_probe_clear_flag(tp, TP_FLAG_TRACE);
-	} else
-		trace_probe_clear_flag(tp, TP_FLAG_PROFILE);
-
-	if (!trace_probe_is_enabled(tp)) {
-		for_each_trace_eprobe_tp(ep, tp)
-			disable_eprobe(ep, file->tr);
-	}
+	if (!trace_probe_get_file_link(tp, file))
+		return -ENOENT;
 
- out:
-	if (file)
-		/*
-		 * Synchronization is done in below function. For perf event,
-		 * file == NULL and perf_trace_event_unreg() calls
-		 * tracepoint_synchronize_unregister() to ensure synchronize
-		 * event. We don't need to care about it.
-		 */
-		trace_probe_remove_file(tp, file);
+	for_each_trace_eprobe_tp(ep, tp)
+		disable_eprobe(ep, file->tr);
+
+	/* Synchronization is done in below function. */
+	trace_probe_remove_file(tp, file);
 
 	return 0;
 }
author maintainer
#554 lore raw

PATCH 550/816 KEYS: Reject descriptions larger than KEY_MAX_DESC_SIZE

In reply to Greg Kroah-Hartman

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

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

From: Jarkko Sakkinen <[email protected]>

commit 094c53d2994975e36d4cab7cf5d9f34c1b0f1916 upstream.

KEY_MAX_DESC_SIZE includes the trailing NULL character. Descriptions generated from payloads and in-kernel paths bypass the userspace limit.

Reject descriptions at or above KEY_MAX_DESC_SIZE with -EINVAL at the following sites:

- key_alloc(): before quota calculation
- __key_create_or_update(): before key_set_index_key()
- keyring_search(): before match_preparse
- request_key_and_link(): before match_preparse
- request_key_rcu(): before check_cached_key()

---
 include/linux/key.h         |    3 +++
 security/keys/key.c         |   10 +++++++++-
 security/keys/keyctl.c      |    2 --
 security/keys/keyring.c     |    7 ++++++-
 security/keys/request_key.c |   14 ++++++++++++--
 5 files changed, 30 insertions(+), 6 deletions(-)
include/linux/key.h +3 -0
@@ -37,6 +37,9 @@ struct net;
 
 #undef KEY_DEBUGGING
 
+/* Maximum length of a key description, including the trailing NUL */
+#define KEY_MAX_DESC_SIZE 4096
+
 #define KEY_POS_VIEW	0x01000000	/* possessor can view a key's attributes */
 #define KEY_POS_READ	0x02000000	/* possessor can read key payload / view keyring */
 #define KEY_POS_WRITE	0x04000000	/* possessor can update key payload / add link to keyring */
security/keys/key.c +9 -1
@@ -245,6 +245,8 @@ struct key *key_alloc(struct key_type *t
 	}
 
 	desclen = strlen(desc);
+	if (desclen >= KEY_MAX_DESC_SIZE)
+		goto error;
 	quotalen = desclen + 1 + type->def_datalen;
 
 	/* get hold of the key tracking for this user */
@@ -828,6 +830,7 @@ static key_ref_t __key_create_or_update(
 	key_ref_t key_ref;
 	int ret;
 	struct key_restriction *restrict_link = NULL;
+	size_t desclen;
 
 	/* look up the key type to see if it's one of the registered kernel
 	 * types */
@@ -868,7 +871,12 @@ static key_ref_t __key_create_or_update(
 		if (!index_key.description)
 			goto error_free_prep;
 	}
-	index_key.desc_len = strlen(index_key.description);
+	desclen = strlen(index_key.description);
+	if (desclen >= KEY_MAX_DESC_SIZE) {
+		key_ref = ERR_PTR(-EINVAL);
+		goto error_free_prep;
+	}
+	index_key.desc_len = desclen;
 	key_set_index_key(&index_key);
 
 	ret = __key_link_lock(keyring, &index_key);
security/keys/keyctl.c +0 -2
@@ -24,8 +24,6 @@
 #include <keys/request_key_auth-type.h>
 #include "internal.h"
 
-#define KEY_MAX_DESC_SIZE 4096
-
 static const unsigned char keyrings_capabilities[2] = {
 	[0] = (KEYCTL_CAPS0_CAPABILITIES |
 	       (IS_ENABLED(CONFIG_PERSISTENT_KEYRINGS)	? KEYCTL_CAPS0_PERSISTENT_KEYRINGS : 0) |
security/keys/keyring.c +6 -1
@@ -957,7 +957,6 @@ key_ref_t keyring_search(key_ref_t keyri
 	struct keyring_search_context ctx = {
 		.index_key.type		= type,
 		.index_key.description	= description,
-		.index_key.desc_len	= strlen(description),
 		.cred			= current_cred(),
 		.match_data.cmp		= key_default_cmp,
 		.match_data.raw_data	= description,
@@ -965,8 +964,14 @@ key_ref_t keyring_search(key_ref_t keyri
 		.flags			= KEYRING_SEARCH_DO_STATE_CHECK,
 	};
 	key_ref_t key;
+	size_t desclen;
 	int ret;
 
+	desclen = strlen(description);
+	if (desclen >= KEY_MAX_DESC_SIZE)
+		return ERR_PTR(-EINVAL);
+	ctx.index_key.desc_len = desclen;
+
 	if (recurse)
 		ctx.flags |= KEYRING_SEARCH_RECURSE;
 	if (type->match_preparse) {
security/keys/request_key.c +12 -2
@@ -584,7 +584,6 @@ struct key *request_key_and_link(struct
 		.index_key.type		= type,
 		.index_key.domain_tag	= domain_tag,
 		.index_key.description	= description,
-		.index_key.desc_len	= strlen(description),
 		.cred			= current_cred(),
 		.match_data.cmp		= key_default_cmp,
 		.match_data.raw_data	= description,
@@ -595,8 +594,14 @@ struct key *request_key_and_link(struct
 	};
 	struct key *key;
 	key_ref_t key_ref;
+	size_t desclen;
 	int ret;
 
+	desclen = strlen(description);
+	if (desclen >= KEY_MAX_DESC_SIZE)
+		return ERR_PTR(-EINVAL);
+	ctx.index_key.desc_len = desclen;
+
 	kenter("%s,%s,%p,%zu,%p,%p,%lx",
 	       ctx.index_key.type->name, ctx.index_key.description,
 	       callout_info, callout_len, aux, dest_keyring, flags);
@@ -787,7 +792,6 @@ struct key *request_key_rcu(struct key_t
 		.index_key.type		= type,
 		.index_key.domain_tag	= domain_tag,
 		.index_key.description	= description,
-		.index_key.desc_len	= strlen(description),
 		.cred			= current_cred(),
 		.match_data.cmp		= key_default_cmp,
 		.match_data.raw_data	= description,
@@ -797,6 +801,12 @@ struct key *request_key_rcu(struct key_t
 	};
 	struct key *key;
 	key_ref_t key_ref;
+	size_t desclen;
+
+	desclen = strlen(description);
+	if (desclen >= KEY_MAX_DESC_SIZE)
+		return ERR_PTR(-EINVAL);
+	ctx.index_key.desc_len = desclen;
 
 	kenter("%s,%s", type->name, description);
 
author maintainer
#555 lore raw

PATCH 551/816 KEYS: Verify the key identity in __key_unlink_begin

In reply to Greg Kroah-Hartman

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

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

From: Jarkko Sakkinen <[email protected]>

commit 7a7f70ff7b26519c98b339a3e0cd9ee3c8d17f77 upstream.

When two keys have identical type and description, linking the second key replaces the first in a keyring. However, attempting to unlink the first key (no longer in the keyring) unlinks the second key.

This happens because __key_unlink_begin() calls assoc_array_delete() with &key->index_key, matching only on type and description rather than the key's identity.

Example:

  keyctl new_session >/dev/null
  keyctl newring ring_a @s
  keyctl newring ring_b @s
  A=$(keyctl add user A ss %:ring_a)
  B=$(keyctl add user A qq %:ring_b)
  keyctl newring R @s
  keyctl link $A %:R
  keyctl link $B %:R
  keyctl unlink $A %:R
  keyctl show

Verify the key identity before unlinking, and return -ENOENT on mismatch, instead of unlinking the key with the wrong identity.

---
 security/keys/keyring.c |    6 ++++++
 1 file changed, 6 insertions(+)
security/keys/keyring.c +6 -0
@@ -1506,9 +1506,15 @@ static int __key_unlink_begin(struct key
 			      struct assoc_array_edit **_edit)
 {
 	struct assoc_array_edit *edit;
+	const void *object;
 
 	BUG_ON(*_edit != NULL);
 
+	object = assoc_array_find(&keyring->keys, &keyring_assoc_array_ops,
+				  &key->index_key);
+	if (!object || keyring_ptr_to_key(object) != key)
+		return -ENOENT;
+
 	edit = assoc_array_delete(&keyring->keys, &keyring_assoc_array_ops,
 				  &key->index_key);
 	if (IS_ERR(edit))
author maintainer
#556 lore raw

PATCH 552/816 bootconfig: Allow keys with the maximum supported depth

In reply to Greg Kroah-Hartman

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

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

From: Zhiqi Zhang <[email protected]>

commit cab697164b47eecfa2f146024f5d661f99a1a1e7 upstream.

xbc_verify_tree() accepts keys with XBC_DEPTH_MAX (16) components, but xbc_node_compose_key_after() returns -ERANGE immediately after storing the sixteenth component. It rejects the key before discovering that there are no more ancestors to collect.

For example, a.b.c.d.e.f.g.h.i.j.k.l.m.n.o.p = value can be attached to an initrd successfully. However, bootconfig -l stops listing and prints "Failed to compose key -34". In the kernel, the same error propagates through copy_xbc_key_value_list() during its length probe, so proc_boot_config_init() returns before creating /proc/bootconfig.

Check the array capacity before storing the next component. This lets exactly XBC_DEPTH_MAX components be composed while retaining the check before any out-of-bounds store.

I found this issue while reviewing bootconfig's depth handling and used OpenAI Codex to verify the failure and develop the fix. I reviewed the change and wrote and ran the regression tests.

Fixes 76db5a27a827 ("bootconfig: Add Extra Boot Config support")
---
 lib/bootconfig.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
lib/bootconfig.c +1 -1
@@ -302,9 +302,9 @@ int __init xbc_node_compose_key_after(st
 		node = xbc_node_get_parent(node);
 
 	while (node && node != root) {
-		keys[depth++] = xbc_node_index(node);
 		if (depth == XBC_DEPTH_MAX)
 			return -ERANGE;
+		keys[depth++] = xbc_node_index(node);
 		node = xbc_node_get_parent(node);
 	}
 	if (!node && root)
author maintainer
#557 lore raw

PATCH 553/816 ALSA: caiaq: Kill EP1 URB before unregistering the input device

In reply to Greg Kroah-Hartman

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

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

From: Sergei Nizovtsev <[email protected]>

commit 5d325345185015024a86abca4cc5fa6a3f75294e upstream.

snd_disconnect() unregisters the input device via snd_usb_caiaq_input_disconnect() and only afterwards kills the EP1 command URB (cdev->ep1_in_urb). The EP1 completion handler usb_ep1_command_reply_dispatch() feeds snd_usb_caiaq_input_dispatch() for EP1_CMD_READ_{ERP,ANALOG,IO} replies, which report into cdev->input_dev. Since commit b04dcbb7f7b1 ("ALSA: caiaq: Use snd_card_free_when_closed() at disconnection") the input device is unregistered from snd_usb_caiaq_input_disconnect() but cdev->input_dev is cleared only later, in snd_usb_caiaq_input_free() from the card destructor. As the dispatch guard only tests cdev->input_dev for NULL, an EP1 reply that completes after input_unregister_device() but before cdev->ep1_in_urb is killed reports into an input device that has already been unregistered and, with no evdev client holding it open, freed.

Normally the window is closed by the USB core: usb_unbind_interface() calls usb_disable_interface() before ->disconnect(), which flushes the EP1 URB as long as endpoint 0x81 belongs to the interface being unbound. But caiaq addresses EP1 through the device-wide pipe usb_rcvbulkpipe(usb_dev, 0x1) without checking which interface owns the endpoint. If a device declares it in another interface, the URB stays live across snd_disconnect() of the interface that owns the card.

This needs a crafted device descriptor; a device that has EP1 in the interface caiaq is bound to is not affected.

Kill cdev->ep1_in_urb (and the paired midi_out_urb) before the input and audio disconnect helpers, so no EP1 completion can run once the input device has been unregistered.

Reproduced under KASAN with raw-gadget + dummy_hcd emulating an Audio Kontrol 1 (17cc:0815) with the EP1 bulk pair in interface 1: only interface 0 was bound to snd-usb-caiaq and then unbound through sysfs while the gadget flooded EP1 with EP1_CMD_READ_ERP replies. With no PCM stream running the window is very short and was only hit by stalling the unbinding CPU with a kgdb breakpoint at snd_usb_caiaq_audio_disconnect(). With the fix applied, the same test runs clean.

  BUG: KASAN: slab-use-after-free in input_event+0x3a/0xc0
  Read of size 8 at addr ffff8880151a4028 by task sh/118

  Call Trace:
   <IRQ>
   input_event+0x3a/0xc0
   snd_usb_caiaq_input_dispatch+0xab2/0xf00
   usb_ep1_command_reply_dispatch+0x1f3/0x580
   __usb_hcd_giveback_urb+0x246/0x400
   dummy_timer+0x1415/0x3380
   __hrtimer_run_queues+0x39d/0x800
   hrtimer_run_softirq+0x187/0x2d0
   handle_softirqs+0x1ff/0x930
   __irq_exit_rcu+0x15b/0x210
   irq_exit_rcu+0xe/0x20
   sysvec_apic_timer_interrupt+0x81/0xb0
   </IRQ>
   <TASK>
   asm_sysvec_apic_timer_interrupt+0x1a/0x20
  RIP: 0010:snd_usb_caiaq_audio_disconnect+0x0/0x70
   snd_disconnect+0x81/0x110
   usb_unbind_interface+0x1a0/0x860
   device_release_driver_internal+0x2c5/0x470
   unbind_store+0xde/0x100
   </TASK>

  Allocated by task 80:
   input_allocate_device+0x47/0x340
   snd_usb_caiaq_input_init+0x4c/0x1ac0
   snd_probe+0xab3/0x1160
   usb_probe_interface+0x2ea/0x810

  Freed by task 118:
   kfree+0x1ea/0x5c0
   input_dev_release+0xab/0xd0
   device_release+0xcf/0x250
   kobject_put+0x169/0x320
   snd_disconnect+0x79/0x110
   usb_unbind_interface+0x1a0/0x860
Fixes b04dcbb7f7b1 ("ALSA: caiaq: Use snd_card_free_when_closed() at disconnection")
Assisted-by Claude:claude-opus-4-8
---
 sound/usb/caiaq/device.c |   11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)
sound/usb/caiaq/device.c +8 -3
@@ -593,14 +593,19 @@ static void snd_disconnect(struct usb_in
 
 	snd_card_disconnect(card);
 
+	/*
+	 * Kill the EP1 URB before disconnecting the input device: its
+	 * completion reports into cdev->input_dev, which input_disconnect()
+	 * frees without clearing the pointer.
+	 */
+	usb_kill_urb(cdev->ep1_in_urb);
+	usb_kill_urb(cdev->midi_out_urb);
+
 #ifdef CONFIG_SND_USB_CAIAQ_INPUT
 	snd_usb_caiaq_input_disconnect(cdev);
 #endif
 	snd_usb_caiaq_audio_disconnect(cdev);
 
-	usb_kill_urb(cdev->ep1_in_urb);
-	usb_kill_urb(cdev->midi_out_urb);
-
 	snd_card_free_when_closed(card);
 }
 
author maintainer
#558 lore raw

PATCH 554/816 ALSA: usb-audio: Drop capture packets with bogus actual_length

In reply to Greg Kroah-Hartman

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

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

From: Gichoon Han <[email protected]>

commit eed0e9583a290e6adbe3a8480bdae911f31e1ed9 upstream.

retire_capture_urb() copies urb->iso_frame_desc[i].actual_length bytes out of urb->transfer_buffer at the packet's offset, but never checks that value against the requested packet length. A host controller reporting more data than requested makes memcpy() read past the end of the URB transfer buffer.

Commit 06be918062ad ("ALSA: usb-audio: Bound packet copies by the PCM buffer size") clamps the count to the PCM ring buffer size, which protects the destination. The source slot is only ep->curpacksize bytes per packet, though, so the over-read remains.

This was hit on an ARM32 system (vendor 5.4 kernel; the code path is unchanged in mainline) with a full-speed UAC1 microphone behind a high-speed hub, i.e. the EHCI siTD path. sitd_complete() computes actual_length as desc->length - SITD_LENGTH(t); the controller reported a remaining length larger than the programmed one, the value wrapped to ~4G, and the capture copy faulted on the first unmapped page after the URB buffer:

  Unable to handle kernel paging request at virtual address e8756000
  Internal error: Oops: 7 [#1] PREEMPT SMP ARM
  r3 : 00000000  r2 : 0001e700  r1 : e8756000  r0 : e878fc80
  Code: ba000002 f5d1f03c f5d1f05c f5d1f07c (e8b151f8)

A packet can never legitimately carry more than its requested length, so warn and skip it instead of copying.

---
 sound/usb/pcm.c |    6 ++++++
 1 file changed, 6 insertions(+)
sound/usb/pcm.c +6 -0
@@ -1286,6 +1286,12 @@ static void retire_capture_urb(struct sn
 			// continue;
 		}
 		bytes = urb->iso_frame_desc[i].actual_length;
+		if (unlikely(bytes > urb->iso_frame_desc[i].length)) {
+			dev_warn_ratelimited(&subs->dev->dev,
+					     "packet %d: actual_length %u exceeds length %u, dropping\n",
+					     i, bytes, urb->iso_frame_desc[i].length);
+			continue;
+		}
 		if (subs->stream_offset_adj > 0) {
 			unsigned int adj = min(subs->stream_offset_adj, bytes);
 			cp += adj;
author maintainer
#559 lore raw

PATCH 555/816 selftests/ftrace: Add missing spaces after ! in probe syntax tests

In reply to Greg Kroah-Hartman

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

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

From: Jaewon Jung <[email protected]>

commit 36990c8fda77d918b1e52d5d6df3a144b552d86e upstream.

Add the missing space between ! and grep. Otherwise, the shell tries to run !grep and reports "!grep: not found". This always skips the conditional checks without checking for kernel return probe argument support.

Fixes 25f00e40ce79 ("tracing/probes: Support $argN in return probe (kprobe and fprobe)")
---
 tools/testing/selftests/ftrace/test.d/dynevent/fprobe_syntax_errors.tc |    4 ++--
 tools/testing/selftests/ftrace/test.d/kprobe/kprobe_syntax_errors.tc   |    2 +-
 2 files changed, 3 insertions(+), 3 deletions(-)
tools/testing/selftests/ftrace/test.d/dynevent/fprobe_syntax_errors.tc +2 -2
@@ -34,7 +34,7 @@ check_error 'f vfs_read ^$stack10000'	#
 
 check_error 'f vfs_read ^$arg10000'	# BAD_ARG_NUM
 
-if !grep -q 'kernel return probes support:' README; then
+if ! grep -q 'kernel return probes support:' README; then
 check_error 'f vfs_read $retval ^$arg1' # BAD_VAR
 fi
 check_error 'f vfs_read ^$none_var'	# BAD_VAR
@@ -101,7 +101,7 @@ if grep -q "<argname>" README; then
 check_error 'f vfs_read args=^$arg*'		# BAD_VAR_ARGS
 check_error 'f vfs_read +0(^$arg*)'		# BAD_VAR_ARGS
 check_error 'f vfs_read $arg* ^$arg*'		# DOUBLE_ARGS
-if !grep -q 'kernel return probes support:' README; then
+if ! grep -q 'kernel return probes support:' README; then
 check_error 'f vfs_read%return ^$arg*'		# NOFENTRY_ARGS
 fi
 check_error 'f vfs_read ^hoge'			# NO_BTFARG
tools/testing/selftests/ftrace/test.d/kprobe/kprobe_syntax_errors.tc +1 -1
@@ -108,7 +108,7 @@ if grep -q "<argname>" README; then
 check_error 'p vfs_read args=^$arg*'		# BAD_VAR_ARGS
 check_error 'p vfs_read +0(^$arg*)'		# BAD_VAR_ARGS
 check_error 'p vfs_read $arg* ^$arg*'		# DOUBLE_ARGS
-if !grep -q 'kernel return probes support:' README; then
+if ! grep -q 'kernel return probes support:' README; then
 check_error 'r vfs_read ^$arg*'			# NOFENTRY_ARGS
 fi
 check_error 'p vfs_read+20 ^$arg*'		# NOFENTRY_ARGS
author maintainer
#560 lore raw

PATCH 556/816 tracing/selftests: Fix false bashism in kprobe_non_uniq_symbol.tc

In reply to Greg Kroah-Hartman

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

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

From: Steven Rostedt <[email protected]>

commit 88d5f8cb8a6276194ac8c1de44f3ed77d7e938ce upstream.

The checkbashism is giving a false positive to the kprobe test of:

($"foo" should be eval_gettext "foo"):
if [ "$(grep -c -E "[[:alnum:]]+ t ${SYMBOL}$" /proc/kallsyms)" -le '1' ]; then

This is because it sees the $" at the end of the grep as a bash symbol. Instead, escape the '$' with a backslash as it is within quotes and that '$' is for grep to process an end of line character and not a bash variable.

---
 tools/testing/selftests/ftrace/test.d/kprobe/kprobe_non_uniq_symbol.tc |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
tools/testing/selftests/ftrace/test.d/kprobe/kprobe_non_uniq_symbol.tc +1 -1
@@ -6,7 +6,7 @@
 SYMBOL='name_show'
 
 # We skip this test on kernel where SYMBOL is unique or does not exist.
-if [ "$(grep -c -E "[[:alnum:]]+ t ${SYMBOL}$" /proc/kallsyms)" -le '1' ]; then
+if [ "$(grep -c -E "[[:alnum:]]+ t ${SYMBOL}\$" /proc/kallsyms)" -le '1' ]; then
 	exit_unsupported
 fi
 
author maintainer
#561 lore raw

PATCH 557/816 mmc: mmci: fix DMA channel leak when mmc_add_host() fails

In reply to Greg Kroah-Hartman

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

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

From: Anfernee Cao <[email protected]>

commit 2d8927fadbf95e2d2dfa95bcc73882d6e19c2ce4 upstream.

mmci_probe() calls mmci_dma_setup(), which acquires the RX and TX DMA channels via dma_request_chan(). These channels are not managed by devres, and are released only by mmci_dma_release().

If the following mmc_add_host() fails, probe jumps to the clk_disable label, which only disables the clock. As probe then fails, mmci_remove() is never called, so both DMA channels are leaked.

Release them by adding a dedicated unwind label, reached only after mmci_dma_setup().

This issue was found by manual code inspection.

Fixes b38a20f29a49 ("mmc: mmci: fix return value check of mmc_add_host()")
---
 drivers/mmc/host/mmci.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/mmc/host/mmci.c +3 -1
@@ -2484,11 +2484,13 @@ static int mmci_probe(struct amba_device
 
 	ret = mmc_add_host(mmc);
 	if (ret)
-		goto clk_disable;
+		goto dma_release;
 
 	pm_runtime_put(&dev->dev);
 	return 0;
 
+dma_release:
+	mmci_dma_release(host);
  clk_disable:
 	clk_disable_unprepare(host->clk);
  host_free:
author maintainer
#562 lore raw

PATCH 558/816 mmc: sdhci-esdhc-imx: map unsupported driver type to Type B

In reply to Greg Kroah-Hartman

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

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

From: Ian Ray <[email protected]>

commit d35d93c2902592a84347a15deac4d67a323694c9 upstream.

Since commit 5a52c5701a67 ("mmc: core: Fix host controller programming for fixed driver type"), the eMMC driver strength is passed directly to mmc_set_driver_type(), which propagates the value through ios.drv_type all the way to sdhci_set_ios(). For value 4, SDHCI correctly warns:

mmc2: invalid driver type, default to driver type B

The host driver type has no effect on this controller: esdhc_writew_le() never programs the driver-type field of SDHCI_HOST_CONTROL2. Hook set_ios() and force drv_type to the always-valid Type B, so that SDHCI never sees an unsupported value.

Tested on i.MX8MP (usdhc3, eMMC in HS400) with fixed-emmc-driver-type = <4>: the warning is gone and the HS_TIMING register contains 0x43 as expected.

---
 drivers/mmc/host/sdhci-esdhc-imx.c |   17 +++++++++++++++++
 1 file changed, 17 insertions(+)
drivers/mmc/host/sdhci-esdhc-imx.c +17 -0
@@ -1092,6 +1092,20 @@ static void esdhc_reset_tuning(struct sd
 	}
 }
 
+static void sdhci_esdhc_imx_set_ios(struct mmc_host *mmc, struct mmc_ios *ios)
+{
+	/*
+	 * This controller has no driver-type control: esdhc_writew_le()
+	 * discards the driver-type field when writing SDHCI_HOST_CONTROL2.
+	 * The programmed value is therefore irrelevant, but SDHCI rejects
+	 * non-SD values such as 4 (eMMC 40 ohm, from fixed-emmc-driver-type).
+	 * Force an always-valid Type B.
+	 */
+	ios->drv_type = MMC_SET_DRIVER_TYPE_B;
+
+	sdhci_set_ios(mmc, ios);
+}
+
 static void usdhc_init_card(struct mmc_host *mmc, struct mmc_card *card)
 {
 	struct sdhci_host *host = mmc_priv(mmc);
@@ -1766,6 +1780,9 @@ static int sdhci_esdhc_imx_probe(struct
 		host->mmc_host_ops.init_card = usdhc_init_card;
 	}
 
+	/* No SDHCI driver type control */
+	host->mmc_host_ops.set_ios = sdhci_esdhc_imx_set_ios;
+
 	if (imx_data->socdata->flags & ESDHC_FLAG_MAN_TUNING)
 		sdhci_esdhc_ops.platform_execute_tuning =
 					esdhc_executing_tuning;
author maintainer
#563 lore raw

PATCH 559/816 mmc: meson-gx: report busy from DAT0 alone

In reply to Greg Kroah-Hartman

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

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

From: Igor Velkov <[email protected]>

commit 318fdb75f4dc9d18ae621b9fb25eb11160c95649 upstream.

meson_mmc_card_busy() reports busy only while DAT0..3 are all low. A busy card drives DAT0 low and leaves DAT1..3 to the pull-ups, and the callback is defined as "Check if the card is pulling dat[0] low". So a busy card is reported free, and the core, which prefers card_busy over CMD13 in mmc_busy_cb(), stops polling after CMD6 and erase at once. The controller hides this on R1b commands, where it waits for busy itself. Once max_busy_timeout is reported, the core sends the longer waits, the 120 s BKOPS and 240 s sanitize switches among them, as R1 and has only the polling left.

Look at DAT0 only, as sdhci_card_busy() does. The checks around the voltage switch in mmc_set_uhs_voltage() still hold: the card drives DAT0..3 low together after CMD11 and keeps them low together on failure.

Fixes 186cd8b7f586 ("mmc: meson-gx: implement card_busy callback")
---
 drivers/mmc/host/meson-gx-mmc.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/mmc/host/meson-gx-mmc.c +2 -2
@@ -1079,8 +1079,8 @@ static int meson_mmc_card_busy(struct mm
 
 	regval = readl(host->regs + SD_EMMC_STATUS);
 
-	/* We are only interrested in lines 0 to 3, so mask the other ones */
-	return !(FIELD_GET(STATUS_DATI, regval) & 0xf);
+	/* The card signals busy on DAT0 alone. */
+	return !(FIELD_GET(STATUS_DATI, regval) & BIT(0));
 }
 
 static int meson_mmc_voltage_switch(struct mmc_host *mmc, struct mmc_ios *ios)
author maintainer
#564 lore raw

PATCH 560/816 mmc: meson-gx: honour the busy timeout for R1b commands

In reply to Greg Kroah-Hartman

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

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

From: Igor Velkov <[email protected]>

commit 7e3cc541aa5855bc36e6cbffa82efc2795955a10 upstream.

For a command without data the driver programs a fixed 1024 ms into the CMD_CFG timeout field, and for R1b the controller waits for the card to release busy within that time. The core sends erase and cache flush as R1b with busy timeouts of up to 60 s and 30 s, and the controller gives up after one second:

mmc_erase: erase error -110, status 0x0
mmc1: cache flush error -110

Program the timeout from cmd->busy_timeout, kept between 1024 ms, the fixed value until now, and 32768 ms, the most the field holds, and rounded up to a power of two. The clamp comes first: MMC_IOC_CMD passes cmd_timeout_ms from user space straight into busy_timeout, and roundup_pow_of_two() of a value above 2^31 does not fit in unsigned int. sdhci takes its command timeout from cmd->busy_timeout in the same way.

Fixes 51c5d8447bd7 ("MMC: meson: initial support for GX platforms")
---
 drivers/mmc/host/meson-gx-mmc.c |   16 +++++++++++++++-
 1 file changed, 15 insertions(+), 1 deletion(-)
drivers/mmc/host/meson-gx-mmc.c +15 -1
@@ -214,6 +214,20 @@ static unsigned int meson_mmc_get_timeou
 	return min(timeout, 32768U); /* max. 2^15 ms */
 }
 
+/* For R1b the controller waits for busy to be released within this timeout. */
+static unsigned int meson_mmc_get_cmd_timeout_msecs(struct mmc_command *cmd)
+{
+	unsigned int timeout = cmd->busy_timeout;
+
+	if (!timeout)
+		return SD_EMMC_CMD_TIMEOUT;
+
+	timeout = clamp_t(unsigned int, timeout, SD_EMMC_CMD_TIMEOUT,
+			  SD_EMMC_CMD_TIMEOUT_MAX);
+
+	return roundup_pow_of_two(timeout);
+}
+
 static struct mmc_command *meson_mmc_get_next_command(struct mmc_command *cmd)
 {
 	if (cmd->opcode == MMC_SET_BLOCK_COUNT && !cmd->error)
@@ -840,7 +854,7 @@ static void meson_mmc_start_cmd(struct m
 		cmd_data = host->bounce_dma_addr & CMD_DATA_MASK;
 	} else {
 		cmd_cfg |= FIELD_PREP(CMD_CFG_TIMEOUT_MASK,
-				      ilog2(SD_EMMC_CMD_TIMEOUT));
+				      ilog2(meson_mmc_get_cmd_timeout_msecs(cmd)));
 	}
 
 	/* Last descriptor */
author maintainer
#565 lore raw

PATCH 561/816 mmc: meson-gx: report the longest busy wait the controller can do

In reply to Greg Kroah-Hartman

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

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

From: Igor Velkov <[email protected]>

commit 18e9f7fb05ada68d491ff49165b9644f790e0e0c upstream.

The driver does not set max_busy_timeout, so the core takes the host for one that can wait for busy indefinitely and sends erase and cache flush as R1b with busy timeouts of up to 60 s and 30 s. The CMD_CFG timeout field holds at most 32768 ms, so the controller times out first.

Report 32768 ms as max_busy_timeout. The core then sizes discards to fit and, for a longer wait, sends R1 and polls for busy itself.

Fixes 51c5d8447bd7 ("MMC: meson: initial support for GX platforms")
---
 drivers/mmc/host/meson-gx-mmc.c |    3 +++
 1 file changed, 3 insertions(+)
drivers/mmc/host/meson-gx-mmc.c +3 -0
@@ -1180,6 +1180,9 @@ static int meson_mmc_probe(struct platfo
 
 	mmc->caps |= MMC_CAP_CMD23;
 
+	/* The longest busy wait the CMD_CFG timeout field can hold. */
+	mmc->max_busy_timeout = SD_EMMC_CMD_TIMEOUT_MAX;
+
 	if (mmc->caps & MMC_CAP_SDIO_IRQ)
 		mmc->caps2 |= MMC_CAP2_SDIO_IRQ_NOTHREAD;
 
author maintainer
#566 lore raw

PATCH 562/816 mmc: meson-gx: name the limit of the CMD_CFG timeout field

In reply to Greg Kroah-Hartman

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

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

From: Igor Velkov <[email protected]>

commit e1644210d15f7f8adbe6315199b4b73bead63a2c upstream.

The data timeout is capped at a literal 32768 ms with a comment next to it. Give the limit a name beside the other timeout constants.

Fixes 51c5d8447bd7 ("MMC: meson: initial support for GX platforms")
---
 drivers/mmc/host/meson-gx-mmc.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/mmc/host/meson-gx-mmc.c +2 -1
@@ -125,6 +125,7 @@
 #define SD_EMMC_CFG_RESP_TIMEOUT 256 /* in clock cycles */
 #define SD_EMMC_CMD_TIMEOUT 1024 /* in ms */
 #define SD_EMMC_CMD_TIMEOUT_DATA 4096 /* in ms */
+#define SD_EMMC_CMD_TIMEOUT_MAX 32768 /* in ms, 2^15: limit of CMD_CFG_TIMEOUT_MASK */
 #define SD_EMMC_CFG_CMD_GAP 16 /* in clock cycles */
 #define SD_EMMC_DESC_BUF_LEN PAGE_SIZE
 
@@ -211,7 +212,7 @@ static unsigned int meson_mmc_get_timeou
 
 	timeout = roundup_pow_of_two(timeout);
 
-	return min(timeout, 32768U); /* max. 2^15 ms */
+	return min_t(unsigned int, timeout, SD_EMMC_CMD_TIMEOUT_MAX);
 }
 
 /* For R1b the controller waits for busy to be released within this timeout. */
author maintainer
#567 lore raw

PATCH 563/816 backing-file: pass RWF_NOAPPEND to synchronous writes

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

commit afa735786a89bde4959db52f20e3579de54ec740 upstream.

pwritev2() with RWF_NOAPPEND ignores the offset and appends the data on an overlayfs or FUSE passthrough file that was opened with O_APPEND, and the call still returns success. The flag must make the write go to the given offset even though the file is in append mode. Any user who can write to the file is affected, with the default mount options.

overlayfs and FUSE passthrough forward the reads and writes on their files to a backing file on an underlying filesystem, through the helpers in fs/backing-file.c.

The flag works for the file that the user opened: kiocb_set_rw_flags() clears IOCB_APPEND in the write's kiocb. It also copies RWF_NOAPPEND into ki_flags, as it does with every RWF_ flag.

overlayfs and FUSE passthrough then pass the write on to the backing file. They opened it with the open flags of the user's file, so it is in append mode too.

For a synchronous write, do_backing_file_write_iter() calls vfs_iter_write(), which sets up a new kiocb for the backing file. That kiocb starts out with IOCB_APPEND set. vfs_iter_write() is only given the flags of the user's kiocb that are in BACKING_IOCB_MASK, and RWF_NOAPPEND is not one of them. So nothing clears IOCB_APPEND again, and the data goes to the end of the file while the call returns success.

An asynchronous write reuses the flags of the user's kiocb and is not affected.

Reproduced by calling pwritev2() with RWF_NOAPPEND at offset 0, on an overlayfs file and on a FUSE passthrough file opened with O_APPEND: the data was at the end of the file afterwards.

Fix this by adding RWF_NOAPPEND to BACKING_IOCB_MASK.

---
 fs/backing-file.c |    7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)
fs/backing-file.c +6 -1
@@ -103,8 +103,13 @@ struct backing_aio {
 
 static struct kmem_cache *backing_aio_cachep;
 
+/*
+ * RWF_NOAPPEND stays set in ki_flags.  Pass it on, because the backing file is
+ * in append mode as well and a new kiocb for it starts with IOCB_APPEND.
+ */
 #define BACKING_IOCB_MASK \
-	(IOCB_NOWAIT | IOCB_HIPRI | IOCB_DSYNC | IOCB_SYNC | IOCB_APPEND)
+	(IOCB_NOWAIT | IOCB_HIPRI | IOCB_DSYNC | IOCB_SYNC | IOCB_APPEND | \
+	 (__force int) RWF_NOAPPEND)
 
 static rwf_t iocb_to_rw_flags(int flags)
 {
author maintainer
#568 lore raw

PATCH 564/816 eventpoll: wake the next waiter when a woken waiter is killed

In reply to Greg Kroah-Hartman

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

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

From: Mani Tofigh <[email protected]>

commit 9f4413e522faed76f4cf610098b2369eb3ba1f1c upstream.

Processes sharing an epoll instance can sleep forever while an event is ready. An event wakes only one waiter, which then wakes the next one in ep_done_scan() if events are still ready. Since commit c257a340ede0 ("fs, epoll: short circuit fetching events if thread has been killed"), ep_send_events() returns before the scan when the waiter has a fatal signal. If the woken waiter is killed before it runs, nobody wakes the next one:

Task A Task B Task C
epoll_wait(ep, -1) epoll_wait(ep, -1)

                                                    write(efd)
                                                      /* wakes A only */
                                                    kill(A, SIGKILL)
  ep_send_events()
    return -EINTR
      /* skips ep_done_scan() */
                             /* still asleep */

B then sleeps until another file on the instance becomes ready, if ever. This can hit eg a pre-fork server whose worker gets OOM killed. Commit 7fab29e35630 ("fs/epoll: restore waking from ep_done_scan()") fixed the same kind of hang when the wakeup in ep_done_scan() was removed.

Keep the early return so that a dying task still doesn't take events nobody will see, but wake the next waiter there if events are ready, as ep_done_scan() would have. With the fix, B gets the event.

This bug was identified and confirmed with the help of a deterministic hypervisor currently under development. The C reproducer below however hits it within about 2s.

Fixes c257a340ede0 ("fs, epoll: short circuit fetching events if thread has been killed")
---
 fs/eventpoll.c |   11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
fs/eventpoll.c +9 -2
@@ -2074,10 +2074,17 @@ static int ep_send_events(struct eventpo
 	/*
 	 * Always short-circuit for fatal signals to allow threads to make a
 	 * timely exit without the chance of finding more events available and
-	 * fetching repeatedly.
+	 * fetching repeatedly. The wakeup that got us here may have been the
+	 * only one for the events on ->rdllist, so pass it on to the next
+	 * waiter, as ep_done_scan() would have.
 	 */
-	if (fatal_signal_pending(current))
+	if (fatal_signal_pending(current)) {
+		spin_lock_irq(&ep->lock);
+		if (!list_empty(&ep->rdllist))
+			wake_up(&ep->wq);
+		spin_unlock_irq(&ep->lock);
 		return -EINTR;
+	}
 
 	init_poll_funcptr(&pt, NULL);
 
author maintainer
#569 lore raw

PATCH 565/816 aio: dont let exit_aio() return before complete() is done

In reply to Greg Kroah-Hartman

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

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

From: Christian Brauner <[email protected]>

commit ac4b449b39e605123c12ea10042cafc9b6f39603 upstream.

exit_aio() kills all contexts in one go and waits for them with a single on-stack struct ctx_rq_wait. The count starts at table->nr, each killed context drops one count in free_ioctx_reqs() and exit_aio() subtracts the empty slots afterwards. Whoever drops the last count either calls complete() or, if it is exit_aio(), skips the wait.

With a full table skipped is zero and atomic_sub_and_test(0, ...) only tells us whether the count already hit zero. free_ioctx_reqs() runs from the percpu_ref RCU callback, so if exit_aio() is off the CPU long enough the last callback can have done its atomic_dec_and_test() but not yet called complete():

    free_ioctx_reqs()                    exit_aio()
    atomic_dec_and_test() // 1 -> 0
                                         atomic_sub_and_test(0) // true
                                         kfree(table)
                                         return
    complete(&wait.comp)

complete() then locks and writes a completion on a stack frame that is gone. So hold an extra count for exit_aio() itself. Then the last count is always dropped by exit_aio() after it waited, or by a callback while exit_aio() waits for it. An unprivileged user gets there with four io_setup() calls and an exit without io_destroy().

---
 fs/aio.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
fs/aio.c +2 -2
@@ -910,7 +910,7 @@ void exit_aio(struct mm_struct *mm)
 	if (!table)
 		return;
 
-	atomic_set(&wait.count, table->nr);
+	atomic_set(&wait.count, table->nr + 1);
 	init_completion(&wait.comp);
 
 	skipped = 0;
@@ -934,7 +934,7 @@ void exit_aio(struct mm_struct *mm)
 		kill_ioctx(mm, ctx, &wait);
 	}
 
-	if (!atomic_sub_and_test(skipped, &wait.count)) {
+	if (!atomic_sub_and_test(skipped + 1, &wait.count)) {
 		/* Wait until all IO for the context are done. */
 		wait_for_completion(&wait.comp);
 	}
author maintainer
#570 lore raw

PATCH 566/816 splice, net: avoid MSG_MORE when the bvec array fills

In reply to Greg Kroah-Hartman

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

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

From: Avi Weiss <[email protected]>

commit 8eaa35c6c29ae669949f4b5b0814c3d34c8ed658 upstream.

splice_to_socket() leaves tail at the last included pipe buffer when its 16-entry bvec array fills. If the requested length exceeds the available pipe data, pipe_occupancy() counts that buffer again and sets MSG_MORE even though the pipe is empty. Small TCP transfers can then be delayed until the cork timeout expires.

Advance tail before checking the array limit so the occupancy test counts only pipe buffers that have not been included in the send.

Fixes ca2d49f77ce4 ("splice, net: Fix splice_to_socket() to handle pipe bufs larger than a page")
---
 fs/splice.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/splice.c +1 -1
@@ -871,9 +871,9 @@ ssize_t splice_to_socket(struct pipe_ino
 
 			bvec_set_page(&bvec[bc++], buf->page, seg, buf->offset);
 			remain -= seg;
+			tail++;
 			if (remain == 0 || bc >= ARRAY_SIZE(bvec))
 				break;
-			tail++;
 		}
 
 		if (!bc)
author maintainer
#571 lore raw

PATCH 567/816 mm/mmzone: read the zoneref slot once in zonelist_zone()

In reply to Greg Kroah-Hartman

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

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

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

commit 9c52ebe9c89d41c56fcb5d94efe9e539414175a9 upstream.

Memory hotplug rebuilds zonelists in place while allocations walk them, so a zoneref slot can change between two loads of it.

zonelist_zone() loads the slot with a plain access. The compiler may load it again later instead of keeping the zone it already read, so a caller can check one zone and then use another, or the NULL terminator.

Use READ_ONCE(). Callers that take a zone from a slot and keep using it, such as get_page_from_freelist() with ac->preferred_zoneref, need that single load.

---
 include/linux/mmzone.h |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
include/linux/mmzone.h +2 -1
@@ -1627,7 +1627,8 @@ extern struct zone *next_zone(struct zon
 
 static inline struct zone *zonelist_zone(struct zoneref *zoneref)
 {
-	return zoneref->zone;
+	/* Memory hotplug rewrites zonelists in place. */
+	return READ_ONCE(zoneref->zone);
 }
 
 static inline int zonelist_zone_idx(struct zoneref *zoneref)
author maintainer
#572 lore raw

PATCH 568/816 mm, page_alloc: pass zone pointer to trace_reclaim_retry_zone

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

commit 6c48b3ab4ee435c41c3395d31e8ec3dbccc3478c upstream.

should_reclaim_retry() walks a zonelist and passes the zoneref pointer to the reclaim_retry_zone tracepoint, which loads the zone from the entry again to find the node.

Memory hotplug rebuilds the zonelists in place while allocations are under way. When a zone in front of the zoneref entry has become empty, the entries move up, and this one can be the end marker by the time the tracepoint looks at it. zonelist_node_idx() then dereferences a NULL zone. Short of that, the event can name another zone than the one its numbers belong to.

Pass the zone pointer instead of the zoneref pointer.

---
 include/trace/events/oom.h |    8 ++++----
 mm/page_alloc.c            |    2 +-
 2 files changed, 5 insertions(+), 5 deletions(-)
include/trace/events/oom.h +4 -4
@@ -33,7 +33,7 @@ TRACE_EVENT(oom_score_adj_update,
 
 TRACE_EVENT(reclaim_retry_zone,
 
-	TP_PROTO(struct zoneref *zoneref,
+	TP_PROTO(struct zone *zone,
 		int order,
 		unsigned long reclaimable,
 		unsigned long available,
@@ -41,7 +41,7 @@ TRACE_EVENT(reclaim_retry_zone,
 		int no_progress_loops,
 		bool wmark_check),
 
-	TP_ARGS(zoneref, order, reclaimable, available, min_wmark, no_progress_loops, wmark_check),
+	TP_ARGS(zone, order, reclaimable, available, min_wmark, no_progress_loops, wmark_check),
 
 	TP_STRUCT__entry(
 		__field(	int, node)
@@ -55,8 +55,8 @@ TRACE_EVENT(reclaim_retry_zone,
 	),
 
 	TP_fast_assign(
-		__entry->node = zonelist_node_idx(zoneref);
-		__entry->zone_idx = zonelist_zone_idx(zoneref);
+		__entry->node = zone_to_nid(zone);
+		__entry->zone_idx = zone_idx(zone);
 		__entry->order = order;
 		__entry->reclaimable = reclaimable;
 		__entry->available = available;
mm/page_alloc.c +1 -1
@@ -4227,7 +4227,7 @@ should_reclaim_retry(gfp_t gfp_mask, uns
 		 */
 		wmark = __zone_watermark_ok(zone, order, min_wmark,
 				ac->highest_zoneidx, alloc_flags, available);
-		trace_reclaim_retry_zone(z, order, reclaimable,
+		trace_reclaim_retry_zone(zone, order, reclaimable,
 				available, min_wmark, *no_progress_loops, wmark);
 		if (wmark) {
 			ret = true;
author maintainer
#573 lore raw

PATCH 569/816 mm/mempolicy: read the zoneref slot once in mempolicy_slab_node()

In reply to Greg Kroah-Hartman

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

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

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

commit 4cc1bcdf2e4ebcd319005ce2ea132489f6155139 upstream.

For a bind or preferred-many policy, mempolicy_slab_node() tests the first matching slot's zone for NULL, then reads the slot again to look up the zone's node. Offlining a zone's last block rebuilds the zonelists in place, so the second read can return the terminator:

CPU 0 CPU 1
mempolicy_slab_node()
zonelist_zone(slot 4)
= node 2 NORMAL
offline_pages()
build_all_zonelists()
slot 4 = NULL
zonelist_node_idx(slot 4)
zone_to_nid(NULL)

Current GCC merges the two reads, but nothing requires it. With mm/mempolicy.o built with -fno-inline -fno-ipa-sra, holding a bound task's slab_strict_numa allocation between the reads while a movable block earlier in the zonelist goes offline oopses every time:

  BUG: kernel NULL pointer dereference, address: 0000000000000060
  RIP: 0010:zone_to_nid+0x0/0x10
  Call Trace:
   kmem_cache_alloc_noprof+0x294/0x610
   do_getname+0x34/0x230

mempolicy_slab_node() and zonelist_node_idx() are tail calls here, so neither appears in the trace.

Read the slot once and use that zone.

---
 mm/mempolicy.c |    4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
mm/mempolicy.c +3 -1
@@ -1937,6 +1937,7 @@ unsigned int mempolicy_slab_node(void)
 	case MPOL_PREFERRED_MANY:
 	{
 		struct zoneref *z;
+		struct zone *zone;
 
 		/*
 		 * Follow bind policy behavior and start allocation at the
@@ -1947,7 +1948,8 @@ unsigned int mempolicy_slab_node(void)
 		zonelist = &NODE_DATA(node)->node_zonelists[ZONELIST_FALLBACK];
 		z = first_zones_zonelist(zonelist, highest_zoneidx,
 							&policy->nodes);
-		return zonelist_zone(z) ? zonelist_node_idx(z) : node;
+		zone = zonelist_zone(z);
+		return zone ? zone_to_nid(zone) : node;
 	}
 	case MPOL_LOCAL:
 		return node;
author maintainer
#574 lore raw

PATCH 570/816 mm/memory_hotplug: resize zones under their seqlock

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

commit 58e81bb7de5aac8ec5e4aa21d401e7dafbd4058b upstream.

With CONFIG_DEBUG_VM the page allocator checks that a page which is freed, split or allocated lies within its zone. The check reads zone->zone_start_pfn and zone->spanned_pages under zone->span_seqlock, as memory hotplug can change the two at any time.

Commit 27cacaad16c5 ("mm,memory_hotplug: drop unneeded locking") removed the write side, since all resizing is serialized by the hotplug lock. That leaves the reader without protection. When memory below the start of a zone goes online, the start is lowered first and the size is raised afterwards. When the lowest memory of a zone goes offline, the size is reduced first. In between, the zone seems to end before its last pages. If one of them goes through the allocator at that moment, it is reported as being outside of the zone triggers VM_BUG_ON_PAGE().

Write the two fields in a write section of the seqlock. Interrupts are disabled as pages are freed from interrupts, too, and the reader would wait for the writer which it has interrupted.

---
 mm/memory_hotplug.c |   44 ++++++++++++++++++++++++++++----------------
 1 file changed, 28 insertions(+), 16 deletions(-)
mm/memory_hotplug.c +28 -16
@@ -479,6 +479,22 @@ static unsigned long find_biggest_sectio
 	return 0;
 }
 
+/*
+ * The page allocator checks pages against the span of their zone while the
+ * zone is resized, see page_outside_zone_boundaries(). It must not see the
+ * new value of one field together with the old value of the other one.
+ */
+static void zone_set_span(struct zone *zone, unsigned long start_pfn,
+			  unsigned long spanned_pages)
+{
+	unsigned long flags;
+
+	write_seqlock_irqsave(&zone->span_seqlock, flags);
+	zone->zone_start_pfn = start_pfn;
+	zone->spanned_pages = spanned_pages;
+	write_sequnlock_irqrestore(&zone->span_seqlock, flags);
+}
+
 static void shrink_zone_span(struct zone *zone, unsigned long start_pfn,
 			     unsigned long end_pfn)
 {
@@ -494,13 +510,10 @@ static void shrink_zone_span(struct zone
 		 */
 		pfn = find_smallest_section_pfn(nid, zone, end_pfn,
 						zone_end_pfn(zone));
-		if (pfn) {
-			zone->spanned_pages = zone_end_pfn(zone) - pfn;
-			zone->zone_start_pfn = pfn;
-		} else {
-			zone->zone_start_pfn = 0;
-			zone->spanned_pages = 0;
-		}
+		if (pfn)
+			zone_set_span(zone, pfn, zone_end_pfn(zone) - pfn);
+		else
+			zone_set_span(zone, 0, 0);
 	} else if (zone_end_pfn(zone) == end_pfn) {
 		/*
 		 * If the section is biggest section in the zone, it need
@@ -511,11 +524,10 @@ static void shrink_zone_span(struct zone
 		pfn = find_biggest_section_pfn(nid, zone, zone->zone_start_pfn,
 					       start_pfn);
 		if (pfn)
-			zone->spanned_pages = pfn - zone->zone_start_pfn + 1;
-		else {
-			zone->zone_start_pfn = 0;
-			zone->spanned_pages = 0;
-		}
+			zone_set_span(zone, zone->zone_start_pfn,
+				      pfn - zone->zone_start_pfn + 1);
+		else
+			zone_set_span(zone, 0, 0);
 	}
 }
 
@@ -723,12 +735,12 @@ static void node_states_set_node(int nod
 static void __meminit resize_zone_range(struct zone *zone, unsigned long start_pfn,
 		unsigned long nr_pages)
 {
-	unsigned long old_end_pfn = zone_end_pfn(zone);
+	unsigned long end_pfn = max(start_pfn + nr_pages, zone_end_pfn(zone));
 
-	if (zone_is_empty(zone) || start_pfn < zone->zone_start_pfn)
-		zone->zone_start_pfn = start_pfn;
+	if (!zone_is_empty(zone) && start_pfn > zone->zone_start_pfn)
+		start_pfn = zone->zone_start_pfn;
 
-	zone->spanned_pages = max(start_pfn + nr_pages, old_end_pfn) - zone->zone_start_pfn;
+	zone_set_span(zone, start_pfn, end_pfn - start_pfn);
 }
 
 static void __meminit resize_pgdat_range(struct pglist_data *pgdat, unsigned long start_pfn,
author maintainer
#575 lore raw

PATCH 571/816 mm/page_alloc: keep the pagesets of an empty zone

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

commit 7bfcf81b1cb469bc016fa8e07939c0924b9ff8db upstream.

When the last memory of a zone goes offline, zone_pcp_reset() frees zone->per_cpu_pageset and zone->per_cpu_zonestats. Nothing waits for those who found the zone populated and still use the two pointers. They take neither the memory hotplug lock nor any other lock which offline_pages() holds, and some of them can sleep:

CPU0 vmstat_update() CPU1 offline_pages()
refresh_cpu_vm_stats()

    for_each_populated_zone(zone)
      pcp = zone->per_cpu_pageset
      cond_resched()
                                      adjust_present_page_count()
                                      zone_pcp_reset(zone)
                                        free_percpu(zone->per_cpu_pageset)
      decay_pcp_high(zone, pcp)
      __this_cpu_write(pcp->expire, 0)

The same goes for drain_all_pages(NULL), which takes pcp->lock, for zone_pcp_update(), show_free_areas() and the readers and writers of the zonestats. If the per-cpu memory has got a new owner in the meantime, it is corrupted.

The pagesets are only freed because setup_zone_pageset() would otherwise leak them when the zone gets memory again. Keep them instead and let setup_zone_pageset() and zone_pcp_init() use them again, like it is done with pgdat->per_cpu_nodestats. Their lists are empty, and their limits have been calculated for a zone without memory by the init_per_zone_wmark_min() of offline_pages(), which is what setup_zone_pageset() would come up with as well.

---
 mm/page_alloc.c |   20 ++++++++++++++------
 1 file changed, 14 insertions(+), 6 deletions(-)
mm/page_alloc.c +14 -6
@@ -5840,6 +5840,10 @@ void __meminit setup_zone_pageset(struct
 {
 	int cpu;
 
+	/* The zone has been populated before, see zone_pcp_reset(). */
+	if (zone->per_cpu_pageset != &boot_pageset)
+		return;
+
 	/* Size may be 0 on !SMP && !NUMA */
 	if (sizeof(struct per_cpu_zonestat) > 0)
 		zone->per_cpu_zonestats = alloc_percpu(struct per_cpu_zonestat);
@@ -5933,6 +5937,10 @@ void __init setup_per_cpu_pageset(void)
 
 __meminit void zone_pcp_init(struct zone *zone)
 {
+	/* This initialization only needs to be done once */
+	if (zone->per_cpu_pageset)
+		return;
+
 	/*
 	 * per cpu subsystem is not up at this point. The following code
 	 * relies on the ability of the linker to provide the
@@ -6982,6 +6990,12 @@ void zone_pcp_enable(struct zone *zone)
 	mutex_unlock(&pcp_batch_high_lock);
 }
 
+/*
+ * The zone has become empty. Its pagesets and zonestats are not freed: nothing
+ * keeps somebody who found the zone populated, such as refresh_cpu_vm_stats()
+ * or drain_all_pages(), from still using them. They are used again when the
+ * zone gets memory again.
+ */
 void zone_pcp_reset(struct zone *zone)
 {
 	int cpu;
@@ -6992,12 +7006,6 @@ void zone_pcp_reset(struct zone *zone)
 			pzstats = per_cpu_ptr(zone->per_cpu_zonestats, cpu);
 			drain_zonestat(zone, pzstats);
 		}
-		free_percpu(zone->per_cpu_pageset);
-		zone->per_cpu_pageset = &boot_pageset;
-		if (zone->per_cpu_zonestats != &boot_zonestats) {
-			free_percpu(zone->per_cpu_zonestats);
-			zone->per_cpu_zonestats = &boot_zonestats;
-		}
 	}
 }
 
author maintainer
#576 lore raw

PATCH 572/816 mm/page_alloc: detect zonelist rebuilds from memory hot-add

In reply to Greg Kroah-Hartman

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

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

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

commit e5db040c3d09c5d85dda70f736d4d1a6714b741e upstream.

The zonelist_update_seq retry was limited to CONFIG_MEMORY_HOTREMOVE, presumably because only hot-remove takes zones out of a zonelist.

However, build_zonerefs_node() rewrites the zonelists in place, so onlining the first block of a zone shifts the entries that follow it in every zonelist containing that zone. This can cause a spurious allocation failure for a __GFP_THISNODE caller.

For a node with only ZONE_NORMAL, onlining its first ZONE_MOVABLE block rewrites the node's ZONELIST_NOFALLBACK list as:

[NORMAL, NULL] -> [MOVABLE, NULL] -> [MOVABLE, NORMAL, NULL]

A concurrent GFP_KERNEL | __GFP_THISNODE allocation can observe the intermediate list, skip ZONE_MOVABLE, and find no eligible zone. With CONFIG_MEMORY_HOTREMOVE=n, check_retry_zonelist() returns 0 and the allocation fails even though the node has free ZONE_NORMAL memory.

Gate the sequence checks on CONFIG_MEMORY_HOTPLUG, which covers every configuration that rebuilds zonelists after boot.

Fixes 3d36424b3b58 ("mm/page_alloc: fix race condition between build_all_zonelists and page allocation")
---
 mm/page_alloc.c |    4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
mm/page_alloc.c +2 -2
@@ -3982,7 +3982,7 @@ static DEFINE_SEQLOCK(zonelist_update_se
 
 static unsigned int zonelist_iter_begin(void)
 {
-	if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE))
+	if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG))
 		return read_seqbegin(&zonelist_update_seq);
 
 	return 0;
@@ -3990,7 +3990,7 @@ static unsigned int zonelist_iter_begin(
 
 static unsigned int check_retry_zonelist(unsigned int seq)
 {
-	if (IS_ENABLED(CONFIG_MEMORY_HOTREMOVE))
+	if (IS_ENABLED(CONFIG_MEMORY_HOTPLUG))
 		return read_seqretry(&zonelist_update_seq, seq);
 
 	return seq;
author maintainer
#577 lore raw

PATCH 573/816 coda: honor the append state of each write

In reply to Greg Kroah-Hartman

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

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

From: Hungyu Lin <[email protected]>

commit 87ea037a9166a5842356ce68e3585fc6e756603b upstream.

coda_open() adds O_APPEND to the container file's f_flags after it has been opened, without updating its cached f_iocb_flags. An O_APPEND write can therefore overwrite existing data instead of appending. For example, writing "Z" to a file containing "abc" produces "Zbc" rather than "abcZ".

Pass RWF_APPEND or RWF_NOAPPEND to vfs_iter_write() according to the incoming IOCB_APPEND state. This also honors changes made with F_SETFL and per-write append overrides instead of relying on the container's open-time flags.

Fixes 164f4064ca81 ("keep iocb_flags() result cached in struct file")
---
 fs/coda/file.c |    3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
fs/coda/file.c +2 -1
@@ -71,6 +71,7 @@ coda_file_write_iter(struct kiocb *iocb,
 	struct file *host_file = cfi->cfi_container;
 	loff_t ki_pos = iocb->ki_pos;
 	size_t count = iov_iter_count(to);
+	rwf_t flags = (iocb->ki_flags & IOCB_APPEND) ? RWF_APPEND : RWF_NOAPPEND;
 	ssize_t ret;
 
 	ret = venus_access_intent(coda_inode->i_sb, coda_i2f(coda_inode),
@@ -80,7 +81,7 @@ coda_file_write_iter(struct kiocb *iocb,
 		goto finish_write;
 
 	inode_lock(coda_inode);
-	ret = vfs_iter_write(cfi->cfi_container, to, &iocb->ki_pos, 0);
+	ret = vfs_iter_write(cfi->cfi_container, to, &iocb->ki_pos, flags);
 	coda_inode->i_size = file_inode(host_file)->i_size;
 	coda_inode->i_blocks = (coda_inode->i_size + 511) >> 9;
 	inode_set_mtime_to_ts(coda_inode, inode_set_ctime_current(coda_inode));
author maintainer
#578 lore raw

PATCH 574/816 net: dst_metadata: fix memcmp overread in skb_metadata_dst_cmp

In reply to Greg Kroah-Hartman

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

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

From: Jean-Paul Sergent <[email protected]>

commit 74a7db839308dd7d1c3f72dd1e3299784df3affb upstream.

Commit 3fcece12bc1b6 ("net: store port/representator id in metadata_dst") dropped the options_len equality check when converting skb_metadata_dst_cmp() to a type switch, so the memcmp length is taken from skb a alone. When skb b carries fewer options than a, the comparison reads past b's allocation.

Hit in practice with Cilium geneve GRO aggregation, comparing an skb carrying 12 bytes of tunnel options against one carrying none:

memcmp: detected buffer overflow: 108 byte read of buffer size 96

  WARNING: CPU: 0 PID: 15 at lib/string_helpers.c:1036 __fortify_report
   __fortify_panic+0x9/0x10
   skb_metadata_dst_cmp+0x11b/0x120
   dev_gro_receive+0x303/0x620
   gro_cell_poll+0x67/0xa0

Restore the check: unequal options_len means different metadata and no aggregation; the memcmp only runs when both sides carry the same options length.

Fixes 3fcece12bc1b6 ("net: store port/representator id in metadata_dst")
Cc Ilya Maximets <[email protected]>
Cc Sasha Levin <[email protected]>
Cc Jakub Kicinski <[email protected]>
Cc "David S. Miller" <[email protected]>
Cc Eric Dumazet <[email protected]>
Cc Paolo Abeni <[email protected]>
Cc Simon Horman <[email protected]>
Cc Sridhar Samudrala <[email protected]>
Cc Kees Cook <[email protected]>
---
 include/net/dst_metadata.h |    2 ++
 1 file changed, 2 insertions(+)
include/net/dst_metadata.h +2 -0
@@ -115,6 +115,8 @@ static inline int skb_metadata_dst_cmp(c
 		return memcmp(&a->u.port_info, &b->u.port_info,
 			      sizeof(a->u.port_info));
 	case METADATA_IP_TUNNEL:
+		if (a->u.tun_info.options_len != b->u.tun_info.options_len)
+			return 1;
 		return memcmp(&a->u.tun_info, &b->u.tun_info,
 			      sizeof(a->u.tun_info) +
 					 a->u.tun_info.options_len);
author maintainer
#579 lore raw

PATCH 575/816 macsec: reject frames that decapsulate into runt Ethernet frames

In reply to Greg Kroah-Hartman

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

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

From: Kyle Zeng <[email protected]>

commit 1d5e2c57e9ffc134e14b3f837c8d7c53b508bd22 upstream.

When an SCI is unknown and the C bit is clear, macsec_handle_frame() removes the SecTAG and the default ICV without checking how much of the frame remains. A short frame can therefore become an skb shorter than ETH_HLEN. eth_type_trans() cannot pull its Ethernet header, and a second stacked MACsec device can copy stale skb headroom into a packet delivered to a packet socket.

The matched-SCI path has a related hole: macsec_validate_skb() accepts a short_length of one, so a frame that passes the existing length check can still become a 13-byte Ethernet frame.

Require enough bytes for the MACsec overhead and a complete Ethernet header before decapsulating an unknown-SCI frame. Apply the same bound in macsec_validate_skb(), using the selected SecY's ICV length, to cover the no-SA, synchronous-decrypt and asynchronous-decrypt delivery paths. Leave other unknown-SCI handling unchanged.

Fixes c09440f7dcb3 ("macsec: introduce IEEE 802.1AE driver")
---
 drivers/net/macsec.c |   15 ++++++++++-----
 1 file changed, 10 insertions(+), 5 deletions(-)
drivers/net/macsec.c +10 -5
@@ -402,8 +402,10 @@ static bool macsec_validate_skb(struct s
 	int len = skb->len - 2 * ETH_ALEN;
 	int extra_len = macsec_extra_len(!!(h->tci_an & MACSEC_TCI_SC)) + icv_len;
 
-	/* a) It comprises at least 17 octets */
-	if (skb->len <= 16)
+	/* a) It comprises at least 17 octets. The SecTAG and ICV must
+	 * also leave a complete Ethernet header.
+	 */
+	if (skb->len < ETH_HLEN + extra_len)
 		return false;
 
 	/* b) MACsec EtherType: already checked */
@@ -1325,9 +1327,12 @@ drop_direct:
 nosci:
 	/* 10.6.1 if the SC is not found */
 	cbit = !!(hdr->tci_an & MACSEC_TCI_C);
-	if (!cbit)
-		macsec_finalize_skb(skb, MACSEC_DEFAULT_ICV_LEN,
-				    macsec_extra_len(macsec_skb_cb(skb)->has_sci));
+	if (!cbit) {
+		len = macsec_extra_len(macsec_skb_cb(skb)->has_sci);
+		if (skb->len < ETH_HLEN + len + MACSEC_DEFAULT_ICV_LEN)
+			goto drop_nosc;
+		macsec_finalize_skb(skb, MACSEC_DEFAULT_ICV_LEN, len);
+	}
 
 	list_for_each_entry_rcu(macsec, &rxd->secys, secys) {
 		struct sk_buff *nskb;
author maintainer
#580 lore raw

PATCH 576/816 mctp: accept MSG_CMSG_COMPAT in recvmsg

In reply to Greg Kroah-Hartman

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

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

From: Davidlohr Bueso <[email protected]>

commit 350e1d0d3b386fcc0cff2d37aa920fab4800bf72 upstream.

32-bit userspace running on a 64-bit kernel is unable to receive MCTP messages on an AF_MCTP socket, even though sending succeeds. There is nothing for MCTP to do with it beyond not rejecting it, as af_packet, af_key and can/isotp already do, for example.

---
 net/mctp/af_mctp.c |    2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/mctp/af_mctp.c +1 -1
@@ -212,7 +212,7 @@ static int mctp_recvmsg(struct socket *s
 	u8 type;
 	int rc;
 
-	if (flags & ~(MSG_DONTWAIT | MSG_TRUNC | MSG_PEEK))
+	if (flags & ~(MSG_DONTWAIT | MSG_TRUNC | MSG_PEEK | MSG_CMSG_COMPAT))
 		return -EOPNOTSUPP;
 
 	skb = skb_recv_datagram(sk, flags, &rc);
author maintainer
#581 lore raw

PATCH 577/816 net/mlx5e: SHAMPO, Disable end padding when relaxed ordering is supported

In reply to Greg Kroah-Hartman

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

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

From: Jiabin Deng <[email protected]>

commit 68c183619f24982a635930697bf8e148f2d78f71 upstream.

When SHAMPO and relaxed ordering writes are enabled, aligned RQ end padding can corrupt received TCP data. Due to reordering, alignment padding written at the end of one packet can overwrite data from the next packet.

The current RQ end padding selection avoids alignment padding for LRO, but not for SHAMPO. Extend the condition to SHAMPO to prevent this corruption.

The issue was observed in a two-host test using a BlueField-3 NIC and an NVIDIA H20 GPU. In the original test with MTU 1500, 354 of 400 transfers contained corrupted data before the fix. After applying this change, all 400 transfers across eight message sizes from 32 KiB to 4 MiB, with 50 transfers per size, completed successfully, with no incorrect bytes or corrupted intervals.

---
 drivers/net/ethernet/mellanox/mlx5/core/en/params.c |    5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/net/ethernet/mellanox/mlx5/core/en/params.c +3 -2
@@ -887,10 +887,11 @@ static void mlx5e_build_rx_cq_param(stru
 
 static u8 rq_end_pad_mode(struct mlx5_core_dev *mdev, struct mlx5e_params *params)
 {
-	bool lro_en = params->packet_merge.type == MLX5E_PACKET_MERGE_LRO;
+	bool no_pad = params->packet_merge.type == MLX5E_PACKET_MERGE_LRO ||
+		      params->packet_merge.type == MLX5E_PACKET_MERGE_SHAMPO;
 	bool ro = MLX5_CAP_GEN(mdev, relaxed_ordering_write);
 
-	return ro && lro_en ?
+	return ro && no_pad ?
 		MLX5_WQ_END_PAD_MODE_NONE : MLX5_WQ_END_PAD_MODE_ALIGN;
 }
 
author maintainer
#582 lore raw

PATCH 578/816 net/rds: Do not unpin a page after a failed atomic pin

In reply to Greg Kroah-Hartman

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

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

From: Kyle Zeng <[email protected]>

commit 8d5ce4751fad9499ea408163af7f410f18a85782 upstream.

rds_cmsg_atomic() assumes that a non-NULL output from rds_pin_pages() represents a pin that it owns. However, pin_user_pages_fast() can roll back a fast-GUP pin after racing fork() and then fail in the slow path, for example after a concurrent mprotect(PROT_NONE). The output slot can still contain the already-unpinned page.

The common error path calls unpin_user_page() on that stale pointer. This can consume another subsystem's pin and allow the page to be freed while it is still in use. A local unprivileged reproducer triggers a KASAN use-after-free write through an io_uring registered buffer.

Clear page when rds_pin_pages() does not return one. The error path continues to release the page on errors after a successful pin, and successful requests retain their existing ownership and behavior. All four RDS atomic ancillary operations share this path.

The issue was found by an LLM.

Fixes 15133f6e67d8 ("RDS: Implement atomic operations")
---
 net/rds/rdma.c |    5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
net/rds/rdma.c +4 -1
@@ -960,8 +960,11 @@ int rds_cmsg_atomic(struct rds_sock *rs,
 	}
 
 	ret = rds_pin_pages(args->local_addr, 1, &page, 1);
-	if (ret != 1)
+	if (ret != 1) {
+		/* A failed pin can leave a stale page pointer. */
+		page = NULL;
 		goto err;
+	}
 	ret = 0;
 
 	sg_set_page(rm->atomic.op_sg, page, 8, offset_in_page(args->local_addr));
author maintainer
#583 lore raw

PATCH 579/816 net/smc: fix lgr/lnk lifetime vs diag reader race

In reply to Greg Kroah-Hartman

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

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

From: Mahanta Jambigi <[email protected]>

commit d7900fa51642fbc2a5a03354238e71050a7d391d upstream.

The diag dump walks the socket hash table under a read_lock and dereferences conn->lgr and conn->lnk. Several paths expose a window where a hashed socket has freed or partially freed conn/lgr/lnk state.

First, smc_conn_abort() calls smc_conn_free() during early handshake aborts while the socket is still hashed in SMC_INIT, synchronously freeing the lgr on the smc_lgr_cleanup_early() path without holding the hash write_lock. A concurrent diag reader can load a non-NULL conn->lgr and dereference it after the kfree. Skip the connection, link group and DMB attributes in __smc_diag_dump() for sockets in SMC_INIT or SMC_CLOSED or fallen back to TCP, and take diag_mode from an is_smcd flag cached at connection creation.

The state filter alone does not close the race. A connection aborted by a failed handshake can keep its alert token, because smc_conn_free() skips the unregister when smc_lgr_terminate_sched() has emptied lgr->list; close_work may also have been queued before the abort, as the CDC receive path is not excluded by the handshake's socket lock. smc_close_passive_work() would then move the hashed socket from SMC_INIT to SMC_APPCLOSEWAIT1 or SMC_PROCESSABORT, states the filter does not cover, and later run a passive-closing sock_put() that smc_connect_decline_fallback() dropped already. Return early from smc_close_passive_work() when the connection was freed; the check holds the socket lock that every smc_conn_free() caller holds as well, so a hashed socket with a freed connection stays in SMC_INIT or SMC_CLOSED until release.

This changes the sock_diag output for such sockets: the connection, link group and DMB attributes are omitted, which smcss does not read for sockets in these states, while SMC_DIAG_FALLBACK is still reported and an SMC-D socket in SMC_INIT or SMC_CLOSED still reports SMC_DIAG_MODE_SMCD from the cached flag. A fallback socket is a plain TCP socket with no SMC connection state to report; the stale conn fields left behind by smc_conn_abort() must not be read.

Second, in smc_conn_kill() on SMC-D with dmb_nocopy, smcd_buf_detach() NULLs and frees conn->sndbuf_desc while the socket is still hashed. A concurrent diag reader entering the CONNINFO block can dereference the freed descriptor. Unhash the socket right before smcd_buf_detach(). As a result, killed ACTIVE and APPCLOSEWAIT sockets that are still open are no longer visible to smcss on loopback-ism devices.

Third, in the terminal teardown branches of smc_close_active_abort() (PEERCLOSEWAIT and PROCESSABORT groups) and in smc_close_passive_work(), smc_conn_free() drops lgr and lnk references while the socket is still hashed. Unhash immediately before each smc_conn_free() call at those sites. Sockets killed in those close states are therefore unhashed, and their inuse accounting dropped, before close(), even if the fd is still open.

Fourth, use smp_load_acquire() / smp_store_release() on sk_state to order these checks on weakly ordered CPUs. A reader that observes SMC_ACTIVE is guaranteed to see the connection setup that preceded the store; a reader that observes SMC_CLOSED from smc_listen_out_err() skips the connection fields in any case, so that particular store is hardening kept for uniformity, not a required ordering.

Additionally, in __smc_diag_dump(), use the cached link->ibname instead of link->smcibdev->ibdev->name, avoiding a NULL pointer dereference or use-after-free of the IB device when __smcr_link_clear() zeroes the link during concurrent SMC-R link failover. The link data is still read without conns_lock or send_lock, so a dump racing a failover may transiently report zeroed or mixed link fields; this does not affect memory safety and the next dump reports the new link. Like the SMC netlink link dump and the tracepoints, the name is the one cached at link creation time.

Fixes f16a7dd5cf27 ("smc: netlink interface for SMC sockets")
Fixes 2a0674fffb6b ("net/smc: improve abnormal termination of link groups")
Fixes 46c28dbd4c23 ("net/smc: no socket state changes in tasklet context")
Fixes 9dbe086c69b8 ("net/smc: fix invalid link access in dumping SMC-R connections")
Fixes ae2be35cbed2 ("net/smc: {at|de}tach sndbuf to peer DMB if supported")
---
 net/smc/af_smc.c    |   10 +++++-----
 net/smc/smc.h       |    1 +
 net/smc/smc_close.c |   14 ++++++++++++++
 net/smc/smc_core.c  |    8 +++++++-
 net/smc/smc_diag.c  |   12 ++++++++----
 5 files changed, 35 insertions(+), 10 deletions(-)
net/smc/af_smc.c +5 -5
@@ -977,7 +977,7 @@ static int smc_connect_fallback(struct s
 	smc_copy_sock_settings_to_clc(smc);
 	smc->connect_nonblock = 0;
 	if (smc->sk.sk_state == SMC_INIT)
-		smc->sk.sk_state = SMC_ACTIVE;
+		smp_store_release(&smc->sk.sk_state, SMC_ACTIVE);
 	return 0;
 }
 
@@ -1381,7 +1381,7 @@ static int smc_connect_rdma(struct smc_s
 	smc_copy_sock_settings_to_clc(smc);
 	smc->connect_nonblock = 0;
 	if (smc->sk.sk_state == SMC_INIT)
-		smc->sk.sk_state = SMC_ACTIVE;
+		smp_store_release(&smc->sk.sk_state, SMC_ACTIVE);
 
 	return 0;
 connect_abort:
@@ -1484,7 +1484,7 @@ static int smc_connect_ism(struct smc_so
 	smc_copy_sock_settings_to_clc(smc);
 	smc->connect_nonblock = 0;
 	if (smc->sk.sk_state == SMC_INIT)
-		smc->sk.sk_state = SMC_ACTIVE;
+		smp_store_release(&smc->sk.sk_state, SMC_ACTIVE);
 
 	return 0;
 connect_abort:
@@ -1955,7 +1955,7 @@ static void smc_listen_out_connected(str
 	struct sock *newsmcsk = &new_smc->sk;
 
 	if (newsmcsk->sk_state == SMC_INIT)
-		newsmcsk->sk_state = SMC_ACTIVE;
+		smp_store_release(&newsmcsk->sk_state, SMC_ACTIVE);
 
 	smc_listen_out(new_smc);
 }
@@ -1969,7 +1969,7 @@ static void smc_listen_out_err(struct sm
 	this_cpu_inc(net->smc.smc_stats->srv_hshake_err_cnt);
 	if (newsmcsk->sk_state == SMC_INIT)
 		sock_put(&new_smc->sk); /* passive closing */
-	newsmcsk->sk_state = SMC_CLOSED;
+	smp_store_release(&newsmcsk->sk_state, SMC_CLOSED);
 
 	smc_listen_out(new_smc);
 }
net/smc/smc.h +1 -0
@@ -196,6 +196,7 @@ struct smc_connection {
 	struct rb_node		alert_node;
 	struct smc_link_group	*lgr;		/* link group of connection */
 	struct smc_link		*lnk;		/* assigned SMC-R link */
+	bool			is_smcd;	/* SMC-R or SMC-D connection */
 	u32			alert_token_local; /* unique conn. id */
 	u8			peer_rmbe_idx;	/* from tcp handshake */
 	int			peer_rmbe_size;	/* size of peer rx buffer */
net/smc/smc_close.c +14 -0
@@ -154,6 +154,7 @@ void smc_close_active_abort(struct smc_s
 		if (sk->sk_state != SMC_PEERABORTWAIT)
 			break;
 		sk->sk_state = SMC_CLOSED;
+		sk->sk_prot->unhash(sk);
 		smc_conn_free(&smc->conn);
 		release_clcsock = true;
 		sock_put(sk); /* passive closing */
@@ -165,6 +166,7 @@ void smc_close_active_abort(struct smc_s
 		if (sk->sk_state != SMC_PEERABORTWAIT)
 			break;
 		sk->sk_state = SMC_CLOSED;
+		sk->sk_prot->unhash(sk);
 		smc_conn_free(&smc->conn);
 		release_clcsock = true;
 		break;
@@ -367,6 +369,17 @@ static void smc_close_passive_work(struc
 	lock_sock(sk);
 	old_state = sk->sk_state;
 
+	if (conn->freed) {
+		/* conn->freed is set under the socket lock, which is
+		 * held here as well, so this cannot race with the free; the
+		 * state machine and its postponed sock_put() are not owed
+		 * anymore
+		 */
+		release_sock(sk);
+		sock_put(sk); /* sock_hold done by schedulers of close_work */
+		return;
+	}
+
 	rxflags = &conn->local_rx_ctrl.conn_state_flags;
 	if (rxflags->peer_conn_abort) {
 		/* peer has not received all data */
@@ -433,6 +446,7 @@ wakeup:
 		sk->sk_state_change(sk);
 		if ((sk->sk_state == SMC_CLOSED) &&
 		    (sock_flag(sk, SOCK_DEAD) || !sk->sk_socket)) {
+			sk->sk_prot->unhash(sk);
 			smc_conn_free(conn);
 			if (smc->clcsock)
 				release_clcsock = true;
net/smc/smc_core.c +7 -1
@@ -1511,8 +1511,10 @@ static void smc_conn_kill(struct smc_con
 			tasklet_kill(&conn->rx_tsklet);
 		else
 			tasklet_unlock_wait(&conn->rx_tsklet);
-		if (smc_ism_support_dmb_nocopy(conn->lgr->smcd))
+		if (smc_ism_support_dmb_nocopy(conn->lgr->smcd)) {
+			smc->sk.sk_prot->unhash(&smc->sk);
 			smcd_buf_detach(conn);
+		}
 	} else {
 		smc_cdc_wait_pend_tx_wr(conn);
 	}
@@ -2032,6 +2034,10 @@ create:
 			goto out;
 		}
 	}
+	/* cache the connection type: smc_diag reads it after
+	 * smc_conn_free() dropped the link group reference
+	 */
+	conn->is_smcd = conn->lgr->is_smcd;
 	smc_lgr_hold(conn->lgr); /* lgr_put in smc_conn_free() */
 	if (!conn->lgr->is_smcd)
 		smcr_link_hold(conn->lnk); /* link_put in smc_conn_free() */
net/smc/smc_diag.c +8 -4
@@ -87,10 +87,10 @@ static int __smc_diag_dump(struct sock *
 
 	r = nlmsg_data(nlh);
 	smc_diag_msg_common_fill(r, sk);
-	r->diag_state = sk->sk_state;
+	r->diag_state = smp_load_acquire(&sk->sk_state);
 	if (smc->use_fallback)
 		r->diag_mode = SMC_DIAG_MODE_FALLBACK_TCP;
-	else if (smc_conn_lgr_valid(&smc->conn) && smc->conn.lgr->is_smcd)
+	else if (smc->conn.is_smcd)
 		r->diag_mode = SMC_DIAG_MODE_SMCD;
 	else
 		r->diag_mode = SMC_DIAG_MODE_SMCR;
@@ -103,6 +103,10 @@ static int __smc_diag_dump(struct sock *
 	if (nla_put(skb, SMC_DIAG_FALLBACK, sizeof(fallback), &fallback) < 0)
 		goto errout;
 
+	if (r->diag_state == SMC_INIT || r->diag_state == SMC_CLOSED ||
+	    smc->use_fallback)
+		goto out;
+
 	if ((req->diag_ext & (1 << (SMC_DIAG_CONNINFO - 1))) &&
 	    smc->conn.alert_token_local) {
 		struct smc_connection *conn = &smc->conn;
@@ -154,8 +158,7 @@ static int __smc_diag_dump(struct sock *
 			.lnk[0].link_id = link->link_id,
 		};
 
-		memcpy(linfo.lnk[0].ibname, link->smcibdev->ibdev->name,
-		       sizeof(link->smcibdev->ibdev->name));
+		memcpy(linfo.lnk[0].ibname, link->ibname, sizeof(link->ibname));
 		smc_gid_be16_convert(linfo.lnk[0].gid, link->gid);
 		smc_gid_be16_convert(linfo.lnk[0].peer_gid, link->peer_gid);
 
@@ -185,6 +188,7 @@ static int __smc_diag_dump(struct sock *
 			goto errout;
 	}
 
+out:
 	nlmsg_end(skb, nlh);
 	return 0;
 
author maintainer
#584 lore raw

PATCH 580/816 net: bridge: use one headroom snapshot for ND replies

In reply to Greg Kroah-Hartman

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

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

From: Jun Yang <[email protected]>

commit e573df093ef849bb7c763aed591cb6556b110671 upstream.

br_nd_send() calls LL_RESERVED_SPACE(dev) once to size the reply skb and again to reserve its headroom. When a port requiring more headroom is added to the bridge, br_add_if() can increase dev->needed_headroom between the two calls. The reserved headroom can then exceed the space accounted for by alloc_skb().

Take one headroom snapshot and use it for both the allocation size and skb_reserve().

---
 net/bridge/br_arp_nd_proxy.c |    6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)
net/bridge/br_arp_nd_proxy.c +4 -2
@@ -259,6 +259,7 @@ static void br_nd_send(struct net_bridge
 	struct sk_buff *reply;
 	struct ipv6hdr *pip6;
 	int na_olen = 8; /* opt hdr + ETH_ALEN for target */
+	int headroom;
 	int ns_olen;
 	int i, len;
 	u8 *daddr;
@@ -268,7 +269,8 @@ static void br_nd_send(struct net_bridge
 	if (!dev || skb_linearize(request))
 		return;
 
-	len = LL_RESERVED_SPACE(dev) + sizeof(struct ipv6hdr) +
+	headroom = LL_RESERVED_SPACE(dev);
+	len = headroom + sizeof(struct ipv6hdr) +
 		sizeof(*na) + na_olen + dev->needed_tailroom;
 
 	reply = alloc_skb(len, GFP_ATOMIC);
@@ -277,7 +279,7 @@ static void br_nd_send(struct net_bridge
 
 	reply->protocol = htons(ETH_P_IPV6);
 	reply->dev = dev;
-	skb_reserve(reply, LL_RESERVED_SPACE(dev));
+	skb_reserve(reply, headroom);
 	skb_push(reply, sizeof(struct ethhdr));
 	skb_set_mac_header(reply, 0);
 
author maintainer
#585 lore raw

PATCH 581/816 net: dsa: microchip: initialize the IRQ access mutex

In reply to Greg Kroah-Hartman

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

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

From: Tapio Reijonen <[email protected]>

commit ba1dc196502f3435f4ae53ed6745caacf066f83e upstream.

ksz_switch_register() initializes dev_mutex, regmap_mutex, alu_mutex and vlan_mutex but not lock_irq, which the IRQ chip takes in its bus lock callbacks on every mask and unmask of a switch interrupt, and the PTP code takes the same way. The zeroed mutex happens to work on the uncontended fast path, but with CONFIG_DEBUG_MUTEXES the first lock, from the IRQ domain mapping during probe, warns:

DEBUG_LOCKS_WARN_ON(lock->magic != lock)

  WARNING: kernel/locking/mutex.c:625 at __mutex_lock
  ...
  ksz_irq_domain_map
  irq_domain_associate_locked
  irq_create_mapping_affinity
  ksz_irq_common_setup
  ksz9477_setup
  dsa_register_switch
  ksz_spi_probe

and turns lock debugging off for the rest of the boot.

Initialize it with the other mutexes.

Triggered at every boot of a KSZ9897S over SPI on an i.MX6 SoloX board with CONFIG_DEBUG_MUTEXES, on v7.4-rc1 and earlier. With this patch the same board boots with lock debugging enabled and it stays enabled (debug_locks 1) through two hours of unrelated stress tests.

Fixes c9cd961c0d43 ("net: dsa: microchip: lan937x: add interrupt support for port phy link")
---
 drivers/net/dsa/microchip/ksz_common.c |    1 +
 1 file changed, 1 insertion(+)
drivers/net/dsa/microchip/ksz_common.c +1 -0
@@ -4806,6 +4806,7 @@ int ksz_switch_register(struct ksz_devic
 	mutex_init(&dev->regmap_mutex);
 	mutex_init(&dev->alu_mutex);
 	mutex_init(&dev->vlan_mutex);
+	mutex_init(&dev->lock_irq);
 
 	ret = ksz_switch_detect(dev);
 	if (ret)
author maintainer
#586 lore raw

PATCH 582/816 net: leave O_NONBLOCK to the sendmsg and recvmsg syscalls

In reply to Greg Kroah-Hartman

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

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

From: Jens Axboe <[email protected]>

commit bdc350ddbcbe4788158019d4d8e8e9345cb16235 upstream.

____sys_sendmsg() and ____sys_recvmsg() turn O_NONBLOCK on the socket into MSG_DONTWAIT. That is right for the system calls, but io_uring uses __sys_sendmsg_sock() and __sys_recvmsg_sock() for a blocking attempt from io-wq as well, after the non-blocking attempts with MSG_DONTWAIT have failed. On an O_NONBLOCK socket that attempt can't block either and the request completes with -EAGAIN, unlike IORING_OP_SEND and RECV, which call sock_sendmsg() and sock_recvmsg() directly and don't look at O_NONBLOCK at all.

Move the O_NONBLOCK handling to ___sys_sendmsg() and ___sys_recvmsg(), which the sendmsg, sendmmsg, recvmsg and recvmmsg system calls go through. The io_uring helpers then pass the flags the caller asked for.

Fixes 0fa03c624d8f ("io_uring: add support for sendmsg()")
Fixes aa1fa28fc73e ("io_uring: add support for recvmsg()")
---
 net/socket.c |   11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)
net/socket.c +6 -5
@@ -2611,8 +2611,6 @@ static int ____sys_sendmsg(struct socket
 	flags &= ~MSG_INTERNAL_SENDMSG_FLAGS;
 	msg_sys->msg_flags = flags;
 
-	if (sock->file->f_flags & O_NONBLOCK)
-		msg_sys->msg_flags |= MSG_DONTWAIT;
 	/*
 	 * If this is sendmmsg() and current destination address is same as
 	 * previously succeeded address, omit asking LSM's decision.
@@ -2676,6 +2674,9 @@ static int ___sys_sendmsg(struct socket
 
 	msg_sys->msg_name = &address;
 
+	if (sock->file->f_flags & O_NONBLOCK)
+		flags |= MSG_DONTWAIT;
+
 	err = sendmsg_copy_msghdr(msg_sys, msg, flags, &iov);
 	if (err < 0)
 		return err;
@@ -2840,9 +2841,6 @@ static int ____sys_recvmsg(struct socket
 	/* We assume all kernel code knows the size of sockaddr_storage */
 	msg_sys->msg_namelen = 0;
 
-	if (sock->file->f_flags & O_NONBLOCK)
-		flags |= MSG_DONTWAIT;
-
 	if (unlikely(nosec))
 		err = sock_recvmsg_nosec(sock, msg_sys, flags);
 	else
@@ -2884,6 +2882,9 @@ static int ___sys_recvmsg(struct socket
 	struct sockaddr __user *uaddr;
 	ssize_t err;
 
+	if (sock->file->f_flags & O_NONBLOCK)
+		flags |= MSG_DONTWAIT;
+
 	err = recvmsg_copy_msghdr(msg_sys, msg, flags, &uaddr, &iov);
 	if (err < 0)
 		return err;
author maintainer
#587 lore raw

PATCH 583/816 net: mana: report RX checksum offload for IPv6

In reply to Greg Kroah-Hartman

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

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

From: Hamza Mahfooz <[email protected]>

commit bbcd02741c4cfbf9e1c59b1906f21ef772bd15eb upstream.

The hardware validates TCP and UDP checksums for both IPv4 and IPv6 and reports the result in rx_tcp_csum_succeed and rx_udp_csum_succeed. However, mana_rx_skb() also requires rx_iphdr_csum_succeed before it sets CHECKSUM_UNNECESSARY. That bit is only set for IPv4 (since IPv6 has no header checksum), so IPv6 TCP and UDP traffic is always checksummed again in software.

So, only look at the L4 result. For IPv4 this makes no material difference since CHECKSUM_UNNECESSARY only covers the L4 checksum, and ip_rcv_core() always verifies the IPv4 header checksum in software.

Between two Azure Standard_E16s_v6 VMs (VF enabled), IPv6 TCP and UDP packets (including VXLAN over IPv6), now arrive with CHECKSUM_UNNECESSARY instead of CHECKSUM_NONE, so GRO no longer checksums them in software. Calls to __skb_gro_checksum_complete() on the receiver during an 8 second iperf3 run:

before after

  TCP/IPv4, 12.2 Gbps              23       28
  TCP/IPv6, 12.1 Gbps         8728419       25
  UDP/IPv6, 1.5 Gbps          1071380       20
  TCP/VXLAN/IPv6, 10.9 Gbps   7934373       18
Fixes ca9c54d2d6a5 ("net: mana: Add a driver for Microsoft Azure Network Adapter (MANA)")
---
 drivers/net/ethernet/microsoft/mana/mana_en.c |    7 +++----
 1 file changed, 3 insertions(+), 4 deletions(-)
drivers/net/ethernet/microsoft/mana/mana_en.c +3 -4
@@ -1560,10 +1560,9 @@ static void mana_rx_skb(void *buf_va, bo
 	skb_checksum_none_assert(skb);
 	skb_record_rx_queue(skb, rxq_idx);
 
-	if ((ndev->features & NETIF_F_RXCSUM) && cqe->rx_iphdr_csum_succeed) {
-		if (cqe->rx_tcp_csum_succeed || cqe->rx_udp_csum_succeed)
-			skb->ip_summed = CHECKSUM_UNNECESSARY;
-	}
+	if ((ndev->features & NETIF_F_RXCSUM) &&
+	    (cqe->rx_tcp_csum_succeed || cqe->rx_udp_csum_succeed))
+		skb->ip_summed = CHECKSUM_UNNECESSARY;
 
 	if (cqe->rx_hashtype != 0 && (ndev->features & NETIF_F_RXHASH)) {
 		hash_value = cqe->ppi[0].pkt_hash;