Skip to contentSkip to conversation

6.18.66-rc1 review

PATCH In review Greg Kroah-Hartman 3 participants 995 messages Nov 25 Page 2 of 9

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

PATCH 85/990 drm/imagination: Align rogue_fwif_hwrtdata to 64 bytes

In reply to Greg Kroah-Hartman

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

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

From: Michal Wilczynski <[email protected]>

[ Upstream commit 6c6200ffebf9766fd5d9293002298ea371c261c1 ]

Sparse (W=1) builds fail because SIZE_CHECK(struct rogue_fwif_hwrtdata, 384) expects 384 bytes, but the compiler generates a 336-byte structure.

This is due to an alignment conflict: the inner member cleanup_state requires 64-byte alignment, but the outer struct is explicitly marked __aligned(8).

While a non-sparse build implicitly pads the size to a multiple of 64, a sparse build strictly respects the 8-byte outer alignment, resulting in a size mismatch.

Fix this by aligning the entire structure to 64 bytes, which resolves the contradiction and forces the correct 384 byte size on all builds.

---
 drivers/gpu/drm/imagination/pvr_rogue_fwif.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/imagination/pvr_rogue_fwif.h +1 -1
index 5d590c4c25663..2f8daa93c9e68 100644
@@ -2174,7 +2174,7 @@ struct rogue_fwif_hwrtdata {
 	bool geom_caches_need_zeroing __aligned(4);
 
 	struct rogue_fwif_cleanup_ctl cleanup_state __aligned(64);
-} __aligned(8);
+} __aligned(64);
 
 /*
  ******************************************************************************
Signature · 1 line
2.53.0
author maintainer
#86 lore raw

PATCH 86/990 gpio: omap: Propagate runtime PM failures in probe and request

In reply to Greg Kroah-Hartman

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

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

From: Avi Weiss <[email protected]>

[ Upstream commit 05be1a99d6d68b24cbe24a191e1af67c70193ac3 ]

pm_runtime_get_sync() can fail when the OMAP PM domain cannot resume a GPIO controller, but omap_gpio_probe() and omap_gpio_request() ignore its return value.

Consequently, probe can register a GPIO controller despite a failed resume, while a GPIO request can report success and modify GPIO state even though runtime-PM acquisition failed.

Use pm_runtime_resume_and_get() in both paths and propagate resume errors. On probe failure, disable runtime PM and unprepare the debounce clock when applicable.

Reproduced both failures on QEMU N800 by injecting -EIO from the OMAP PM-domain resume callback. The original driver continues probe and accepts the GPIO request - while the patched driver rejects both operations with -EIO. Normal GPIO controller registration continues to work without fault injection.

Fixes 77640aabd755 ("OMAP: GPIO: Implement GPIO as a platform device")
Fixes 55b93c32520d ("gpio/omap: use pm-runtime framework")
---
 drivers/gpio/gpio-omap.c | 13 +++++++++++--
 1 file changed, 11 insertions(+), 2 deletions(-)
drivers/gpio/gpio-omap.c +11 -2
index 8693544304fa8..2ebef18c37abe 100644
@@ -814,8 +814,11 @@ static int omap_gpio_request(struct gpio_chip *chip, unsigned offset)
 {
 	struct gpio_bank *bank = gpiochip_get_data(chip);
 	unsigned long flags;
+	int ret;
 
-	pm_runtime_get_sync(chip->parent);
+	ret = pm_runtime_resume_and_get(chip->parent);
+	if (ret < 0)
+		return ret;
 
 	raw_spin_lock_irqsave(&bank->lock, flags);
 	omap_enable_gpio_module(bank, offset);
@@ -1469,7 +1472,13 @@ static int omap_gpio_probe(struct platform_device *pdev)
 	platform_set_drvdata(pdev, bank);
 
 	pm_runtime_enable(dev);
-	pm_runtime_get_sync(dev);
+	ret = pm_runtime_resume_and_get(dev);
+	if (ret < 0) {
+		pm_runtime_disable(dev);
+		if (bank->dbck_flag)
+			clk_unprepare(bank->dbck);
+		return ret;
+	}
 
 	if (bank->is_mpuio)
 		omap_mpuio_init(bank);
Signature · 1 line
2.53.0
author maintainer
#87 lore raw

PATCH 87/990 bpf: Fix jited line info off by the CFI preamble

In reply to Greg Kroah-Hartman

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

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

From: Jose Fernandez (Anthropic) <[email protected]>

[ Upstream commit 3e4279dc5144a5afcda101df23792b13e94c3859 ]

With CONFIG_CFI=y, every jited line info entry after a function's first is cfi_get_offset() bytes too high on x86-64, riscv64 and arm64, so tools that use it show the wrong source line.

The JITs count the insn_to_jit_off[] offsets from the start of the image. Since the CFI commits below, prog->bpf_func starts cfi_get_offset() bytes into the image, and bpf_prog_fill_jited_linfo() adds the offsets to prog->bpf_func. s390 corrects its offsets before the call, the other three JITs do not.

Subtract cfi_get_offset() once in bpf_prog_fill_jited_linfo() and drop the s390 correction. jited_linfo[0] stays prog->bpf_func, the function's ksym address. Without CONFIG_CFI, cfi_get_offset() is 0 and nothing changes.

Fixes 4f9087f16651 ("x86/cfi,bpf: Fix BPF JIT call")
Fixes e63985ecd226 ("bpf, riscv64/cfi: Support kCFI + BPF on riscv64")
Fixes 710618c760c0 ("arm64/cfi,bpf: Support kCFI + BPF on arm64")
---
 kernel/bpf/core.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
kernel/bpf/core.c +5 -3
index 346588a32a854..bbd0f1ebd2d3c 100644
@@ -206,7 +206,9 @@ void bpf_prog_jit_attempt_done(struct bpf_prog *prog)
  * here is relative to the prog itself instead of the main prog.
  * This array has one entry for each xlated bpf insn.
  *
- * jited_off is the byte off to the end of the jited insn.
+ * jited_off is the byte off to the end of the jited insn, counted from
+ * the start of the jited image, which is cfi_get_offset() bytes before
+ * prog->bpf_func.
  *
  * Hence, with
  * insn_start:
@@ -220,7 +222,7 @@ void bpf_prog_jit_attempt_done(struct bpf_prog *prog)
  *
  * For i > linfo_idx,
  *
- * jited_linfo[i] = prog->bpf_func +
+ * jited_linfo[i] = prog->bpf_func - cfi_get_offset() +
  *	insn_to_jit_off[linfo[i].insn_off - insn_start - 1]
  */
 void bpf_prog_fill_jited_linfo(struct bpf_prog *prog,
@@ -248,7 +250,7 @@ void bpf_prog_fill_jited_linfo(struct bpf_prog *prog,
 		/* The verifier ensures that linfo[i].insn_off is
 		 * strictly increasing
 		 */
-		jited_linfo[i] = prog->bpf_func +
+		jited_linfo[i] = prog->bpf_func - cfi_get_offset() +
 			insn_to_jit_off[linfo[i].insn_off - insn_start - 1];
 }
 
Signature · 1 line
2.53.0
author maintainer
#88 lore raw

PATCH 88/990 btrfs: verity: propagate orphan insertion errors when enabling verity

In reply to Greg Kroah-Hartman

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

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

From: guolingxing <[email protected]>

[ Upstream commit 45a686dff6b91c3667cd8188d3a02c69f62f4d00 ]

btrfs_begin_enable_verity() ignores the return value of btrfs_orphan_add() and unconditionally returns 0. If orphan insertion fails, btrfs_orphan_add() aborts the transaction, but the generic fs-verity code still proceeds with Merkle tree construction because the begin_enable_verity callback reported success.

Return the error so that fs-verity stops immediately instead of continuing after the initialization failure.

The transaction is already aborted by btrfs_orphan_add() and the handle is released by btrfs_end_transaction(), so no additional cleanup is needed.

Fixes 705242538ff3 ("btrfs: verity metadata orphan items")
---
 fs/btrfs/verity.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/btrfs/verity.c +1 -1
index bb2d2fc47ee91..0a8df39e82e49 100644
@@ -609,7 +609,7 @@ static int btrfs_begin_enable_verity(struct file *filp)
 		set_bit(BTRFS_INODE_VERITY_IN_PROGRESS, &inode->runtime_flags);
 	btrfs_end_transaction(trans);
 
-	return 0;
+	return ret;
 }
 
 /*
Signature · 1 line
2.53.0
author maintainer
#90 lore raw

PATCH 89/990 btrfs: fix fiemap merging compressed extents

In reply to Greg Kroah-Hartman

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

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

From: Filipe Manana <[email protected]>

[ Upstream commit 980fbbd041ac2538fdbe7cfda4253dfc28fdcad1 ]

Compressed extents are never supposed to be merged by the fiemap code and reported as a single extent, as each extent's content comes from a different compression stream and has its own header and context.

We currently rely on checking the logical and physical address adjacency to prevent merging compressed extents but that is broken. Consider the following reproducer which explains why the merging happens:

  $ cat test.sh
  #!/bin/bash

DEV=/dev/sdi
MNT=/mnt/sdi

mkfs.btrfs -s 4K -f $DEV
mount -o compress $DEV $MNT

# Do a write that compresses to a single 4K extent and represents the

  # maximum compressed chunk size (128K).
  xfs_io -f -c "pwrite 0 128K" $MNT/foo

# Sync to flush delalloc and allocate the 4K extent. sync -f $MNT

# Now allocate a 124K extent in some other file, which will be adjacent # (to the right) of the 4K extent previously allocated. xfs_io -f -c "falloc 0 124K" $MNT/filler

# Do another write to the main file at its current EOF that is

  # compressible and fits in a 4K extent.
  xfs_io -c "pwrite 128K 128K" $MNT/foo
  # Sync to flush delalloc and allocate the 4K extent.
  sync -f $MNT

# Run fiemap which should report 2 encoded extents, each with a

  # logical size of 128K.
  xfs_io -c "fiemap -v" $MNT/foo

umount $MNT

Running this, fiemap will report a single extent:

  $ ./test.sh
  (...)
  /mnt/sdi/foo:
   EXT: FILE-OFFSET      BLOCK-RANGE      TOTAL FLAGS
     0: [0..511]:        26624..27135       512   0x9

Fix this by never attempting to merge extents if the flags contain FIEMAP_EXTENT_ENCODED.

Fixes 4751832da990 ("btrfs: fiemap: Cache and merge fiemap extent before submit it to user")
---
 fs/btrfs/fiemap.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
fs/btrfs/fiemap.c +2 -1
index 30a0f66c9c9ef..5fb7342a616d1 100644
@@ -228,7 +228,8 @@ static int emit_fiemap_extent(struct fiemap_extent_info *fieinfo,
 	 *
 	 * 3) Share same flags
 	 */
-	if (cache->offset + cache->len  == offset &&
+	if (!(flags & FIEMAP_EXTENT_ENCODED) &&
+	    cache->offset + cache->len == offset &&
 	    cache->phys + cache->len == phys  &&
 	    cache->flags == flags) {
 		cache->len += len;
Signature · 1 line
2.53.0
author maintainer
#91 lore raw

PATCH 90/990 btrfs: scrub: fix lost wakeup and hang when cancelling a scrub that is finishing

In reply to Greg Kroah-Hartman

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

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

From: Filipe Manana <[email protected]>

[ Upstream commit bda65e5115fe66ee0d8cf4ade11807f9fca4f0e1 ]

When scrub finishes, it does a wakeup on the fs_info->scrub_pause_wait wait queue and then sets dev->scrub_sctx to NULL. On the other hand the scrub cancel code (btrfs_scrub_cancel_dev()) waits on that wait queue for dev->scrub_sctx to be NULL. So this means if btrfs_scrub_cancel_dev() is called right when scrub is finishing and sees the wakeup before the NULL is assigned to dev->scrub_sctx by btrfs_scrub_dev(), it hangs.

Fix this by doing the wakeup in btrfs_scrub_dev() after setting dev->scrub_sctx to NULL.

Fixes a2de733c78fa ("btrfs: scrub")
---
 fs/btrfs/scrub.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
fs/btrfs/scrub.c +7 -1
index fdf37653907c7..a924eeb7a6618 100644
@@ -3174,7 +3174,6 @@ int btrfs_scrub_dev(struct btrfs_fs_info *fs_info, u64 devid, u64 start,
 	memalloc_nofs_restore(nofs_flag);
 
 	atomic_dec(&fs_info->scrubs_running);
-	wake_up(&fs_info->scrub_pause_wait);
 
 	if (progress)
 		memcpy(progress, &sctx->stat, sizeof(*progress));
@@ -3187,6 +3186,13 @@ int btrfs_scrub_dev(struct btrfs_fs_info *fs_info, u64 devid, u64 start,
 	dev->scrub_ctx = NULL;
 	mutex_unlock(&fs_info->scrub_lock);
 
+	/*
+	 * We have set dev->scrub_ctx to NULL, now do the wakeup as a concurrent
+	 * scrub cancel (btrfs_scrub_cancel_dev()) waits for dev->scrub_ctx to
+	 * be set to NULL.
+	 */
+	wake_up(&fs_info->scrub_pause_wait);
+
 	scrub_workers_put(fs_info);
 	scrub_put_ctx(sctx);
 
Signature · 1 line
2.53.0
author maintainer
#92 lore raw

PATCH 91/990 btrfs: zoned: fix double free of bitmaps on clone failure

In reply to Greg Kroah-Hartman

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

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

From: Thomas Fourier <[email protected]>

[ Upstream commit 8c66a6aa59a5df1d672d72b7cd379d897ff73200 ]

btrfs_clone_dev_zone_info() duplicates the original orig_dev->zone_info with kmemdup(), which also copies the seq_zones, empty_zones and active_zones pointers. The clone then replaces them one by one with fresh bitmaps. If one of the allocations fails, the error path frees all three pointers, including those not yet replaced, which still point to the bitmaps owned by the original device.

Clear the three pointers right after kmemdup() so the error path only frees what this function allocated.

Fixes 21e61ec6d0bb ("btrfs: zoned: clone zoned device info when cloning a device")
---
 fs/btrfs/zoned.c | 5 +++++
 1 file changed, 5 insertions(+)
fs/btrfs/zoned.c +5 -0
index 88559307bac7d..69ede4e4d0c20 100644
@@ -642,6 +642,11 @@ struct btrfs_zoned_device_info *btrfs_clone_dev_zone_info(struct btrfs_device *o
 	if (!zone_info)
 		return NULL;
 
+	/* Don't let the error path free the bitmaps still owned by @orig_dev. */
+	zone_info->seq_zones = NULL;
+	zone_info->empty_zones = NULL;
+	zone_info->active_zones = NULL;
+
 	zone_info->seq_zones = bitmap_zalloc(zone_info->nr_zones, GFP_KERNEL);
 	if (!zone_info->seq_zones)
 		goto out;
Signature · 1 line
2.53.0
author maintainer
#65 lore raw

PATCH 65/990 net/9p/usbg: Fix use-after-free on usb9pfs_clear_tx

In reply to Greg Kroah-Hartman

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

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

From: Yizhou Zhao <[email protected]>

[ Upstream commit 5c69297356bf6d04d8222f52717c6c4aa73e5d2c ]

When p9_usbg_close() is called, it invokes usb9pfs_clear_tx() but does not clear usb9pfs->client nor usb9pfs->in_req->context afterwards. The 9p client core (p9_client_destroy) calls close() and then kfree(clnt), so after p9_usbg_close returns the client struct is freed.

If the USB gadget is later disabled (e.g., host disconnect), usb9pfs_disable calls usb9pfs_clear_tx again, which passes the dangling usb9pfs->client pointer to p9_client_cb. Inside p9_client_cb, p9_req_put(c, req) dereferences the freed client to access its reqs IDR, causing a use-after-free.

Additionally, usb9pfs_clear_tx does not clear usb9pfs->in_req->context after calling p9_client_cb, so a second invocation finds a stale request pointer and attempts double-completion, further compounding the UAF risk.

Fix by:
1. Clearing usb9pfs->in_req->context to NULL in usb9pfs_clear_tx() before checking usb9pfs->client, so that even if the client is gone the stale request pointer is consumed and cannot cause double-completion.
2. Adding a NULL check on usb9pfs->client in usb9pfs_clear_tx() to skip p9_client_cb() when the client has already been destroyed.
3. Setting usb9pfs->client = NULL in p9_usbg_close() after calling usb9pfs_clear_tx(), to prevent any subsequent call from dereferencing the freed client pointer.

Fixes a3be076dc174 ("net/9p/usbg: Add new usb gadget function transport")
Assisted-by GLM:GLM-5.1

Message-ID: <[email protected]>

---
 net/9p/trans_usbg.c | 6 ++++++
 1 file changed, 6 insertions(+)
net/9p/trans_usbg.c +6 -0
index 1592b99ae00c7..79735bbe739ac 100644
@@ -460,6 +460,11 @@ static void usb9pfs_clear_tx(struct f_usb9pfs *usb9pfs)
 	if (!req || !client)
 		return;
 
+	usb9pfs->in_req->context = NULL;
+
+	if (!usb9pfs->client)
+		return;
+
 	if (!req->t_err)
 		req->t_err = -ECONNRESET;
 
@@ -483,6 +488,7 @@ static void p9_usbg_close(struct p9_client *client)
 	client->status = Disconnected;
 
 	usb9pfs_clear_tx(usb9pfs);
+	usb9pfs->client = NULL;
 
 	opts = container_of(usb9pfs->function.fi,
 			    struct f_usb9pfs_opts, func_inst);
Signature · 1 line
2.53.0
author maintainer
#93 lore raw

PATCH 92/990 bpf: Drop percpu_counter from the htab element count

In reply to Greg Kroah-Hartman

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

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

From: Puranjay Mohan <[email protected]>

[ Upstream commit 1cd28b5354ab77c727ed87255bf289a87178b415 ]

The element count of a large non-preallocated hash map is a percpu_counter, whose slow path takes fbc->lock with raw_spin_lock_irqsave(). That is not safe against BPF programs that run while the lock is held or contended: NMI programs and, as queued_spin_lock_slowpath() calls trace_contention_end() with the lock already held, programs attached to the contention_end tracepoint. If such a program updates the same map it spins on the lock its own CPU holds:

WARNING: possible recursive locking detected cend/250 is trying to acquire lock:
(key#5){....}-{2:2}, at: _raw_spin_lock_irqsave+0x18/0x30 but task is already holding lock:
(key#5){....}-{2:2}, at: _raw_spin_lock_irqsave+0x18/0x30

    percpu_counter_add_batch+0xd8/0x160
    alloc_htab_elem+0x408/0x480
    htab_map_update_elem+0x1e8/0x6a0
    bpf_prog_7a29a1ae68aedf07_cend+0x14c/0x1f8
    __bpf_trace_contention_end+0x14/0x20
    queued_spin_lock_slowpath+0x2e8/0x468
    percpu_counter_add_batch+0xd8/0x160
    alloc_htab_elem+0x408/0x480
    htab_map_update_elem+0x1e8/0x6a0

is_map_full() is affected too, as __percpu_counter_compare() falls back to percpu_counter_sum(), which takes the same lock.

map.elem_count already is a lockless per-cpu count of the same elements. Make htab->count follow it in steps of PERCPU_COUNTER_BATCH and let is_map_full() sum elem_count once count is within nr_cpu_ids * batch of max_entries. Each cpu's elem_count is ahead of count by less than the batch, so that is exact, in NMI as well.

Fixes 86fe28f7692d ("bpf: Optimize element count in non-preallocated hash map.")
---
 include/linux/bpf.h  |  2 ++
 kernel/bpf/hashtab.c | 64 ++++++++++++++++++--------------------------
 2 files changed, 28 insertions(+), 38 deletions(-)
include/linux/bpf.h +2 -0
index d840ec32d95ba..fc5af5a7f6a21 100644
@@ -2546,6 +2546,8 @@ static inline void bpf_map_dec_elem_count(struct bpf_map *map)
 	this_cpu_dec(*map->elem_count);
 }
 
+s64 bpf_map_sum_elem_count(const struct bpf_map *map);
+
 extern int sysctl_unprivileged_bpf_disabled;
 
 bool bpf_token_capable(const struct bpf_token *token, int cap);
kernel/bpf/hashtab.c +26 -38

120 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#94 lore raw

PATCH 93/990 net: ethernet: mtk_wed: skip ring reset in wdma_tx_ring_setup for WED v3

In reply to Greg Kroah-Hartman

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

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

From: Zhi-Jun You <[email protected]>

[ Upstream commit cb50f16f37fc3429085c454ee5978e05732d10ba ]

Currently WED v3 tx wdma ring, ring reset happens in a separate code block unconditionally.

Moreover, v3 has double the size of wdma_desc and has different init values. mtk_wed_ring_reset doens't deal with that and would corrupt the wdma_desc.

Fix this by skipping mtk_wed_ring_reset in mtk_wdma_tx_ring_setup for WED v3.

---
 drivers/net/ethernet/mediatek/mtk_wed.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/ethernet/mediatek/mtk_wed.c +1 -1
index fdb487e5d46e1..04a8da8cb3c51 100644
@@ -1938,7 +1938,7 @@ mtk_wed_wdma_tx_ring_setup(struct mtk_wed_device *dev, int idx, int size,
 	wdma_w32(dev, MTK_WDMA_RING_TX(idx) + MTK_WED_RING_OFS_CPU_IDX, 0);
 	wdma_w32(dev, MTK_WDMA_RING_TX(idx) + MTK_WED_RING_OFS_DMA_IDX, 0);
 
-	if (reset)
+	if (!mtk_wed_is_v3_or_greater(dev->hw) && reset)
 		mtk_wed_ring_reset(wdma, MTK_WED_WDMA_RING_SIZE, true);
 
 	if (!idx)  {
Signature · 1 line
2.53.0
author maintainer
#95 lore raw

PATCH 94/990 net: ethernet: mtk_wed: fix reset condition for rx wdma

In reply to Greg Kroah-Hartman

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

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

From: Zhi-Jun You <[email protected]>

[ Upstream commit 7180a42d8e616f919dcff4b90a13b9a5ecea665b ]

In mtk_wdma_rx_reset, currently only resets the CPU index of the rings that doesn't have a descriptor. This is wrong because no descriptor means the ring is not configured.

Also mtk_wed_start makes sure that all rx_wdma rings are set up this would lead to no ring getting their CPU index reset.

Fix this by inverting the reset condition so allocated rings will be reset.

---
 drivers/net/ethernet/mediatek/mtk_wed.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/net/ethernet/mediatek/mtk_wed.c +1 -1
index 04a8da8cb3c51..202ab2f34d56a 100644
@@ -257,7 +257,7 @@ mtk_wdma_rx_reset(struct mtk_wed_device *dev)
 	wdma_w32(dev, MTK_WDMA_RESET_IDX, 0);
 
 	for (i = 0; i < ARRAY_SIZE(dev->rx_wdma); i++) {
-		if (dev->rx_wdma[i].desc)
+		if (!dev->rx_wdma[i].desc)
 			continue;
 
 		wdma_w32(dev,
Signature · 1 line
2.53.0
author maintainer
#96 lore raw

PATCH 95/990 net: ethernet: mtk_wed: free up rings during detach

In reply to Greg Kroah-Hartman

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

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

From: Zhi-Jun You <[email protected]>

[ Upstream commit 5b8d12512cbd3495dbd8c38e8047bb5d716f0f3f ]

During __mtk_wed_detach, rx_ring and tx_wdma aren't freed up.

Fix this by add them to mtk_wed_free_rx_rings.

This patch is pulled from mtk-openwrt-feeds to address Sashiko's review and edit to rely on ring->desc instead of an extra flag.

---
 drivers/net/ethernet/mediatek/mtk_wed.c | 8 ++++++++
 1 file changed, 8 insertions(+)
drivers/net/ethernet/mediatek/mtk_wed.c +8 -0
index 202ab2f34d56a..e81a62c6029c2 100644
@@ -949,6 +949,14 @@ mtk_wed_free_ring(struct mtk_wed_device *dev, struct mtk_wed_ring *ring)
 static void
 mtk_wed_free_rx_rings(struct mtk_wed_device *dev)
 {
+	int i;
+
+	for (i = 0; i < ARRAY_SIZE(dev->rx_ring); i++)
+		mtk_wed_free_ring(dev, &dev->rx_ring[i]);
+
+	for (i = 0; i < ARRAY_SIZE(dev->tx_wdma); i++)
+		mtk_wed_free_ring(dev, &dev->tx_wdma[i]);
+
 	mtk_wed_free_rx_buffer(dev);
 	mtk_wed_free_ring(dev, &dev->rro.ring);
 }
Signature · 1 line
2.53.0
Tested-by on the v1 series
#89 lore raw
In reply to Greg Kroah-Hartman
Quoted 4 lines · On Wed, 25 Nov 2026 15:22:47 +0100 Greg Kroah-Hartman…

This is the start of the stable review cycle for the 6.18.66 release. There are 990 patches in this series, all will be posted as a response to this one. If anyone has any issues with these being applied, please let me know.

This rc kernel passes DAMON functionality test [1] on my test machine.

[1] https://github.com/damonitor/damon-tests/tree/next/corr

Thanks,
SJ

[...]

author maintainer
#97 lore raw

PATCH 96/990 net: ethernet: mtk_wed: setup WDMA_RING_TX(0) for non-DBDC MT7986

In reply to Greg Kroah-Hartman

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

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

From: Zhi-Jun You <[email protected]>

[ Upstream commit dd6efae5529107cc8db277eaeaff5c5f15e6bc15 ]

WDMA_RING_TX(0) is required to set MTK_WED_WDMA_RING_TX for WED RX but on a non-DBDC MT7986 it is never setup because idx is 1.

Setting MTK_WED_WDMA_RING_TX with WDMA_RING_TX(1) is not feasible because WED still tries to send through WDMA_RING_TX(0). This is verified with register dump.

Fix this by calling mtk_wed_wdma_tx_ring_setup if wed is v2 and rx_ring[0] is not allocated and reset tx_wdma[0] if it's already allocated also add error messages and bail when mtk_wed_start fails.

Fixes 4c5de09eb0d0 ("net: ethernet: mtk_wed: add configure wed wo support")
---
 drivers/net/ethernet/mediatek/mtk_wed.c | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)
drivers/net/ethernet/mediatek/mtk_wed.c +14 -1
index e81a62c6029c2..03829017dc49e 100644
@@ -2345,7 +2345,20 @@ mtk_wed_start(struct mtk_wed_device *dev, u32 irq_mask)
 
 	for (i = 0; i < ARRAY_SIZE(dev->rx_wdma); i++)
 		if (!dev->rx_wdma[i].desc)
-			mtk_wed_wdma_rx_ring_setup(dev, i, 16, false);
+			if (mtk_wed_wdma_rx_ring_setup(dev, i, 16, false)) {
+				dev_err(dev->hw->dev, "wdma rx ring %d setup failed\n", i);
+				return;
+			}
+
+	/*
+	 * non-DBDC MT7986 allocates only rx_ring[1] and tx_wdma[1] during setup
+	 * but tx_wdma[0] is also needed for WED to function.
+	 */
+	if (mtk_wed_is_v2(dev->hw) && !dev->rx_ring[0].desc)
+		if (mtk_wed_wdma_tx_ring_setup(dev, 0, MTK_WED_WDMA_RING_SIZE, !!dev->tx_wdma[0].desc)) {
+			dev_err(dev->hw->dev, "wdma tx ring 0 setup failed\n");
+			return;
+		}
 
 	if (dev->wlan.hw_rro) {
 		for (i = 0; i < MTK_WED_RX_PAGE_QUEUES; i++) {
Signature · 1 line
2.53.0
author maintainer
#98 lore raw

PATCH 97/990 ptp: drain virtual clock sysfs operations before unregistering children

In reply to Greg Kroah-Hartman

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

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

From: James Hilliard <[email protected]>

[ Upstream commit 0e4a135aebc7686286d87e286499ce55e5bd5aad ]

Parent clock removal walks its virtual clocks before removing the n_vclocks sysfs attribute. The mutex taken by ptp_vclock_in_use() is released before that walk, so a concurrent sysfs deletion can pick the same child and unregister and free its ptp_vclock a second time. A reference held by the device iterator does not protect that separately allocated virtual clock.

Remove n_vclocks before walking the children. Removing the attribute prevents new stores and drains stores already running, without holding n_vclocks_mux across a callback that needs that mutex. Skip virtual clocks, which do not have this attribute.

This race was found by code inspection of virtual-clock registration failure cleanup and parent removal.

Fixes bfcbb76b0f59 ("ptp: unregister virtual clocks when unregistering physical clock.")
---
 drivers/ptp/ptp_clock.c   | 5 +++++
 drivers/ptp/ptp_private.h | 1 +
 drivers/ptp/ptp_sysfs.c   | 6 ++++++
 3 files changed, 12 insertions(+)
drivers/ptp/ptp_clock.c +5 -0
index ef020599b7711..8b27c749aebea 100644
@@ -494,6 +494,11 @@ static int unregister_vclock(struct device *dev, void *data)
 
 int ptp_clock_unregister(struct ptp_clock *ptp)
 {
+	/*
+	 * Stop and drain virtual-clock creation and deletion before walking the
+	 * children. Do not hold n_vclocks_mux while waiting for sysfs callbacks.
+	 */
+	ptp_vclock_remove_sysfs(ptp);
 	if (ptp_vclock_in_use(ptp)) {
 		device_for_each_child(&ptp->dev, NULL, unregister_vclock);
 	}
drivers/ptp/ptp_private.h +1 -0
index db4039d642b41..ec8633126d6b8 100644
@@ -169,6 +169,7 @@ extern const struct attribute_group *ptp_groups[];
 
 int ptp_populate_pin_groups(struct ptp_clock *ptp);
 void ptp_cleanup_pin_groups(struct ptp_clock *ptp);
+void ptp_vclock_remove_sysfs(struct ptp_clock *ptp);
 
 struct ptp_vclock *ptp_vclock_register(struct ptp_clock *pclock);
 void ptp_vclock_unregister(struct ptp_vclock *vclock);
drivers/ptp/ptp_sysfs.c +6 -0
index 0d4b081daf639..998de4be08ebd 100644
@@ -267,6 +267,12 @@ static ssize_t n_vclocks_store(struct device *dev,
 }
 static DEVICE_ATTR_RW(n_vclocks);
 
+void ptp_vclock_remove_sysfs(struct ptp_clock *ptp)
+{
+	if (!ptp->is_virtual_clock)
+		device_remove_file(&ptp->dev, &dev_attr_n_vclocks);
+}
+
 static ssize_t max_vclocks_show(struct device *dev,
 				struct device_attribute *attr, char *page)
 {
Signature · 1 line
2.53.0
author maintainer
#99 lore raw

PATCH 98/990 ptp: unwind partially completed virtual clock creation

In reply to Greg Kroah-Hartman

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

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

From: James Hilliard <[email protected]>

[ Upstream commit 3dea778260e3dddf30651a6913d87a42861346a2 ]

n_vclocks_store() publishes the new clock count only after every child has been registered. If a later registration fails, it returns without unregistering the children already created by that request. Those clocks are left out of n_vclocks, and a subsequent request can overwrite their index entries without removing them.

Unregister the newly created children in reverse order and clear their index entries on failure. Leave the previously installed clocks and their count unchanged. The n_vclocks mutex serializes this rollback with other sysfs changes, and parent removal drains the store before walking the children.

This was found by code inspection while adding initial PHC sample error handling to virtual clock registration.

Fixes 73f37068d540 ("ptp: support ptp physical/virtual clocks conversion")
---
 drivers/ptp/ptp_sysfs.c | 8 +++++++-
 1 file changed, 7 insertions(+), 1 deletion(-)
drivers/ptp/ptp_sysfs.c +7 -1
index 998de4be08ebd..b07274b67294a 100644
@@ -229,7 +229,7 @@ static ssize_t n_vclocks_store(struct device *dev,
 		for (i = 0; i < num - ptp->n_vclocks; i++) {
 			vclock = ptp_vclock_register(ptp);
 			if (!vclock)
-				goto out;
+				goto err_register;
 
 			*(ptp->vclock_index + ptp->n_vclocks + i) =
 				vclock->clock->index;
@@ -261,6 +261,12 @@ static ssize_t n_vclocks_store(struct device *dev,
 	mutex_unlock(&ptp->n_vclocks_mux);
 
 	return count;
+err_register:
+	num = i;
+	if (num)
+		device_for_each_child_reverse(dev, &num, unregister_vclock);
+	for (num = 0; num < i; num++)
+		ptp->vclock_index[ptp->n_vclocks + num] = -1;
 out:
 	mutex_unlock(&ptp->n_vclocks_mux);
 	return err;
Signature · 1 line
2.53.0
author maintainer
#100 lore raw

PATCH 99/990 ptp: vclock: propagate physical clock sampling errors

In reply to Greg Kroah-Hartman

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

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

From: James Hilliard <[email protected]>

[ Upstream commit d1bdfdafd663dd00b01d43eb3391f87718f2a09d ]

The cyclecounter read callback cannot report errors. ptp_vclock_read() ignores the return from the physical clock and consumes its output even if the read failed. A zero sample followed by the real counter can add an extra 32-bit wrap to virtual time. This was found by code inspection of reset-time PHC access and the virtual clock callers.

Sample the parent before calling timecounter_read() or timecounter_init() and have the cyclecounter callback return the cached successful sample. On failure, leave the counter and frequency adjustment unchanged and return the PHC error to the caller.

Retry the first failed refresh after 10 ms instead of waiting another two seconds. With the existing 32-bit nanosecond mask, timecounter_cyc2time() can interpret a fresh timestamp as being in the past once the last successful refresh is about 2.147 seconds old. An isolated read failure should not deliberately defer the next attempt until that sample is four seconds old.

Double the retry delay after consecutive failures, up to the normal two-second refresh interval, and reset it after a successful refresh. Each virtual clock has its own worker, and a failed parent read can involve bus traffic and error logging. Backoff limits that repeated work during a persistent failure while retaining a prompt first retry.

Limit each retry delay to the next regular refresh deadline. Otherwise, backoff can skip the next two-second refresh opportunity and lose a full counter wrap even when the parent has recovered before that refresh was due. Advance the deadline when an attempt reaches it without resetting the backoff, so sustained failures still settle at the normal refresh interval. Keep the retry state private to each clock's auxiliary worker.

Take the initial sample and initialize the counter before publishing the clock. Return an error pointer from registration and propagate its errno through n_vclocks, including when the initial sample fails. Queue the first refresh immediately after registration so registration latency is not followed by another full refresh interval.

Keep the existing cyclecounter mask and scaling. These scheduling changes do not guarantee timely samples: prolonged read failures or worker delays can still exceed the half-wrap conversion window, and a gap of about 4.295 seconds between successful samples can lose a full counter wrap. Do not assume that getcycles64() exposes a full-width nanosecond counter.

Fixes 5d43f951b1ac ("ptp: add ptp virtual clock driver framework")
---
 drivers/ptp/ptp_private.h |  6 ++-
 drivers/ptp/ptp_sysfs.c   |  4 +-
 drivers/ptp/ptp_vclock.c  | 89 ++++++++++++++++++++++++++++++---------
 3 files changed, 76 insertions(+), 23 deletions(-)
drivers/ptp/ptp_private.h +5 -1
index ec8633126d6b8..99e7eb241336e 100644
@@ -81,7 +81,11 @@ struct ptp_vclock {
 	struct hlist_node vclock_hash_node;
 	struct cyclecounter cc;
 	struct timecounter tc;
-	struct mutex lock;	/* protects tc/cc */
+	u64 cycles;
+	struct mutex lock;	/* protects tc/cc and the cached sample */
+	/* Owned by the auxiliary worker. */
+	unsigned long retry_delay;
+	unsigned long refresh_deadline;
 };
 
 /*
drivers/ptp/ptp_sysfs.c +3 -1
index b07274b67294a..de073b21f1f72 100644
@@ -228,8 +228,10 @@ static ssize_t n_vclocks_store(struct device *dev,
 	if (num > ptp->n_vclocks) {
 		for (i = 0; i < num - ptp->n_vclocks; i++) {
 			vclock = ptp_vclock_register(ptp);
-			if (!vclock)
+			if (IS_ERR(vclock)) {
+				err = PTR_ERR(vclock);
 				goto err_register;
+			}
 
 			*(ptp->vclock_index + ptp->n_vclocks + i) =
 				vclock->clock->index;
drivers/ptp/ptp_vclock.c +68 -21

179 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#101 lore raw

PATCH 100/990 ptp: vclock: serialize extended samples with counter updates

In reply to Greg Kroah-Hartman

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

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

From: James Hilliard <[email protected]>

[ Upstream commit d3fcce5afe3bb62e8f7a2efb29e43da4fe4ae1f3 ]

The extended and cross-timestamp callbacks sample the physical clock before taking the virtual clock mutex. A concurrent frequency adjustment can advance the timecounter and change its multiplier in between, so the older sample is converted using a different frequency than the one in effect when it was taken.

Take the mutex before sampling and keep it held through the conversion. Retain timecounter_cyc2time() and its existing conversion window. A PHC sample need not advance the counter: for example, e1000e explicitly allows non-monotonic SYSTIM readings. Treating a slightly older sample as a forward delta would instead advance virtual time by nearly a full counter wrap.

This race was found by code inspection of the virtual clock sampling paths.

Fixes f0067ebfc42b ("ptp: add gettimex64() to virtual clocks.")
Fixes 21fad63084c2 ("ptp: add getcrosststamp() to virtual clocks.")
---
 drivers/ptp/ptp_vclock.c | 32 ++++++++++++++------------------
 1 file changed, 14 insertions(+), 18 deletions(-)
drivers/ptp/ptp_vclock.c +14 -18
index 96efbadc0baef..1a75a5b9bc058 100644
@@ -115,20 +115,18 @@ static int ptp_vclock_gettimex(struct ptp_clock_info *ptp,
 	struct ptp_clock *pptp = vclock->pclock;
 	struct timespec64 pts;
 	int err;
-	u64 ns;
-
-	err = pptp->info->getcyclesx64(pptp->info, &pts, sts);
-	if (err)
-		return err;
 
 	if (mutex_lock_interruptible(&vclock->lock))
 		return -EINTR;
-	ns = timecounter_cyc2time(&vclock->tc, timespec64_to_ns(&pts));
-	mutex_unlock(&vclock->lock);
+	err = pptp->info->getcyclesx64(pptp->info, &pts, sts);
+	if (!err) {
+		u64 ns = timecounter_cyc2time(&vclock->tc, timespec64_to_ns(&pts));
 
-	*ts = ns_to_timespec64(ns);
+		*ts = ns_to_timespec64(ns);
+	}
+	mutex_unlock(&vclock->lock);
 
-	return 0;
+	return err;
 }
 
 static int ptp_vclock_settime(struct ptp_clock_info *ptp,
@@ -154,20 +152,18 @@ static int ptp_vclock_getcrosststamp(struct ptp_clock_info *ptp,
 	struct ptp_vclock *vclock = info_to_vclock(ptp);
 	struct ptp_clock *pptp = vclock->pclock;
 	int err;
-	u64 ns;
-
-	err = pptp->info->getcrosscycles(pptp->info, xtstamp);
-	if (err)
-		return err;
 
 	if (mutex_lock_interruptible(&vclock->lock))
 		return -EINTR;
-	ns = timecounter_cyc2time(&vclock->tc, ktime_to_ns(xtstamp->device));
-	mutex_unlock(&vclock->lock);
+	err = pptp->info->getcrosscycles(pptp->info, xtstamp);
+	if (!err) {
+		u64 ns = timecounter_cyc2time(&vclock->tc, ktime_to_ns(xtstamp->device));
 
-	xtstamp->device = ns_to_ktime(ns);
+		xtstamp->device = ns_to_ktime(ns);
+	}
+	mutex_unlock(&vclock->lock);
 
-	return 0;
+	return err;
 }
 
 static long ptp_vclock_refresh(struct ptp_clock_info *ptp)
Signature · 1 line
2.53.0
author maintainer
#102 lore raw

PATCH 101/990 ptp: vclock: preserve missing hardware timestamps

In reply to Greg Kroah-Hartman

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

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

From: James Hilliard <[email protected]>

[ Upstream commit 63787dfd1b5ae720cc30dab5e66c8e4d81ff7391 ]

Socket timestamp delivery converts hardware timestamps to a bound virtual clock before checking whether a hardware timestamp is present. A zero timestamp means that the packet has no hardware timestamp, but timecounter_cyc2time() can turn that zero into a nonzero virtual time. The socket then reports a hardware timestamp which was never supplied.

Return zero without conversion when the input timestamp is absent. This also covers skb_get_tx_timestamp(), which checks for an absent timestamp after the same conversion.

This was identified during review of virtual clock sampling changes.

Fixes d7c088265588 ("net: socket: support hardware timestamp conversion to PHC bound")
---
 drivers/ptp/ptp_vclock.c         | 2 ++
 include/linux/ptp_clock_kernel.h | 2 +-
 2 files changed, 3 insertions(+), 1 deletion(-)
drivers/ptp/ptp_vclock.c +2 -0
index 1a75a5b9bc058..0ecd63eb729a4 100644
@@ -326,6 +326,8 @@ ktime_t ptp_convert_timestamp(const ktime_t *hwtstamp, int vclock_index)
 	u64 ns;
 
 	ns = ktime_to_ns(*hwtstamp);
+	if (!ns)
+		return 0;
 
 	srcu_idx = srcu_read_lock(&vclock_srcu);
 
include/linux/ptp_clock_kernel.h +1 -1
index 884364596dd32..d199ac4ec1c8f 100644
@@ -495,7 +495,7 @@ int ptp_get_vclocks_index(int pclock_index, int **vclock_index);
  * @hwtstamp:     timestamp
  * @vclock_index: phc index of ptp vclock.
  *
- * Returns: converted timestamp, or 0 on error.
+ * Returns: converted timestamp, or 0 if @hwtstamp is zero or on error.
  */
 ktime_t ptp_convert_timestamp(const ktime_t *hwtstamp, int vclock_index);
 #else
Signature · 1 line
2.53.0
author maintainer
#66 lore raw

PATCH 66/990 9p: skip intermediate directory entry name copy in p9dirent_read()

In reply to Greg Kroah-Hartman

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

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

From: Haobin Wu <[email protected]>

[ Upstream commit 8bb0279930cc90975f03bad4d83282613e5f57fa ]

v9fs_dir_readdir_dotl() decodes each entry of a Rreaddir reply with p9dirent_read(), which parses it through p9pdu_readf("Qqbs"). The 's' conversion in p9pdu_vreadf() already allocates a NUL-terminated copy of the name from the wire buffer; p9dirent_read() then strscpy()s that copy into the fixed 256-byte p9_dirent::d_name and frees the original.

The wire format carries the name length in 16 bits, so a name longer than 255 bytes is valid on the wire and may well be valid on the server's filesystem, but it makes strscpy() return -E2BIG. v9fs_dir_readdir_dotl() turns that into -EIO and aborts getdents64(), so every entry after the long one disappears from the listing.

Drop the second copy: keep the string allocated by p9pdu_vreadf() in p9_dirent and let v9fs_dir_readdir_dotl(), its only user, free it once dir_emit() has consumed it. p9_dirent is a short-lived stack object, so the string's lifetime does not change.

Note that the VFS only rejects names of PATH_MAX bytes or more in verify_dirent_name(), so after this change a name between NAME_MAX and PATH_MAX is returned by getdents64() even though any later lookup on it fails with -ENAMETOOLONG. The next patch skips such entries.

Fixes 7751bdb3a095 ("9p: readdir implementation for 9p2000.L")

Message-ID: <[email protected]>

---
 fs/9p/vfs_dir.c         |  6 +++++-
 include/net/9p/client.h |  2 +-
 net/9p/protocol.c       | 12 ++----------
 3 files changed, 8 insertions(+), 12 deletions(-)
fs/9p/vfs_dir.c +5 -1
index 323f85352f6a4..733ec42258bc6 100644
@@ -196,8 +196,12 @@ static int v9fs_dir_readdir_dotl(struct file *file, struct dir_context *ctx)
 			if (!dir_emit(ctx, curdirent.d_name,
 				      strlen(curdirent.d_name),
 				      QID2INO(&curdirent.qid),
-				      curdirent.d_type))
+				      curdirent.d_type)) {
+				kfree(curdirent.d_name);
 				return 0;
+			}
+
+			kfree(curdirent.d_name);
 
 			ctx->pos = curdirent.d_off;
 			rdir->head += err;
include/net/9p/client.h +1 -1
index 838a94218b593..9f3079c6f3867 100644
@@ -268,7 +268,7 @@ struct p9_dirent {
 	struct p9_qid qid;
 	u64 d_off;
 	unsigned char d_type;
-	char d_name[256];
+	char *d_name;
 };
 
 struct iov_iter;
net/9p/protocol.c +2 -10
index 0e6603b1ec906..0a97b4de243ab 100644
@@ -771,7 +771,7 @@ int p9dirent_read(struct p9_client *clnt, char *buf, int len,
 {
 	struct p9_fcall fake_pdu;
 	int ret;
-	char *nameptr;
+	char *nameptr = NULL;
 
 	fake_pdu.size = len;
 	fake_pdu.capacity = len;
@@ -786,15 +786,7 @@ int p9dirent_read(struct p9_client *clnt, char *buf, int len,
 		return ret;
 	}
 
-	ret = strscpy(dirent->d_name, nameptr, sizeof(dirent->d_name));
-	if (ret < 0) {
-		p9_debug(P9_DEBUG_ERROR,
-			 "On the wire dirent name too long: %s\n",
-			 nameptr);
-		kfree(nameptr);
-		return ret;
-	}
-	kfree(nameptr);
+	dirent->d_name = nameptr;
 
 	return fake_pdu.offset;
 }
Signature · 1 line
2.53.0
author maintainer
#103 lore raw

PATCH 102/990 net/smc: fix limit_smc_hs sysctl on big-endian architecture

In reply to Greg Kroah-Hartman

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

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

From: Fernando Fernandez Mancera <[email protected]>

[ Upstream commit 162cf592b577cccf04515100563e819d9eba5c4a ]

net->smc.limit_smc_hs is a bool, but its sysctl entry uses proc_dointvec_minmax() with .maxlen = sizeof(int), so the handler accesses four bytes at the address of a one-byte field.

On little-endian this works with the extra bytes being written in struct padding. On big-endian (tested on s390x) the bool sits at the most significant byte of the int therefore the bool stays false and the "1" goes into padding. The sysctl reads back 1 but SMC sockets created afterwards see limit_smc_hs as disabled.

Fix this by using proc_dobool() handler and adjust the maxlen to the right value.

---
 net/smc/smc_sysctl.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
net/smc/smc_sysctl.c +2 -4
index 2fab6456f7654..7da98bd5287ae 100644
@@ -93,11 +93,9 @@ static struct ctl_table smc_table[] = {
 	{
 		.procname	= "limit_smc_hs",
 		.data		= &init_net.smc.limit_smc_hs,
-		.maxlen		= sizeof(int),
+		.maxlen		= sizeof(bool),
 		.mode		= 0644,
-		.proc_handler	= proc_dointvec_minmax,
-		.extra1		= SYSCTL_ZERO,
-		.extra2		= SYSCTL_ONE,
+		.proc_handler	= proc_dobool,
 	},
 };
 
Signature · 1 line
2.53.0
author maintainer
#104 lore raw

PATCH 103/990 scsi: target: Validate REGISTER AND MOVE TransportID length

In reply to Greg Kroah-Hartman

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

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

From: Jia Jia <[email protected]>

[ Upstream commit 5d5913710c81eed6fa275b6a24773059d9dbfdfa ]

REGISTER AND MOVE has a 24-byte parameter-list header followed by a TransportID. A 24-byte parameter list with a zero TransportID length passes the existing tid_len + 24 check, then the handler reads buf[24] for the TransportID protocol identifier, one byte past the received parameter list.

A TransportID is at least 24 bytes. Reject shorter TransportIDs and compare the declared length with the bytes following the header before reading buf[24].

A malformed PR OUT sent through vhost-scsi triggered this read on a KASAN kernel. The command is now rejected with INVALID PARAMETER LIST before buf[24] is accessed.

Fixes c66ac9db8d4a ("[SCSI] target: Add LIO target core v4.0.0-rc6")
---
 drivers/target/target_core_pr.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)
drivers/target/target_core_pr.c +5 -4
index f18085d8345f5..24b240786f88a 100644
@@ -3220,10 +3220,11 @@ core_scsi3_emulate_pro_register_and_move(struct se_cmd *cmd, u64 res_key,
 	transport_kunmap_data_sg(cmd);
 	buf = NULL;
 
-	if ((tid_len + 24) != cmd->data_length) {
-		pr_err("SPC-3 PR: Illegal tid_len: %u + 24 byte header"
-			" does not equal CDB data_length: %u\n", tid_len,
-			cmd->data_length);
+	/* TransportID is at least 24 bytes. buf[24] is its first byte. */
+	if (tid_len < 24 ||
+	    tid_len != cmd->data_length - 24) {
+		pr_err("SPC-3 PR: Illegal tid_len: %u for data_length: %u\n",
+		       tid_len, cmd->data_length);
 		ret = TCM_INVALID_PARAMETER_LIST;
 		goto out_put_pr_reg;
 	}
Signature · 1 line
2.53.0
author maintainer
#105 lore raw

PATCH 104/990 tipc: reject attaching bearer of different media to the same occupied device

In reply to Greg Kroah-Hartman

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

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

From: Tung Nguyen <[email protected]>

[ Upstream commit 0a0257228be902ff09608bcaf19ae7c6d58b028f ]

Currently, two bearers of different media types can be added to the same device (e.g., "eth:eth0" and "ib:eth0") via tipc command:

tipc bearer enable media eth dev eth0
tipc bearer enable media ib dev eth0

For each command execution, tipc_enable_l2_media() is called:

tipc_enable_l2_media()
dev_get_by_name()
dev_hold()

As a result, device->dev_refcnt is incremented twice, but the second bearer replaces the first one. This causes a leak in device->dev_refcnt.

Fix this by rejecting a bearer with a different media type when the device is already occupied.

---
 net/tipc/bearer.c | 33 +++++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)
net/tipc/bearer.c +33 -0
index 24dcb8aa32330..e057d0c6786c4 100644
@@ -285,17 +285,50 @@ static int tipc_enable_bearer(struct net *net, const char *name,
 	bearer_id = MAX_BEARERS;
 	i = MAX_BEARERS;
 	while (i-- != 0) {
+		struct net_device *dev;
+
 		b = rtnl_dereference(tn->bearer_list[i]);
 		if (!b) {
 			bearer_id = i;
 			continue;
 		}
 		if (!strcmp(name, b->name)) {
+duplicate:
 			errstr = "already enabled";
 			NL_SET_ERR_MSG(extack, "Already enabled");
 			goto rejected;
 		}
 
+		/* udp media can be used together with any media */
+		if (b->media->type_id == TIPC_MEDIA_TYPE_UDP ||
+		    m->type_id == TIPC_MEDIA_TYPE_UDP)
+			goto priority;
+
+		dev = __dev_get_by_name(net, b_names.if_name);
+
+		if (!dev) {
+			res = -ENODEV;
+			errstr = "no device for the media";
+			NL_SET_ERR_MSG(extack, "No device for the media");
+			goto rejected;
+		}
+
+		if (rtnl_dereference(b->media_ptr) == dev) {
+			char *dev_name = strchr((const char *)b->name, ':') + 1;
+
+			/* Not allow altname of occupied device */
+			if (strcmp(dev_name, b_names.if_name) &&
+			    b->media->type_id == m->type_id)
+				goto duplicate;
+
+			/* Not allow eth and ib to attach to the same device */
+			errstr = "same dev for different media";
+			NL_SET_ERR_MSG(extack,
+				       "Same dev for different media");
+			goto rejected;
+		}
+
+priority:
 		if (b->priority == prio &&
 		    (++with_this_prio > 2)) {
 			pr_warn("Bearer <%s>: already 2 bearers with priority %u\n",
Signature · 1 line
2.53.0
author maintainer
#106 lore raw

PATCH 105/990 net: ipa: Fix double free of the interrupt structure on config error

In reply to Greg Kroah-Hartman

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

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

From: Thomas Fourier <[email protected]>

[ Upstream commit cb284914e749388eef402938bdb3115fe1f6d337 ]

Since ipa_interrupt_init() allocates struct ipa_interrupt in ipa_probe(), the structure is owned by ipa_probe() and released with ipa_interrupt_exit() on its error paths and in ipa_remove(). The error path of ipa_interrupt_config() still frees it with kfree(). If ipa_interrupt_config() fails (called from ipa_config() via ipa_setup()), ipa_probe() unwinds through err_interrupt_exit, which frees the same structure again.

Drop the kfree() from ipa_interrupt_config(); it should only undo what it set up itself. Drop the leftover initialization and cleanup of ipa->interrupt now managed in ipa_proble() and ipa_remove() of ipa_main.c.

---
 drivers/net/ipa/ipa_interrupt.c | 12 ++----------
 1 file changed, 2 insertions(+), 10 deletions(-)
drivers/net/ipa/ipa_interrupt.c +2 -10
index 245a069970556..dc5315ce31d32 100644
@@ -261,10 +261,8 @@ int ipa_interrupt_config(struct ipa *ipa)
 	interrupt->enabled = 0;
 	interrupt->suspend_enabled = bitmap_zalloc(ipa->endpoint_count,
 						   GFP_KERNEL);
-	if (!interrupt->suspend_enabled) {
-		ret = -ENOMEM;
-		goto err_kfree;
-	}
+	if (!interrupt->suspend_enabled)
+		return -ENOMEM;
 
 	/* Disable IPA interrupt types */
 	reg = ipa_reg(ipa, IPA_IRQ_EN);
@@ -290,8 +288,6 @@ int ipa_interrupt_config(struct ipa *ipa)
 		goto err_disable_wakeup;
 	}
 
-	ipa->interrupt = interrupt;
-
 	return 0;
 
 err_disable_wakeup:
@@ -300,8 +296,6 @@ int ipa_interrupt_config(struct ipa *ipa)
 	free_irq(interrupt->irq, interrupt);
 err_free_bitmap:
 	bitmap_free(interrupt->suspend_enabled);
-err_kfree:
-	kfree(interrupt);
 
 	return ret;
 }
@@ -312,8 +306,6 @@ void ipa_interrupt_deconfig(struct ipa *ipa)
 	struct ipa_interrupt *interrupt = ipa->interrupt;
 	struct device *dev = ipa->dev;
 
-	ipa->interrupt = NULL;
-
 	dev_pm_clear_wake_irq(dev);
 	(void)device_init_wakeup(dev, false);
 	free_irq(interrupt->irq, interrupt);
Signature · 1 line
2.53.0
author maintainer
#107 lore raw

PATCH 106/990 ALSA: memalloc: Free the new pages when WC DMA mapping fails

In reply to Greg Kroah-Hartman

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

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

[ Upstream commit 016fe9695e6dc1322ddfe8c7dbc7b973483b4a24 ]

snd_dma_wc_alloc() keeps the newly allocated pages in a local variable, and snd_dma_alloc_dir_pages() stores them in dmab->area only after ->alloc() returns. If dma_map_single() fails, the error path passes dmab->area to do_free_pages() instead, and that is still NULL at this point for the usual callers.

The pages are then leaked with their write-combining attribute still set, set_memory_wb() warns about the zero address, and for buffers larger than a page free_pages_exact() goes on to free the struct pages of the bogus addresses 4096, 8192 and so on. With CONFIG_DEBUG_VM that hits the VM_BUG_ON() in free_pages():

kernel BUG at mm/page_alloc.c:5600!

  RIP: 0010:free_pages_exact+0xcb/0xd0
  Call Trace:
   snd_dma_wc_alloc+0x14f/0x160 [snd_pcm]
   snd_dma_alloc_dir_pages+0x4f/0x80 [snd_pcm]

This was reproduced on an x86 guest without swiotlb by allocating SNDRV_DMA_TYPE_DEV_WC buffers for a device with a 24-bit streaming DMA mask, so that dma_map_single() fails.

Free the pages that were just allocated.

Fixes c880a5146642 ("ALSA: memalloc: Use proper DMA mapping API for x86 WC buffer allocations")
---
 sound/core/memalloc.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
sound/core/memalloc.c +1 -1
index b3853583d2ae1..e2887c9a24631 100644
@@ -506,7 +506,7 @@ static void *snd_dma_wc_alloc(struct snd_dma_buffer *dmab, size_t size)
 		return NULL;
 	dmab->addr = dma_map_single(dmab->dev.dev, p, size, DMA_BIDIRECTIONAL);
 	if (dma_mapping_error(dmab->dev.dev, dmab->addr)) {
-		do_free_pages(dmab->area, size, true);
+		do_free_pages(p, size, true);
 		return NULL;
 	}
 	return p;
Signature · 1 line
2.53.0
author maintainer
#108 lore raw

PATCH 107/990 netfilter: nft_reject: prevent unbounded recursion in output hooks

In reply to Greg Kroah-Hartman

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

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

From: Fernando Fernandez Mancera <[email protected]>

[ Upstream commit d6c18cadfc6c7a88e9e07e0a1b5ead37c0ddf866 ]

nftables payload-mangling rules can rewrite packet contents (such as TCP flags) before they are evaluated by reject targets. This defeats the content-based loop guards, allowing unbounded hook recursion that leads to kernel stack exhaustion and panics.

Fix this by extracting the per-CPU xmit recursion limit previously used by the netdev duplication/forwarding paths into a shared header, and apply it to the inet and inet6 reject transmit functions. It disables BH while transmitting the skb to address a possible migration to different CPU leading to imbalanced decrementation of the recursion counters.

Note that the dev_queue_xmit() path used when CONFIG_BRIDGE_NETFILTER is enabled does not require this recursion guard. In that scenario, the generated reset packet is transmitted directly at Layer 2. Because the packet egresses from a different hook, it cannot synchronously loop. In addition nf_send_unreach() and nf_send_unreach6() are safe as the ICMP transmit functions are protected against recursion by the icmp_xmit_lock() and icmpv6_xmit_lock() guards.

---
 include/linux/netdevice_xmit.h        |  4 +--
 include/net/netfilter/nf_dup_netdev.h | 35 ----------------------
 include/net/netfilter/nf_recursion.h  | 42 +++++++++++++++++++++++++++
 net/ipv4/netfilter/nf_reject_ipv4.c   | 12 ++++++++
 net/ipv6/netfilter/nf_reject_ipv6.c   | 13 +++++++++
 net/netfilter/nf_dup_netdev.c         |  1 +
 net/netfilter/nft_fwd_netdev.c        |  1 +
 7 files changed, 71 insertions(+), 37 deletions(-)
 create mode 100644 include/net/netfilter/nf_recursion.h
include/linux/netdevice_xmit.h +2 -2
index 813a19122ebbb..b4ce469cee740 100644
@@ -11,8 +11,8 @@ struct netdev_xmit {
 #if IS_ENABLED(CONFIG_NET_ACT_MIRRED)
 	u8 sched_mirred_nest;
 #endif
-#if IS_ENABLED(CONFIG_NF_DUP_NETDEV)
-	u8 nf_dup_skb_recursion;
+#if IS_ENABLED(CONFIG_NETFILTER)
+	u8 nf_xmit_skb_recursion;
 #endif
 };
 
include/net/netfilter/nf_dup_netdev.h +0 -35
index f6b05bd80c3fe..a394112646144 100644
@@ -9,41 +9,6 @@
 void nf_dup_netdev_egress(const struct nft_pktinfo *pkt, int oif);
 void nf_fwd_netdev_egress(const struct nft_pktinfo *pkt, int oif);
 
-#define NF_RECURSION_LIMIT	2
-
-#ifndef CONFIG_PREEMPT_RT
-static inline bool nf_dev_xmit_recursion(void)
-{
-	return unlikely(__this_cpu_read(softnet_data.xmit.nf_dup_skb_recursion) >
-			NF_RECURSION_LIMIT);
-}
-
-static inline void nf_dev_xmit_recursion_inc(void)
-{
-	__this_cpu_inc(softnet_data.xmit.nf_dup_skb_recursion);
-}
-
-static inline void nf_dev_xmit_recursion_dec(void)
-{
-	__this_cpu_dec(softnet_data.xmit.nf_dup_skb_recursion);
-}
-#else
-static inline bool nf_dev_xmit_recursion(void)
-{
-	return unlikely(current->net_xmit.nf_dup_skb_recursion > NF_RECURSION_LIMIT);
-}
-
-static inline void nf_dev_xmit_recursion_inc(void)
-{
-	current->net_xmit.nf_dup_skb_recursion++;
-}
-
-static inline void nf_dev_xmit_recursion_dec(void)
-{
-	current->net_xmit.nf_dup_skb_recursion--;
-}
-#endif
-
 struct nft_offload_ctx;
 struct nft_flow_rule;
 
include/net/netfilter/nf_recursion.h new file +42 -0

42 lines not on this page · raw message

net/ipv4/netfilter/nf_reject_ipv4.c +12 -0
index 7cb33af671e26..4082fa184af8b 100644
@@ -10,6 +10,7 @@
 #include <net/dst.h>
 #include <net/dst_metadata.h>
 #include <net/netfilter/ipv4/nf_reject.h>
+#include <net/netfilter/nf_recursion.h>
 #include <linux/netfilter_ipv4.h>
 #include <linux/netfilter_bridge.h>
 
@@ -336,7 +337,18 @@ void nf_send_reset(struct net *net, struct sock *sk, struct sk_buff *oldskb,
 		dev_queue_xmit(nskb);
 	} else
 #endif
+	{
+		local_bh_disable();
+		if (nf_dev_xmit_recursion()) {
+			local_bh_enable();
+			goto free_nskb;
+		}
+
+		nf_dev_xmit_recursion_inc();
 		ip_local_out(net, nskb->sk, nskb);
+		nf_dev_xmit_recursion_dec();
+		local_bh_enable();
+	}
 
 	return;
 
net/ipv6/netfilter/nf_reject_ipv6.c +13 -0
index 5e08d8529cc88..7c94641845175 100644
@@ -10,6 +10,7 @@
 #include <net/ip6_checksum.h>
 #include <net/dst_metadata.h>
 #include <net/netfilter/ipv6/nf_reject.h>
+#include <net/netfilter/nf_recursion.h>
 #include <linux/netfilter_ipv6.h>
 #include <linux/netfilter_bridge.h>
 
@@ -409,7 +410,19 @@ void nf_send_reset6(struct net *net, struct sock *sk, struct sk_buff *oldskb,
 		dev_queue_xmit(nskb);
 	} else
 #endif
+	{
+		local_bh_disable();
+		if (nf_dev_xmit_recursion()) {
+			local_bh_enable();
+			kfree_skb(nskb);
+			return;
+		}
+
+		nf_dev_xmit_recursion_inc();
 		ip6_local_out(net, sk, nskb);
+		nf_dev_xmit_recursion_dec();
+		local_bh_enable();
+	}
 }
 EXPORT_SYMBOL_GPL(nf_send_reset6);
 
net/netfilter/nf_dup_netdev.c +1 -0
index 02d1880bab6b3..c47508b54ba9c 100644
@@ -12,6 +12,7 @@
 #include <net/netfilter/nf_tables.h>
 #include <net/netfilter/nf_tables_offload.h>
 #include <net/netfilter/nf_dup_netdev.h>
+#include <net/netfilter/nf_recursion.h>
 
 static void nf_do_netdev_egress(struct sk_buff *skb, struct net_device *dev,
 				enum nf_dev_hooks hook)
net/netfilter/nft_fwd_netdev.c +1 -0
index eceab479bd8c4..84ae30cd208b7 100644
@@ -14,6 +14,7 @@
 #include <net/netfilter/nf_tables.h>
 #include <net/netfilter/nf_tables_offload.h>
 #include <net/netfilter/nf_dup_netdev.h>
+#include <net/netfilter/nf_recursion.h>
 #include <net/neighbour.h>
 #include <net/ip.h>
 
Signature · 1 line
2.53.0
author maintainer
#109 lore raw

PATCH 108/990 spi: pic32-sqi: fail transfer when the BD ring is exhausted

In reply to Greg Kroah-Hartman

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

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

From: Hongjian Dai <[email protected]>

[ Upstream commit 2066970324a1439e5a2e08c4599098367f8f82cc ]

pic32_sqi_one_transfer() silently stopped programming buffer descriptors when ring_desc_get() returned NULL and still returned success. The caller then marked the last programmed descriptor as the end of the list and started the DMA engine, so the hardware transferred only a prefix of the requested data while the message completed with status 0.

The ring holds PESQI_BD_COUNT (256) descriptors of at most PESQI_BD_BUF_LEN_MAX (256) bytes each, so messages larger than 64 KiB (or with enough SG entries) can exhaust it. Since the driver sets no max_message_size/max_transfer_size, the SPI core does not prevent this.

Return -ENOMEM instead, and set msg->status so the failure reaches the caller rather than being silently truncated.

---
 drivers/spi/spi-pic32-sqi.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/spi/spi-pic32-sqi.c +2 -1
index a6b5a0ed99c9e..6061e425d09c5 100644
@@ -297,7 +297,7 @@ static int pic32_sqi_one_transfer(struct pic32_sqi *sqi,
 		/* get ring descriptor */
 		rdesc = ring_desc_get(sqi);
 		if (!rdesc)
-			break;
+			return -ENOMEM;
 
 		bd = rdesc->bd;
 
@@ -387,6 +387,7 @@ static int pic32_sqi_one_message(struct spi_controller *host,
 		ret = pic32_sqi_one_transfer(sqi, msg, xfer);
 		if (ret) {
 			dev_err(&spi->dev, "xfer %p err\n", xfer);
+			msg->status = ret;
 			goto xfer_out;
 		}
 	}
Signature · 1 line
2.53.0
author maintainer
#110 lore raw

PATCH 109/990 bpf: Avoid changing callchain in bpf_get_stack_pe

In reply to Greg Kroah-Hartman

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

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

From: Jiri Olsa <[email protected]>

[ Upstream commit 347c1d722e3ea4ffa2850585f5c76c6e551eac83 ]

There's no need to modify the trace object bpf_get_stack_pe, we just need to pass the needed callchain length in separate argument.

This way we can have callchain pointers const and remove the trace->nr modification and restoration.

Assisted-by Codex:GPT-5.5

Stable-dep-of: 007fd460798b ("bpf: Clamp the trace length in __bpf_get_stack() again")

---
 kernel/bpf/stackmap.c | 36 +++++++++++++++---------------------
 1 file changed, 15 insertions(+), 21 deletions(-)
kernel/bpf/stackmap.c +15 -21
index 02b6b0e9cb6ce..2749985910855 100644
@@ -541,7 +541,7 @@ const struct bpf_func_proto bpf_get_stackid_proto = {
 	.arg3_type	= ARG_ANYTHING,
 };
 
-static __u64 count_kernel_ip(struct perf_callchain_entry *trace)
+static __u64 count_kernel_ip(const struct perf_callchain_entry *trace)
 {
 	__u64 nr_kernel = 0;
 
@@ -621,15 +621,15 @@ const struct bpf_func_proto bpf_get_stackid_proto_pe = {
 	.arg3_type	= ARG_ANYTHING,
 };
 
-static u32 callchain_store(struct perf_callchain_entry *trace, void *buf,
-			   u32 elem_size, u64 flags)
+static u32 callchain_store(const struct perf_callchain_entry *trace, u32 trace_nr,
+			   void *buf, u32 elem_size, u64 flags)
 {
 	bool user_build_id = flags & BPF_F_USER_BUILD_ID;
 	u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
-	u32 trace_nr, copy_len;
-	u64 *ips;
+	const u64 *ips;
+	u32 copy_len;
 
-	trace_nr = trace->nr - skip;
+	trace_nr = trace_nr - skip;
 	copy_len = trace_nr * elem_size;
 
 	ips = trace->ip + skip;
@@ -713,7 +713,7 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
 		goto err_fault;
 	}
 
-	trace_nr = callchain_store(trace, buf, elem_size, flags);
+	trace_nr = callchain_store(trace, trace->nr, buf, elem_size, flags);
 
 	/* trace should not be dereferenced after this point */
 	if (may_fault)
@@ -817,8 +817,8 @@ const struct bpf_func_proto bpf_get_task_stack_sleepable_proto = {
 	.arg4_type	= ARG_ANYTHING,
 };
 
-static int __bpf_get_stack_pe(struct perf_callchain_entry *trace, void *buf, u32 size,
-			      u64 flags)
+static int __bpf_get_stack_pe(const struct perf_callchain_entry *trace, u32 trace_nr,
+			      void *buf, u32 size, u64 flags)
 {
 	bool user_build_id = flags & BPF_F_USER_BUILD_ID;
 	u64 skip = flags & BPF_F_SKIP_FIELD_MASK;
@@ -834,12 +834,12 @@ static int __bpf_get_stack_pe(struct perf_callchain_entry *trace, void *buf, u32
 		return -EINVAL;
 
 	max_depth = stack_map_calculate_max_depth(size, elem_size, flags);
-	trace->nr = min_t(u32, trace->nr, max_depth);
+	trace_nr = min_t(u32, trace_nr, max_depth);
 
-	if (trace->nr < skip)
+	if (trace_nr < skip)
 		return -EFAULT;
 
-	nr_trace = callchain_store(trace, buf, elem_size, flags);
+	nr_trace = callchain_store(trace, trace_nr, buf, elem_size, flags);
 	return callchain_finalize(buf, size, nr_trace, elem_size, flags, false /* !may_fault */);
 }
 
@@ -847,8 +847,8 @@ BPF_CALL_4(bpf_get_stack_pe, struct bpf_perf_event_data_kern *, ctx,
 	   void *, buf, u32, size, u64, flags)
 {
 	struct pt_regs *regs = (struct pt_regs *)(ctx->regs);
+	const struct perf_callchain_entry *trace;
 	struct perf_event *event = ctx->event;
-	struct perf_callchain_entry *trace;
 	bool kernel, user;
 	int err = -EINVAL;
 	__u64 nr_kernel;
@@ -871,13 +871,7 @@ BPF_CALL_4(bpf_get_stack_pe, struct bpf_perf_event_data_kern *, ctx,
 	nr_kernel = count_kernel_ip(trace);
 
 	if (kernel) {
-		__u64 nr = trace->nr;
-
-		trace->nr = nr_kernel;
-		err = __bpf_get_stack_pe(trace, buf, size, flags);
-
-		/* restore nr */
-		trace->nr = nr;
+		err = __bpf_get_stack_pe(trace, nr_kernel, buf, size, flags);
 	} else { /* user */
 		u64 skip = flags & BPF_F_SKIP_FIELD_MASK;
 
@@ -885,7 +879,7 @@ BPF_CALL_4(bpf_get_stack_pe, struct bpf_perf_event_data_kern *, ctx,
 		if (skip > BPF_F_SKIP_FIELD_MASK)
 			goto clear;
 		flags = (flags & ~BPF_F_SKIP_FIELD_MASK) | skip;
-		err = __bpf_get_stack_pe(trace, buf, size, flags);
+		err = __bpf_get_stack_pe(trace, trace->nr, buf, size, flags);
 	}
 
 clear:
Signature · 1 line
2.53.0
author maintainer
#67 lore raw

PATCH 67/990 xfrm: zero-initialise km_event in the replay-notify path

In reply to Greg Kroah-Hartman

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

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

From: Shubham Antil <[email protected]>

[ Upstream commit e35a12dffd5da67b6ca12bd23eebdd0570592205 ]

xfrm_replay_notify(), xfrm_replay_notify_bmp() and xfrm_replay_notify_esn() declare a struct km_event on the stack and initialise only its .event and .data.aevent fields, leaving .seq and .portid uninitialised. build_aevent() then builds the XFRM_MSG_NEWAE message with those fields:

nlmsg_put(skb, c->portid, c->seq, ...)

so the netlink header of a replay event carries uninitialised stack values rather than defined ones. This was confirmed at runtime rather than by inspection alone: the .seq and .portid carried in that header hold values that nothing in the replay path assigns.

The request-driven paths set these header fields from the requester (xfrm_get_ae() / xfrm_new_ae()); only the kernel-originated replay path leaves them unset. Zero-initialise the event so the header fields are 0, the correct value for a kernel-originated notification.

Fixes f8cd54884e67 ("[IPSEC]: Sync series - core changes")
Assisted-by Claude:claude-opus-4-8
---
 net/xfrm/xfrm_replay.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
net/xfrm/xfrm_replay.c +3 -3
index dbdf8a39dffee..9394953247ab9 100644
@@ -40,7 +40,7 @@ static void xfrm_replay_notify_esn(struct xfrm_state *x, int event);
 
 void xfrm_replay_notify(struct xfrm_state *x, int event)
 {
-	struct km_event c;
+	struct km_event c = {};
 	/* we send notify messages in case
 	 *  1. we updated on of the sequence numbers, and the seqno difference
 	 *     is at least x->replay_maxdiff, in this case we also update the
@@ -304,7 +304,7 @@ static void xfrm_replay_advance_bmp(struct xfrm_state *x, __be32 net_seq)
 
 static void xfrm_replay_notify_bmp(struct xfrm_state *x, int event)
 {
-	struct km_event c;
+	struct km_event c = {};
 	struct xfrm_replay_state_esn *replay_esn = x->replay_esn;
 	struct xfrm_replay_state_esn *preplay_esn = x->preplay_esn;
 
@@ -356,7 +356,7 @@ static void xfrm_replay_notify_bmp(struct xfrm_state *x, int event)
 static void xfrm_replay_notify_esn(struct xfrm_state *x, int event)
 {
 	u32 seq_diff, oseq_diff;
-	struct km_event c;
+	struct km_event c = {};
 	struct xfrm_replay_state_esn *replay_esn = x->replay_esn;
 	struct xfrm_replay_state_esn *preplay_esn = x->preplay_esn;
 
Signature · 1 line
2.53.0
author maintainer
#68 lore raw

PATCH 68/990 batman-adv: avoid WARN_ON for orig_ifinfo allocation failure

In reply to Greg Kroah-Hartman

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

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

From: Deepanshu Kartikey <[email protected]>

[ Upstream commit dfa953ba5366b0a80c303700dab2bbcbdc5c27e9 ]

batadv_orig_ifinfo_new() returns NULL only when its GFP_ATOMIC allocation fails, which is a normal runtime condition and not a bug. batadv_v_ogm_forward() already handles this the same way, simply checking for NULL without a WARN_ON.

Do the same in batadv_iv_ogm_update_seqnos() to avoid a spurious WARN_ON splat when the allocation fails (e.g. under fault injection).

Fixes 7351a4822d42 ("batman-adv: split out router from orig_node")
Reported-by [email protected]
---
 net/batman-adv/bat_iv_ogm.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
net/batman-adv/bat_iv_ogm.c +1 -1
index 38320f6a1dd1f..26f2795fbc183 100644
@@ -1298,7 +1298,7 @@ batadv_iv_ogm_update_seqnos(const struct ethhdr *ethhdr,
 		return BATADV_NO_DUP;
 
 	orig_ifinfo = batadv_orig_ifinfo_new(orig_node, if_outgoing);
-	if (WARN_ON(!orig_ifinfo)) {
+	if (!orig_ifinfo) {
 		batadv_orig_node_put(orig_node);
 		return 0;
 	}
Signature · 1 line
2.53.0
author maintainer
#69 lore raw

PATCH 69/990 wifi: wext: Limit notifier event flushes to the devices netns

In reply to Greg Kroah-Hartman

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

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

From: Cosmin Ratiu <[email protected]>

[ Upstream commit 48c0045366bec142d053f7cf76fb9dd7127cd231 ]

With mlx5 netdev instance locking enabled, registering an IPoIB netdev calls the WEXT notifier while holding the instance mutex. Its call to wireless_nlevent_flush() takes net_rwsem to walk every namespace, completing the following lockdep dependency cycle:

netdev instance mutex -> net_rwsem (read) -> GID table mutex

    -> event_handler_rwsem (read) -> netdev instance mutex

RoCE GID enumeration takes the GID table mutex under net_rwsem. GID updates dispatch events under the table mutex, taking event_handler_rwsem. The IPoIB event handler takes the netdev instance mutex in ipoib_queue_work() to traverse child interfaces.

The all-namespace walk originated in the single global worker servicing per-namespace WEXT queues. The ordering fixes later reused that routine in netdevice notifiers to prevent delayed WEXT RTM_NEWLINK messages from following RTM_DELLINK or reporting stale interface flags. A notifier only needs to drain the affected device's namespace; there is no reason for it to walk and flush all namespaces.

Pass dev_net(dev) from both notifier callers and make the flush helper operate on that namespace. Keep the all-namespace walk and net_rwsem in the existing worker. This removes the instance-mutex -> net_rwsem dependency while retaining synchronous flushing from the notifiers.

It may seem strange that the fix for a lock cycle across multiple subsystems lies in a completely unrelated part of the code, but this seemed the most justified lock cycle edge to break.

Fixes 8f7b00307bf1 ("net/mlx5e: Convert mlx5 netdevs to instance locking")
---
 include/net/iw_handler.h |  8 +++++---
 net/wireless/core.c      |  2 +-
 net/wireless/wext-core.c | 33 +++++++++++++++++----------------
 3 files changed, 23 insertions(+), 20 deletions(-)
include/net/iw_handler.h +5 -3
index b80e474cb0aa9..632618d9ff937 100644
@@ -201,6 +201,8 @@
 #include <linux/wireless.h>		/* IOCTL user space API */
 #include <linux/if_ether.h>
 
+struct net;
+
 /***************************** VERSION *****************************/
 /*
  * This constant is used to know which version of the driver API is
@@ -411,10 +413,10 @@ struct iw_spy_data {
 void wireless_send_event(struct net_device *dev, unsigned int cmd,
 			 union iwreq_data *wrqu, const char *extra);
 #ifdef CONFIG_WEXT_CORE
-/* flush all previous wext events - if work is done from netdev notifiers */
-void wireless_nlevent_flush(void);
+/* Flush previous wext events in this netns from netdev notifiers. */
+void wireless_nlevent_flush(struct net *net);
 #else
-static inline void wireless_nlevent_flush(void) {}
+static inline void wireless_nlevent_flush(struct net *net) {}
 #endif
 
 /* We may need a function to send a stream of events to user space.
net/wireless/core.c +1 -1
index c7d4498682549..0661c432b4e58 100644
@@ -1762,7 +1762,7 @@ static int cfg80211_netdev_notifier_call(struct notifier_block *nb,
 		return NOTIFY_DONE;
 	}
 
-	wireless_nlevent_flush();
+	wireless_nlevent_flush(dev_net(dev));
 
 	return NOTIFY_OK;
 }
net/wireless/wext-core.c +17 -16
index 7b8e94214b072..7de96c3ffda8c 100644
@@ -343,32 +343,28 @@ static const int compat_event_type_size[] = {
 
 /* IW event code */
 
-void wireless_nlevent_flush(void)
+void wireless_nlevent_flush(struct net *net)
 {
 	struct sk_buff *skb;
-	struct net *net;
 
-	down_read(&net_rwsem);
-	for_each_net(net) {
-		while ((skb = skb_dequeue(&net->wext_nlevents)))
-			rtnl_notify(skb, net, 0, RTNLGRP_LINK, NULL,
-				    GFP_KERNEL);
-	}
-	up_read(&net_rwsem);
+	while ((skb = skb_dequeue(&net->wext_nlevents)))
+		rtnl_notify(skb, net, 0, RTNLGRP_LINK, NULL, GFP_KERNEL);
 }
 EXPORT_SYMBOL_GPL(wireless_nlevent_flush);
 
 static int wext_netdev_notifier_call(struct notifier_block *nb,
 				     unsigned long state, void *ptr)
 {
+	struct net_device *dev = netdev_notifier_info_to_dev(ptr);
+
 	/*
-	 * When a netdev changes state in any way, flush all pending messages
-	 * to avoid them going out in a strange order, e.g. RTM_NEWLINK after
-	 * RTM_DELLINK, or with IFF_UP after without IFF_UP during dev_close()
-	 * or similar - all of which could otherwise happen due to delays from
-	 * schedule_work().
+	 * When a netdev changes state in any way, flush all pending messages in
+	 * its network namespace to avoid them going out in a strange order,
+	 * e.g. RTM_NEWLINK after RTM_DELLINK, or with IFF_UP after without
+	 * IFF_UP during dev_close() or similar - all of which could otherwise
+	 * happen due to delays from schedule_work().
 	 */
-	wireless_nlevent_flush();
+	wireless_nlevent_flush(dev_net(dev));
 
 	return NOTIFY_OK;
 }
@@ -411,7 +407,12 @@ subsys_initcall(wireless_nlevent_init);
 /* Process events generated by the wireless layer or the driver. */
 static void wireless_nlevent_process(struct work_struct *work)
 {
-	wireless_nlevent_flush();
+	struct net *net;
+
+	down_read(&net_rwsem);
+	for_each_net(net)
+		wireless_nlevent_flush(net);
+	up_read(&net_rwsem);
 }
 
 static DECLARE_WORK(wireless_nlevent_work, wireless_nlevent_process);
Signature · 1 line
2.53.0
author maintainer
#70 lore raw

PATCH 70/990 fsnotify: preserve 64-bit pre-content ranges

In reply to Greg Kroah-Hartman

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

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

From: Avi Weiss <[email protected]>

[ Upstream commit 1dcf2be94b9be2d366a0d2b70c2b1c7ebccf1443 ]

vfs_fallocate() and remap_verify_area() pass 64-bit lengths to fsnotify_file_area_perm(), which truncates them to size_t on 32-bit systems.

Use 64 bit (unsigned) types throughout the entire pre-content notification chain to keep the full range. The userspace range field is already 64-bits.

Fixes 9740d17162de ("fsnotify: pass optional file access range in pre-content event")
---
 fs/notify/fanotify/fanotify.h    | 2 +-
 fs/notify/fsnotify.c             | 2 +-
 include/linux/fsnotify.h         | 4 ++--
 include/linux/fsnotify_backend.h | 6 +++---
 4 files changed, 7 insertions(+), 7 deletions(-)
fs/notify/fanotify/fanotify.h +1 -1
index 775f55080dd4d..aa19675452d7b 100644
@@ -443,7 +443,7 @@ struct fanotify_perm_event {
 	struct fanotify_event fae;
 	struct path path;
 	loff_t pos;			/* FANOTIFY_NO_RANGE if unavailable */
-	size_t count;
+	u64 count;
 	u32 response;			/* userspace answer to the event */
 	unsigned short state;		/* state of the event */
 	unsigned short watchdog_cnt;	/* already scanned by watchdog? */
fs/notify/fsnotify.c +1 -1
index cae0adce6d47a..f081bfba4dd92 100644
@@ -210,7 +210,7 @@ static inline __u32 fsnotify_object_watched(struct inode *inode, __u32 mnt_mask,
 
 /* Report pre-content event with optional range info */
 int fsnotify_pre_content(const struct path *path, const loff_t *ppos,
-			 size_t count)
+			 u64 count)
 {
 	struct file_range range;
 
include/linux/fsnotify.h +2 -2
index 28a9cb13fbfa3..c4461411dc55e 100644
@@ -135,7 +135,7 @@ int fsnotify_open_perm_and_set_mode(struct file *file);
  * fsnotify_file_area_perm - permission hook before access to file range
  */
 static inline int fsnotify_file_area_perm(struct file *file, int perm_mask,
-					  const loff_t *ppos, size_t count)
+					  const loff_t *ppos, u64 count)
 {
 	/*
 	 * filesystem may be modified in the context of permission events
@@ -213,7 +213,7 @@ static inline int fsnotify_open_perm_and_set_mode(struct file *file)
 }
 
 static inline int fsnotify_file_area_perm(struct file *file, int perm_mask,
-					  const loff_t *ppos, size_t count)
+					  const loff_t *ppos, u64 count)
 {
 	return 0;
 }
include/linux/fsnotify_backend.h +3 -3
index d67a893d75fa6..042f0e7f159d1 100644
@@ -322,7 +322,7 @@ struct fs_error_report {
 struct file_range {
 	const struct path *path;
 	loff_t pos;
-	size_t count;
+	u64 count;
 };
 
 static inline const struct path *file_range_path(const struct file_range *range)
@@ -922,12 +922,12 @@ static inline void fsnotify_init_event(struct fsnotify_event *event)
 	INIT_LIST_HEAD(&event->list);
 }
 int fsnotify_pre_content(const struct path *path, const loff_t *ppos,
-			 size_t count);
+			 u64 count);
 
 #else
 
 static inline int fsnotify_pre_content(const struct path *path,
-				       const loff_t *ppos, size_t count)
+				       const loff_t *ppos, u64 count)
 {
 	return 0;
 }
Signature · 1 line
2.53.0
author maintainer
#71 lore raw

PATCH 71/990 wifi: ath9k_htc: start ANI when an AP interface begins to beacon

In reply to Greg Kroah-Hartman

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

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

From: Mehmet Fide <[email protected]>

[ Upstream commit 5c1b202d67a212c87e7389aaa093ce77828fa98f ]

ath9k_htc_vif_reconfig() re-arms ANI after a channel change when an AP interface beacons. mac80211 configures the channel before it enables the beacon, so during a normal AP start that never triggers, and the start from add_interface that the previous patch removed was cancelled by the same channel configuration: with hostapd, ANI and the periodic calibration it drives did not run in AP mode until a later channel change.

Start ANI when the beacon is enabled. The channel and its calibration data are in place by then, which is the state vif_reconfig() re-arms it in, and remove_interface() already stops it with the last AP interface.

---
 drivers/net/wireless/ath/ath9k/htc_drv_main.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/net/wireless/ath/ath9k/htc_drv_main.c +3 -0
index 0d6272ac0dac8..611d17202eba2 100644
@@ -1554,6 +1554,9 @@ static void ath9k_htc_bss_info_changed(struct ieee80211_hw *hw,
 		ath9k_htc_set_tsfadjust(priv, vif);
 		priv->cur_beacon_conf.enable_beacon = 1;
 		ath9k_htc_beacon_config(priv, vif);
+		if (priv->ah->opmode == NL80211_IFTYPE_AP &&
+		    !test_bit(ATH_OP_ANI_RUN, &common->op_flags))
+			ath9k_htc_start_ani(priv);
 	}
 
 	if ((changed & BSS_CHANGED_BEACON_ENABLED) && !bss_conf->enable_beacon) {
Signature · 1 line
2.53.0
author maintainer
#62 lore raw

PATCH 62/990 net/9p: Replace strlen() strcpy() pair with strscpy()

In reply to Greg Kroah-Hartman

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

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

From: David Laight <[email protected]>

[ Upstream commit cc8b15a2c435bd1caf19741ba85286846a115764 ]

Use the result of strscpy() for the overflow check.

Message-ID: <[email protected]>

Stable-dep-of: 37dce65a0b43 ("9p: use fc->net_ns for network namespace in RDMA and socket transports")

---
 net/9p/trans_fd.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
net/9p/trans_fd.c +2 -4
index 8a03e62992508..f31b2a81ef8bd 100644
@@ -941,14 +941,12 @@ p9_fd_create_unix(struct p9_client *client, struct fs_context *fc)
 	if (!addr || !strlen(addr))
 		return -EINVAL;
 
-	if (strlen(addr) >= UNIX_PATH_MAX) {
+	sun_server.sun_family = PF_UNIX;
+	if (strscpy(sun_server.sun_path, addr) < 0) {
 		pr_err("%s (%d): address too long: %s\n",
 		       __func__, task_pid_nr(current), addr);
 		return -ENAMETOOLONG;
 	}
-
-	sun_server.sun_family = PF_UNIX;
-	strcpy(sun_server.sun_path, addr);
 	err = __sock_create(current->nsproxy->net_ns, PF_UNIX,
 			    SOCK_STREAM, 0, &csocket, 1);
 	if (err < 0) {
Signature · 1 line
2.53.0
author maintainer
#112 lore raw

PATCH 111/990 bpf: Avoid changing callchain in bpf_get_stackid_pe

In reply to Greg Kroah-Hartman

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

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

From: Jiri Olsa <[email protected]>

[ Upstream commit a74594607a0b310c1533e713b9097cc1cbbb85bf ]

There's no need to modify the trace object bpf_get_stackid_pe, we just need to pass the needed callchain length in separate argument.

This way we can have callchain pointers const and remove the trace->nr modification and restoration.

Assisted-by Codex:GPT-5.5

Stable-dep-of: a08ba2ab79df ("bpf: Clamp the trace length before the skip test in stackid_init()")

---
 kernel/bpf/stackmap.c | 39 +++++++++++++++++----------------------
 1 file changed, 17 insertions(+), 22 deletions(-)
kernel/bpf/stackmap.c +17 -22
index f56333c9a8053..128c8d61070e4 100644
@@ -386,7 +386,7 @@ get_callchain_entry_for_task(struct task_struct *task, u32 max_depth)
 
 struct stackid {
 	struct stack_map_bucket *bucket;
-	u64 *ips;
+	const u64 *ips;
 	u32  nr;
 	u32  len;
 	u32  hash;
@@ -395,21 +395,21 @@ struct stackid {
 };
 
 static int stackid_init(struct stackid *stackid, struct bpf_map *map,
-			struct perf_callchain_entry *trace, u64 flags)
+			const struct perf_callchain_entry *trace, u32 trace_nr, u64 flags)
 {
 	struct bpf_stack_map *smap = container_of(map, struct bpf_stack_map, map);
 	u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
 	u32 max_depth;
 
-	if (trace->nr <= skip)
+	if (trace_nr <= skip)
 		/* skipping more than usable stack trace */
 		return -EFAULT;
 
 	max_depth = stack_map_calculate_max_depth(map->value_size, stack_map_data_size(map), flags);
-	stackid->nr = min_t(u32, trace->nr - skip, max_depth - skip);
+	stackid->nr = min_t(u32, trace_nr - skip, max_depth - skip);
 	stackid->len = stackid->nr * sizeof(u64);
 	stackid->ips = trace->ip + skip;
-	stackid->hash = jhash2((u32 *)stackid->ips, stackid->len / sizeof(u32), 0);
+	stackid->hash = jhash2((const u32 *)stackid->ips, stackid->len / sizeof(u32), 0);
 	stackid->id = stackid->hash & (smap->n_buckets - 1);
 	stackid->bucket = READ_ONCE(smap->buckets[stackid->id]);
 	stackid->hash_matches = stackid->bucket && stackid->bucket->hash == stackid->hash;
@@ -417,11 +417,12 @@ static int stackid_init(struct stackid *stackid, struct bpf_map *map,
 }
 
 static int stackid_fastpath(struct stackid *stackid, struct bpf_map *map,
-			    struct perf_callchain_entry *trace, u64 flags)
+			    const struct perf_callchain_entry *trace, u32 trace_nr,
+			    u64 flags)
 {
 	int err;
 
-	err = stackid_init(stackid, map, trace, flags);
+	err = stackid_init(stackid, map, trace, trace_nr, flags);
 	if (err)
 		return err;
 
@@ -520,7 +521,7 @@ BPF_CALL_3(bpf_get_stackid, struct pt_regs *, regs, struct bpf_map *, map,
 			/* couldn't fetch the stack trace */
 			return -EFAULT;
 
-		err = stackid_fastpath(&stackid, map, trace, flags);
+		err = stackid_fastpath(&stackid, map, trace, trace->nr, flags);
 		if (err != -ENOENT)
 			return err;
 
@@ -556,12 +557,13 @@ static __u64 count_kernel_ip(const struct perf_callchain_entry *trace)
 BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx,
 	   struct bpf_map *, map, u64, flags)
 {
+	const struct perf_callchain_entry *trace;
 	struct perf_event *event = ctx->event;
 	struct stack_map_bucket *new_bucket;
-	struct perf_callchain_entry *trace;
 	struct stackid stackid;
 	bool kernel, user;
 	__u64 nr_kernel;
+	u32 trace_nr;
 	int ret;
 
 	/* perf_sample_data doesn't have callchain, use bpf_get_stackid */
@@ -581,13 +583,13 @@ BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx,
 		return -EFAULT;
 
 	nr_kernel = count_kernel_ip(trace);
-	__u64 nr = trace->nr; /* save original */
 
 	if (kernel) {
-		trace->nr = nr_kernel;
+		trace_nr = nr_kernel;
 	} else { /* user */
 		u64 skip = flags & BPF_F_SKIP_FIELD_MASK;
 
+		trace_nr = trace->nr;
 		skip += nr_kernel;
 		if (skip > BPF_F_SKIP_FIELD_MASK)
 			return -EFAULT;
@@ -595,21 +597,14 @@ BPF_CALL_3(bpf_get_stackid_pe, struct bpf_perf_event_data_kern *, ctx,
 		flags = (flags & ~BPF_F_SKIP_FIELD_MASK) | skip;
 	}
 
-	ret = stackid_fastpath(&stackid, map, trace, flags);
+	ret = stackid_fastpath(&stackid, map, trace, trace_nr, flags);
 	if (ret != -ENOENT)
-		goto out;
+		return ret;
 
 	new_bucket = stackid_new_bucket(&stackid, map);
-	if (new_bucket) {
-		trace->nr = nr;
+	if (new_bucket)
 		return stackid_install(&stackid, map, new_bucket, flags);
-	}
-	ret = -ENOMEM;
-
-out:
-	/* restore nr */
-	trace->nr = nr;
-	return ret;
+	return -ENOMEM;
 }
 
 const struct bpf_func_proto bpf_get_stackid_proto_pe = {
Signature · 1 line
2.53.0
author maintainer
#121 lore raw

PATCH 120/990 bpf: Limit the SRH length in bpf_lwt_seg6_adjust_srh()

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit ac159f39b252971141c49b68a27de0b637debfad ]

bpf_lwt_seg6_adjust_srh() lets an End.BPF prog change the size of the TLVs in the SRH. The helper keeps the SRH length in srh_state->hdrlen, in bytes and without the first 8 bytes. Later seg6_bpf_has_valid_srh() writes it to srh->hdrlen, an 8-bit field in units of 8 bytes. But srh_state->hdrlen has no upper limit, and the cast to u8 can truncate it. After that, seg6_validate_srh() gets the SRH length from srh->hdrlen, and thus it can accept the SRH. Then srh->hdrlen is too small, and a parser reads TLVs as the subsequent header.

Return -EFAULT when the new srh_state->hdrlen is larger than 2040, the largest length that srh->hdrlen can hold. To replace a TLV in the largest SRH, a prog can no longer add bytes first. It must remove bytes first.

Fixes fe94cc290f53 ("bpf: Add IPv6 Segment Routing helpers")
---
 net/core/filter.c | 3 +++
 1 file changed, 3 insertions(+)
net/core/filter.c +3 -0
index 2df3e5cfc3fcd..a40e3641ec9b4 100644
@@ -6863,6 +6863,9 @@ BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset,
 		return -EFAULT;
 	if (unlikely(len < 0 && (void *)((char *)ptr - len) > srh_end))
 		return -EFAULT;
+	/* The length field of the SRH has 8 bits, in units of 8 bytes. */
+	if (unlikely(len > (U8_MAX << 3) - srh_state->hdrlen))
+		return -EFAULT;
 
 	if (len > 0) {
 		ret = skb_cow_head(skb, len);
Signature · 1 line
2.53.0
author maintainer
#122 lore raw

PATCH 121/990 bpf: Dont look for the SRH again in the End.BPF helpers

In reply to Greg Kroah-Hartman

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

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

From: Alexei Starovoitov <[email protected]>

[ Upstream commit 45bcc58d576705d2c001332766e10313f1c55bad ]

A packet can have two SRHs. Thus input_action_end_bpf() uses IP6_FH_F_SKIP_RH to skip routing headers with segments_left 0. The helpers bpf_lwt_seg6_store_bytes() and bpf_lwt_seg6_adjust_srh() can reallocate the head of the skb. Thus they look for the SRH again, but without this flag.

  +------------------------+ <- the helpers: srh_state->srh
  | SRH 1, segments_left 0 |
  +------------------------+ <- input_action_end_bpf(): srh_state->srh
  | SRH 2                  |    and srh_state->hdrlen
  +------------------------+

Then the helpers check offset against the wrong limits. If a helper changes TLVs, seg6_bpf_has_valid_srh() writes the length of SRH 2 to SRH 1.

Neither helper changes the offset of the SRH from skb->data. Calculate the new address from this offset. To add IP6_FH_F_SKIP_RH is not sufficient, because advance_nextseg() can set segments_left of SRH 2 to 0. The helper bpf_lwt_seg6_action() can change the headers and still looks for the SRH.

Fixes fbbc5bc2ab8c ("seg6: ignore routing header with segments left equal to 0")
---
 net/core/filter.c | 12 ++++++------
 1 file changed, 6 insertions(+), 6 deletions(-)
net/core/filter.c +6 -6
index a40e3641ec9b4..50245c98d8aee 100644
@@ -6708,12 +6708,13 @@ BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset,
 		this_cpu_ptr(&seg6_bpf_srh_states);
 	struct ipv6_sr_hdr *srh = srh_state->srh;
 	void *srh_tlvs, *srh_end, *ptr;
-	int srhoff = 0;
+	int srhoff;
 
 	lockdep_assert_held(&srh_state->bh_lock);
 	if (srh == NULL)
 		return -EINVAL;
 
+	srhoff = (unsigned char *)srh - skb->data;
 	srh_tlvs = (void *)((char *)srh + ((srh->first_segment + 1) << 4));
 	srh_end = (void *)((char *)srh + sizeof(*srh) + srh_state->hdrlen);
 
@@ -6726,8 +6727,7 @@ BPF_CALL_4(bpf_lwt_seg6_store_bytes, struct sk_buff *, skb, u32, offset,
 
 	if (unlikely(bpf_try_make_writable(skb, offset + len)))
 		return -EFAULT;
-	if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
-		return -EINVAL;
+	/* The head may have moved. */
 	srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
 
 	memcpy(skb->data + offset, from, len);
@@ -6846,13 +6846,14 @@ BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset,
 	struct ipv6_sr_hdr *srh = srh_state->srh;
 	void *srh_end, *srh_tlvs, *ptr;
 	struct ipv6hdr *hdr;
-	int srhoff = 0;
+	int srhoff;
 	int ret;
 
 	lockdep_assert_held(&srh_state->bh_lock);
 	if (unlikely(srh == NULL))
 		return -EINVAL;
 
+	srhoff = (unsigned char *)srh - skb->data;
 	srh_tlvs = (void *)((unsigned char *)srh + sizeof(*srh) +
 			((srh->first_segment + 1) << 4));
 	srh_end = (void *)((unsigned char *)srh + sizeof(*srh) +
@@ -6884,8 +6885,7 @@ BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset,
 	hdr = (struct ipv6hdr *)skb->data;
 	hdr->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
 
-	if (ipv6_find_hdr(skb, &srhoff, IPPROTO_ROUTING, NULL, NULL) < 0)
-		return -EINVAL;
+	/* The bytes in front of offset have moved together with skb->data. */
 	srh_state->srh = (struct ipv6_sr_hdr *)(skb->data + srhoff);
 	srh_state->hdrlen += len;
 	srh_state->valid = false;
Signature · 1 line
2.53.0
author maintainer
#123 lore raw

PATCH 122/990 bpf: Move the MAC header in bpf_lwt_seg6_adjust_srh()

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit 0fcb3f11a93d740e7f9ae1aeb48fe4d25838be18 ]

bpf_skb_net_hdr_push() and bpf_skb_net_hdr_pop() change skb->data and skb->mac_header by len. That is correct in a tc prog, where skb->data is the MAC header. But bpf_lwt_seg6_adjust_srh() calls them in an End.BPF prog, where skb->data is the network header. The MAC header does not move:

  before push  |       free       | MAC header   | IPv6 | SRH | payload
               ^ head             ^ mac_header   ^ data
  today        |       free       | MAC h| IPv6 | SRH   + len | payload
               ^ head     ^ mac_header   ^ data
  this patch   |   free   | MAC header   | IPv6 | SRH   + len | payload
               ^ head     ^ mac_header   ^ data

Users of skb_mac_header() get incorrect bytes until __dev_queue_xmit() sets skb->mac_header again. skb_cow_head() reserves only len bytes. Thus the 16-bit offset skb->mac_header can wrap. A push also changes the "not set" value. In both cases skb_mac_header() points after the skb.

Move the MAC header too. Pass len + skb->mac_len to skb_cow_head(). Keep the "not set" value. The second Fixes tag is for this case. Since that commit an End.BPF prog can get an skb with skb->mac_header not set.

Fixes fe94cc290f53 ("bpf: Add IPv6 Segment Routing helpers")
Fixes 20a081b7984c ("seg6: add VRF support for SRv6 End.DT6 behavior")
---
 net/core/filter.c | 21 ++++++++++++++++++++-
 1 file changed, 20 insertions(+), 1 deletion(-)
net/core/filter.c +20 -1
index 50245c98d8aee..84d5d7e456889 100644
@@ -6843,6 +6843,7 @@ BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset,
 {
 	struct seg6_bpf_srh_state *srh_state =
 		this_cpu_ptr(&seg6_bpf_srh_states);
+	bool mac_set = skb_mac_header_was_set(skb);
 	struct ipv6_sr_hdr *srh = srh_state->srh;
 	void *srh_end, *srh_tlvs, *ptr;
 	struct ipv6hdr *hdr;
@@ -6868,20 +6869,38 @@ BPF_CALL_3(bpf_lwt_seg6_adjust_srh, struct sk_buff *, skb, u32, offset,
 	if (unlikely(len > (U8_MAX << 3) - srh_state->hdrlen))
 		return -EFAULT;
 
+	/*
+	 * skb->data is the network header here. The MAC header is in front of
+	 * it, so bpf_skb_net_hdr_push() and bpf_skb_net_hdr_pop() do not move
+	 * it with the other headers.
+	 */
 	if (len > 0) {
-		ret = skb_cow_head(skb, len);
+		ret = skb_cow_head(skb, len + skb->mac_len);
 		if (unlikely(ret < 0))
 			return ret;
 
+		/* The push can write over the MAC header, so move it first. */
+		if (mac_set)
+			memmove(skb->data - len - skb->mac_len,
+				skb_mac_header(skb), skb->mac_len);
 		ret = bpf_skb_net_hdr_push(skb, offset, len);
 	} else {
 		ret = bpf_skb_net_hdr_pop(skb, offset, -1 * len);
+		/* The pop has added -len to skb->mac_header. */
+		if (likely(!ret) && mac_set)
+			memmove(skb->data - skb->mac_len,
+				skb_mac_header(skb) + len, skb->mac_len);
 	}
 
 	bpf_compute_data_pointers(skb);
 	if (unlikely(ret < 0))
 		return ret;
 
+	if (mac_set)
+		skb_set_mac_header(skb, -skb->mac_len);
+	else
+		skb_unset_mac_header(skb);
+
 	hdr = (struct ipv6hdr *)skb->data;
 	hdr->payload_len = htons(skb->len - sizeof(struct ipv6hdr));
 
Signature · 1 line
2.53.0
author maintainer
#124 lore raw

PATCH 123/990 bpf: Dont leave a stale MAC header in bpf_lwt_push_ip_encap()

In reply to Greg Kroah-Hartman

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

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

From: Alexei Starovoitov <[email protected]>

[ Upstream commit 701ffd202b9e32942c8cfc065c9fe76ceaccc302 ]

With BPF_LWT_ENCAP_IP, bpf_lwt_push_encap() pushes a new IP header. The new header overwrites the MAC header of a received skb. But skb->mac_header continues to point to the same bytes. Code that reads the MAC header after the push, for example netfilter, gets bytes of the new header.

  before the push                        | MAC header  | old IP | payload
                                         ^ mac_header  ^ network_header
  today                            | new header        | old IP | payload
                    network_header ^     ^ mac_header
  this patch, lwt_in | MAC header  | new header        | old IP | payload
                     ^ mac_header  ^ network_header
  this patch, lwt_xmit             | new header        | old IP | payload

network_header ^ mac_header is not set

For lwt_in, move the MAC header in front of the new header before the memcpy(), as __seg6_do_srh_encap() does. skb_cow_head() already reserves len + skb->mac_len bytes.

For lwt_xmit, the output path makes a new MAC header. Thus mark skb->mac_header as not set. This is the state of a locally generated skb.

Fixes 52f278774e79 ("bpf: implement BPF_LWT_ENCAP_IP mode in bpf_lwt_push_encap")
---
 net/core/lwt_bpf.c | 8 ++++++++
 1 file changed, 8 insertions(+)
net/core/lwt_bpf.c +8 -0
index 953237bca36b6..7e011fd3a60ff 100644
@@ -645,6 +645,14 @@ int bpf_lwt_push_ip_encap(struct sk_buff *skb, void *hdr, u32 len, bool ingress)
 	if (ingress)
 		skb_postpush_rcsum(skb, iph, len);
 	skb_reset_network_header(skb);
+	/*
+	 * The new header goes over the MAC header. On ingress move it first.
+	 * On egress the packet gets a new one, so forget the old one.
+	 */
+	if (ingress)
+		skb_mac_header_rebuild(skb);
+	else
+		skb_unset_mac_header(skb);
 	if (is_udp_tunnel) {
 		size_t iph_sz = ipv4 ? iph->ihl * 4 : sizeof(struct ipv6hdr);
 
Signature · 1 line
2.53.0
author maintainer
#125 lore raw

PATCH 124/990 bpf: Reset skb->cb after an lwt prog pushes an IP header

In reply to Greg Kroah-Hartman

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

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

From: Alexei Starovoitov <[email protected]>

[ Upstream commit b3ad42f6183286ab376389a5d26edf7ee3bdba27 ]

IPCB(skb)->opt holds the offsets from the network header to the IPv4 options. But bpf_lwt_push_ip_encap() moves the network header and does not change IPCB(skb). Then ip_forward_options() and __ip_options_echo() use the old offsets on the pushed header. Thus the kernel corrupts the skb and the stack. If the family changes, the kernel also reads IP6CB(skb) as IPCB(skb), or the reverse. With CONFIG_IPV6_MIP6, it reads IPSKB_FORWARDED as frag_max_size and adds a needless fragment header.

Reset skb->cb after the prog. bpf_lwt_push_ip_encap() cannot do it, because bpf_prog_run_save_cb() can restore skb->cb. For IPv4 in IPv4, clear IPCB(skb)->opt as ip_tunnel_xmit() does. If the family changes, clear the cb of the new family but keep iif, because ip6_forward() gets the input device from it. Behind a VRF, skb->skb_iif is the VRF device and cannot replace iif. Do nothing for IPv6 in IPv6, as in seg6_do_srh_encap().

Do the reset in bpf_input() only after a push. Without a push, ip_forward_options() needs the offsets. Do it in bpf_xmit() before each reroute, because an lwt_xmit prog can also change the options. Thus after a reroute without a push, ip_options_fragment() leaves the options in all fragments, and ICMP errors echo none. After BPF_OK or BPF_REDIRECT the skb goes to a device, thus bpf_xmit() does no reset. The inner IPv4 checksum can still be wrong after ip_rcv_options() changes an option.

Fixes 52f278774e79 ("bpf: implement BPF_LWT_ENCAP_IP mode in bpf_lwt_push_encap")
---
 net/core/lwt_bpf.c | 33 +++++++++++++++++++++++++++++++++
 1 file changed, 33 insertions(+)
net/core/lwt_bpf.c +33 -0
index 7e011fd3a60ff..f215978d10a3b 100644
@@ -86,6 +86,32 @@ static int run_lwt_bpf(struct sk_buff *skb, struct bpf_lwt_prog *lwt,
 	return ret;
 }
 
+/*
+ * skb->cb still describes the IP header that was the first one before the
+ * prog ran. The option offsets in IPCB(skb)->opt are wrong for a pushed
+ * header, and a header of the other family needs the other layout. iif
+ * stays: behind a VRF skb->skb_iif is the L3 master and not the port.
+ * bpf_lwt_push_encap() cannot do this, because bpf_prog_run_save_cb() can
+ * restore skb->cb after the prog.
+ */
+static void bpf_lwt_reset_cb(struct sk_buff *skb, __be16 proto)
+{
+	int iif;
+
+	if (skb->protocol == proto) {
+		if (proto == htons(ETH_P_IP))
+			memset(&IPCB(skb)->opt, 0, sizeof(IPCB(skb)->opt));
+	} else if (skb->protocol == htons(ETH_P_IP)) {
+		iif = IP6CB(skb)->iif;
+		memset(IPCB(skb), 0, sizeof(*IPCB(skb)));
+		IPCB(skb)->iif = iif;
+	} else {
+		iif = IPCB(skb)->iif;
+		memset(IP6CB(skb), 0, sizeof(*IP6CB(skb)));
+		IP6CB(skb)->iif = iif;
+	}
+}
+
 static int bpf_lwt_input_reroute(struct sk_buff *skb)
 {
 	enum skb_drop_reason reason;
@@ -120,6 +146,8 @@ static int bpf_lwt_input_reroute(struct sk_buff *skb)
 static int bpf_input(struct sk_buff *skb)
 {
 	struct dst_entry *dst = skb_dst(skb);
+	__be16 proto = skb->protocol;
+	unsigned int len = skb->len;
 	struct bpf_lwt *bpf;
 	int ret;
 
@@ -128,6 +156,9 @@ static int bpf_input(struct sk_buff *skb)
 		ret = run_lwt_bpf(skb, &bpf->in, dst, NO_REDIRECT);
 		if (ret < 0)
 			return ret;
+		/* An lwt_in prog can change the length only with a push. */
+		if (skb->len != len)
+			bpf_lwt_reset_cb(skb, proto);
 		if (ret == BPF_LWT_REROUTE)
 			return bpf_lwt_input_reroute(skb);
 	}
@@ -307,6 +338,8 @@ static int bpf_xmit(struct sk_buff *skb)
 		case BPF_REDIRECT:
 			return LWTUNNEL_XMIT_DONE;
 		case BPF_LWT_REROUTE:
+			/* An lwt_xmit prog can also write to the options. */
+			bpf_lwt_reset_cb(skb, proto);
 			return bpf_lwt_xmit_reroute(skb);
 		default:
 			return ret;
Signature · 1 line
2.53.0
author maintainer
#126 lore raw

PATCH 125/990 bpf: Require BPF_LWT_REROUTE when an lwt_in prog changes the protocol

In reply to Greg Kroah-Hartman

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

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

From: Alexei Starovoitov <[email protected]>

[ Upstream commit d9618a6196953718f7470de5d2e84121bed063f7 ]

When an lwt_in prog returns BPF_OK, bpf_input() calls orig_input(), the input handler of the route. This handler is for one IP version and needs a dst of the same family. But BPF_LWT_ENCAP_IP lets the prog push a header of the other IP version and thus change skb->protocol. Then the handler reads and changes a header of the other IP version. The push of an SRH also replaces the dst, because seg6_lookup_nexthop() puts an rt6_info into the skb. Then ip_forward() uses the rt6_info as a struct rtable.

Drop the skb with -EINVAL when skb->protocol changes, as bpf_xmit() does. Drop it also when the family of the dst changes, because skb->protocol does not always show this change. Today no such skb leaves as the prog made it. A prog works as before if it returns BPF_LWT_REROUTE, or if it pushes an SRH on an IPv6 route.

The commit in the first Fixes tag lets a prog change skb->protocol. The commit in the second tag adds the check to bpf_xmit() only.

Fixes 52f278774e79 ("bpf: implement BPF_LWT_ENCAP_IP mode in bpf_lwt_push_encap")
Fixes 3bd0b15281af ("bpf: add handling of BPF_LWT_REROUTE to lwt_bpf.c")
---
 net/core/lwt_bpf.c | 10 ++++++++++
 1 file changed, 10 insertions(+)
net/core/lwt_bpf.c +10 -0
index f215978d10a3b..982599bb41c97 100644
@@ -161,6 +161,16 @@ static int bpf_input(struct sk_buff *skb)
 			bpf_lwt_reset_cb(skb, proto);
 		if (ret == BPF_LWT_REROUTE)
 			return bpf_lwt_input_reroute(skb);
+		/*
+		 * orig_input() is for the old protocol only, see bpf_xmit().
+		 * It also needs a dst of the old family. BPF_LWT_ENCAP_SEG6
+		 * puts an IPv6 dst into the skb.
+		 */
+		if (skb->protocol != proto ||
+		    skb_dst(skb)->ops->family != dst->ops->family) {
+			kfree_skb(skb);
+			return -EINVAL;
+		}
 	}
 
 	if (unlikely(!dst->lwtstate->orig_input)) {
Signature · 1 line
2.53.0
author maintainer
#127 lore raw

PATCH 126/990 bpf: Move the transport header with the moved headers

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit a9d08fe60fa728ce0e3a99085241e8e790fb14c6 ]

bpf_skb_net_hdr_pop() removes len bytes at offset off. bpf_skb_net_hdr_push() does the opposite.

           skb->data       off
  before   | A             | removed | B            |
  after              | A             | B            |
                     skb->data       off

mac_header and network_header move with A. transport_header moves only when it is equal to network_header. inner_transport_header never moves. This is correct only for a header in B. In bpf_lwt_seg6_adjust_srh() transport_header is in A. bpf_skb_adjust_room() can remove both transport headers. With an incorrect header offset, the stack can drop the skb or read outside of it.

Also move transport_header with A when it is in A. Set it to offset off when it is in the removed bytes. In BPF_ADJ_ROOM_MAC mode it is then equal to network_header. Do not unset it, because skb_gso_validate_mac_len() uses it without a check. After a removal, set inner_transport_header to off when it is not in B and skb->encapsulation is set. A has only outer headers.

Fixes fe94cc290f53 ("bpf: Add IPv6 Segment Routing helpers")
Fixes 868d523535c2 ("bpf: add bpf_skb_adjust_room encap flags")
---
 net/core/filter.c | 37 +++++++++++++++++++++++++++++++------
 1 file changed, 31 insertions(+), 6 deletions(-)
net/core/filter.c +31 -6
index 84d5d7e456889..503ca33402840 100644
@@ -3363,9 +3363,25 @@ static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len)
 	return 0;
 }
 
+/*
+ * bpf_skb_net_hdr_push() inserts bytes at @off, bpf_skb_net_hdr_pop() removes
+ * bytes at @off. Both move the bytes in front of @off together with skb->data,
+ * and leave the rest of the packet where it is. Return true if the transport
+ * header is in the part that moves. A transport header that is equal to the
+ * network header stays equal to it.
+ */
+static bool bpf_skb_trans_hdr_moves(const struct sk_buff *skb, u32 off)
+{
+	if (skb->transport_header == skb->network_header)
+		return true;
+
+	return skb_transport_header_was_set(skb) &&
+	       (u32)skb_transport_offset(skb) < off;
+}
+
 static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len)
 {
-	bool trans_same = skb->transport_header == skb->network_header;
+	bool trans_moves = bpf_skb_trans_hdr_moves(skb, off);
 	int ret;
 
 	/* There's no need for __skb_push()/__skb_pull() pair to
@@ -3376,8 +3392,8 @@ static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len)
 	if (likely(!ret)) {
 		skb->mac_header -= len;
 		skb->network_header -= len;
-		if (trans_same)
-			skb->transport_header = skb->network_header;
+		if (trans_moves)
+			skb->transport_header -= len;
 	}
 
 	return ret;
@@ -3385,7 +3401,7 @@ static int bpf_skb_net_hdr_push(struct sk_buff *skb, u32 off, u32 len)
 
 static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len)
 {
-	bool trans_same = skb->transport_header == skb->network_header;
+	bool trans_moves = bpf_skb_trans_hdr_moves(skb, off);
 	int ret;
 
 	/* Same here, __skb_push()/__skb_pull() pair not needed. */
@@ -3393,8 +3409,17 @@ static int bpf_skb_net_hdr_pop(struct sk_buff *skb, u32 off, u32 len)
 	if (likely(!ret)) {
 		skb->mac_header += len;
 		skb->network_header += len;
-		if (trans_same)
-			skb->transport_header = skb->network_header;
+		if (trans_moves) {
+			skb->transport_header += len;
+		} else if (skb_transport_header_was_set(skb) &&
+			   skb_transport_offset(skb) < (int)off) {
+			/* It was in the removed bytes or before skb->data. */
+			skb_set_transport_header(skb, off);
+		}
+		/* Do not leave the inner transport header in front of @off. */
+		if (skb->encapsulation &&
+		    skb_inner_transport_offset(skb) < (int)off)
+			skb_set_inner_transport_header(skb, off);
 	}
 
 	return ret;
Signature · 1 line
2.53.0
author maintainer
#128 lore raw

PATCH 127/990 bpf: Check the offset in bpf_skb_generic_{push,pop}()

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit ee36c9aa44ef300cd651074bd97552b229337f85 ]

To make room for len bytes at offset off, bpf_skb_generic_push() moves the first off bytes and clears len bytes after them. It assumes that the first off bytes are in the linear part. But in bpf_skb_adjust_room() off can be the end of the IP header, and this header can be in a frag. Then the function reads and writes after skb->tail, and can damage skb_shared_info.

bpf_skb_generic_pop() checks off + len, but this u32 sum can wrap to a small value. bpf_skb_adjust_room() and bpf_skb_change_proto() calculate off from skb_mac_header_len(). This length is a very large u32 when network_header < mac_header. Then the check can pass, and memmove() reads and writes far outside the skb.

Return -ENOMEM from both functions, like the present check, when off > skb->len. Thus the sum cannot wrap. In bpf_skb_generic_push() also pull the first off bytes into the linear part. Now bpf_skb_adjust_room() fails when a prog grows an skb that ends before off. network_header stays wrong.

Fixes 6578171a7ff0 ("bpf: add bpf_skb_change_proto helper")
Fixes 2be7e212d541 ("bpf: add bpf_skb_adjust_room helper")
---
 net/core/filter.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
net/core/filter.c +7 -2
index 503ca33402840..c6677657656c9 100644
@@ -3330,6 +3330,10 @@ static void bpf_skb_change_protocol(struct sk_buff *skb, u16 proto)
 
 static int bpf_skb_generic_push(struct sk_buff *skb, u32 off, u32 len)
 {
+	/* The bytes in front of @off are moved with skb->data. */
+	if (unlikely(off > skb->len || !pskb_may_pull(skb, off)))
+		return -ENOMEM;
+
 	/* Caller already did skb_cow() with meta_len+len as headroom,
 	 * so no need to do it here.
 	 */
@@ -3350,9 +3354,10 @@ static int bpf_skb_generic_pop(struct sk_buff *skb, u32 off, u32 len)
 	void *old_data;
 
 	/* skb_ensure_writable() is not needed here, as we're
-	 * already working on an uncloned skb.
+	 * already working on an uncloned skb. The first test
+	 * keeps off + len from wrapping.
 	 */
-	if (unlikely(!pskb_may_pull(skb, off + len)))
+	if (unlikely(off > skb->len || !pskb_may_pull(skb, off + len)))
 		return -ENOMEM;
 
 	old_data = skb->data;
Signature · 1 line
2.53.0
author maintainer
#129 lore raw

PATCH 128/990 spi: Fix ACPI SPI resources using relative path

In reply to Greg Kroah-Hartman

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

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

From: Alban Bedel <[email protected]>

[ Upstream commit 4825287f6d2346e9273f35a928d1ef40e68bc58b ]

ACPI resources can use relative path when pointing to other resources. This didn't work with SPISerialBus resources because the device defining the resource was not passed to acpi_get_handle().

Pass the ACPI device handle through the lookup context to also allow for relative paths.

Stable-dep-of: 2d0953ab69d3 ("spi: acpi: only look up the IRQ of confirmed SPI devices")

---
 drivers/spi/spi.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
drivers/spi/spi.c +3 -1
index b8db8f5fd285d..b447907fba508 100644
@@ -2601,6 +2601,7 @@ EXPORT_SYMBOL_GPL(spi_new_ancillary_device);
 #ifdef CONFIG_ACPI
 struct acpi_spi_lookup {
 	struct spi_controller 	*ctlr;
+	acpi_handle		device_handle;
 	u32			max_speed_hz;
 	u32			mode;
 	int			irq;
@@ -2695,7 +2696,7 @@ static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
 			if (lookup->index != -1 && lookup->n++ != lookup->index)
 				return 1;
 
-			status = acpi_get_handle(NULL,
+			status = acpi_get_handle(lookup->device_handle,
 						 sb->resource_source.string_ptr,
 						 &parent_handle);
 
@@ -2787,6 +2788,7 @@ struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr,
 		return ERR_PTR(-EINVAL);
 
 	lookup.ctlr		= ctlr;
+	lookup.device_handle	= acpi_device_handle(adev);
 	lookup.irq		= -1;
 	lookup.index		= index;
 	lookup.n		= 0;
Signature · 1 line
2.53.0
author maintainer
#130 lore raw

PATCH 129/990 spi: acpi: only look up the IRQ of confirmed SPI devices

In reply to Greg Kroah-Hartman

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

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

From: Rosen Penev <[email protected]>

[ Upstream commit 2d0953ab69d316589624b0517fdce01f8e630bf0 ]

When an SPI controller is registered, acpi_register_spi_device() is called for every present ACPI device in the namespace and acpi_spi_device_alloc() walks each device's _CRS. While doing so, acpi_spi_add_resource() converts the first interrupt resource it finds, even for devices that have no SpiSerialBus resource at all and are discarded right afterwards. Converting an interrupt resource registers its GSI, so this maps IRQs for arbitrary unrelated ACPI devices.

On a Dell Precision M4800 (Lynx Point, 24-pin IOAPIC) the DSDT reports Haswell-ULT LPSS child devices (\_SB.PCI0.I2C0.ACD0 and \_SB.PCI0.SDHC.WI01) as present with interrupts on GSI 37 and 38. Registering the intel-spi controller then results in:

ERROR: Unable to locate IOAPIC for GSI 37
ERROR: Unable to locate IOAPIC for GSI 38

Do what the I2C core does and only parse the interrupt resource once the device has been identified as an SPI device on this controller.

Fixes 4c3c59544f33 ("spi/acpi: enumerate all SPI slaves in the namespace")
---
 drivers/spi/spi.c | 36 ++++++++++++++++++++++++++++--------
 1 file changed, 28 insertions(+), 8 deletions(-)
drivers/spi/spi.c +28 -8
index b447907fba508..b678e202b384b 100644
@@ -2604,7 +2604,6 @@ struct acpi_spi_lookup {
 	acpi_handle		device_handle;
 	u32			max_speed_hz;
 	u32			mode;
-	int			irq;
 	u8			bits_per_word;
 	u8			chip_select;
 	int			n;
@@ -2747,17 +2746,25 @@ static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
 			if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
 				lookup->mode |= SPI_CS_HIGH;
 		}
-	} else if (lookup->irq < 0) {
-		struct resource r;
-
-		if (acpi_dev_resource_interrupt(ares, 0, &r))
-			lookup->irq = r.start;
 	}
 
 	/* Always tell the ACPI core to skip this resource */
 	return 1;
 }
 
+static int acpi_spi_add_irq_resource(struct acpi_resource *ares, void *data)
+{
+	int *irq = data;
+	struct resource r;
+
+	if (*irq < 0 && ares->type != ACPI_RESOURCE_TYPE_SERIAL_BUS &&
+	    acpi_dev_resource_interrupt(ares, 0, &r))
+		*irq = r.start;
+
+	/* Always tell the ACPI core to skip this resource */
+	return 1;
+}
+
 /**
  * acpi_spi_device_alloc - Allocate a spi device, and fill it in with ACPI information
  * @ctlr: controller to which the spi device belongs
@@ -2782,6 +2789,7 @@ struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr,
 	struct list_head resource_list;
 	struct acpi_spi_lookup lookup = {};
 	struct spi_device *spi;
+	int irq = -1;
 	int ret;
 
 	if (!ctlr && index == -1)
@@ -2789,7 +2797,6 @@ struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr,
 
 	lookup.ctlr		= ctlr;
 	lookup.device_handle	= acpi_device_handle(adev);
-	lookup.irq		= -1;
 	lookup.index		= index;
 	lookup.n		= 0;
 
@@ -2812,6 +2819,19 @@ struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr,
 	if (!lookup.max_speed_hz)
 		return ERR_PTR(-ENODEV);
 
+	/*
+	 * Only look up the IRQ once we know this is an SPI device for us.
+	 * Parsing an interrupt resource maps its GSI, which must not be done
+	 * for every unrelated ACPI device walked during enumeration.
+	 */
+	INIT_LIST_HEAD(&resource_list);
+	ret = acpi_dev_get_resources(adev, &resource_list,
+				     acpi_spi_add_irq_resource, &irq);
+	if (ret < 0)
+		return ERR_PTR(ret);
+
+	acpi_dev_free_resource_list(&resource_list);
+
 	spi = spi_alloc_device(lookup.ctlr);
 	if (!spi) {
 		dev_err(&lookup.ctlr->dev, "failed to allocate SPI device for %s\n",
@@ -2824,7 +2844,7 @@ struct spi_device *acpi_spi_device_alloc(struct spi_controller *ctlr,
 	ACPI_COMPANION_SET(&spi->dev, adev);
 	spi->max_speed_hz	= lookup.max_speed_hz;
 	spi->mode		|= lookup.mode;
-	spi->irq		= lookup.irq;
+	spi->irq		= irq;
 	spi->bits_per_word	= lookup.bits_per_word;
 	/*
 	 * By default spi->chip_select[0] will hold the physical CS number,
Signature · 1 line
2.53.0
author maintainer
#113 lore raw

PATCH 112/990 bpf: Clamp the trace length before the skip test in stackid_init()

In reply to Greg Kroah-Hartman

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

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

From: Alexei Starovoitov <[email protected]>

[ Upstream commit a08ba2ab79dffd92c32d3f2dadfc7eba03625a2b ]

stackid_init() gives a bucket of the stack map
min(trace_nr - skip, max_depth - skip) trace entries. Here max_depth is the size of a bucket plus skip, but at most perf_event_max_stack. Context markers can make trace_nr larger than that, so the skip test can pass when max_depth < skip. Then 'max_depth - skip' wraps, and the kernel can write after the bucket.

Clamp trace_nr to max_depth before the skip test, as __bpf_get_stack_pe() does. The result changes only when skip >= max_depth. Then it is -EFAULT. Until now skip == max_depth could give the id of an empty trace.

get_perf_callchain() releases the trace, so an NMI can change trace->nr. Use READ_ONCE() in bpf_get_stackid(), so the compiler reads it one time.

Fixes 23f852daa4ba ("bpf: Fix stackmap overflow check in __bpf_get_stackid()")
---
 kernel/bpf/stackmap.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
kernel/bpf/stackmap.c +6 -3
index 128c8d61070e4..aa87e8d2d7d2e 100644
@@ -401,12 +401,14 @@ static int stackid_init(struct stackid *stackid, struct bpf_map *map,
 	u32 skip = flags & BPF_F_SKIP_FIELD_MASK;
 	u32 max_depth;
 
+	max_depth = stack_map_calculate_max_depth(map->value_size, stack_map_data_size(map), flags);
+	/* trace_nr can be above max_depth and max_depth below skip: clamp first */
+	trace_nr = min_t(u32, trace_nr, max_depth);
 	if (trace_nr <= skip)
 		/* skipping more than usable stack trace */
 		return -EFAULT;
 
-	max_depth = stack_map_calculate_max_depth(map->value_size, stack_map_data_size(map), flags);
-	stackid->nr = min_t(u32, trace_nr - skip, max_depth - skip);
+	stackid->nr = trace_nr - skip;
 	stackid->len = stackid->nr * sizeof(u64);
 	stackid->ips = trace->ip + skip;
 	stackid->hash = jhash2((const u32 *)stackid->ips, stackid->len / sizeof(u32), 0);
@@ -521,7 +523,8 @@ BPF_CALL_3(bpf_get_stackid, struct pt_regs *, regs, struct bpf_map *, map,
 			/* couldn't fetch the stack trace */
 			return -EFAULT;
 
-		err = stackid_fastpath(&stackid, map, trace, trace->nr, flags);
+		/* the entry is released already, an NMI can change trace->nr */
+		err = stackid_fastpath(&stackid, map, trace, READ_ONCE(trace->nr), flags);
 		if (err != -ENOENT)
 			return err;
 
Signature · 1 line
2.53.0
author maintainer
#131 lore raw

PATCH 130/990 bpf: lwt: Free the skb when bpf_xmit() fails to expand the headroom

In reply to Greg Kroah-Hartman

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

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

From: Yuqiang Sun <[email protected]>

[ Upstream commit 5e96760b25fdedbbf9312827f1f237d6b18b03e8 ]

When an LWT xmit program returns BPF_OK, bpf_xmit() makes sure that the skb still has room for the link layer header. If pskb_expand_head() fails there, bpf_xmit() returns -ENOMEM without freeing the skb. Its callers, lwtunnel_xmit() and then ip_finish_output2() or ip6_finish_output2(), take any return value other than LWTUNNEL_XMIT_CONTINUE to mean that the skb has been consumed, so nothing frees it.

Each such failure leaks the skb, together with what it holds: its dst and its charge to the sending socket, so the socket is never freed either. The other error paths of bpf_xmit() (BPF_DROP, an illegal return code, a changed protocol, a failed reroute) all free the skb.

Free it here too.

The leak was found with kbound, a static analysis prototype for ownership mismatches at kernel interfaces, on v7.2.12; it is present in mainline.

Build-tested with x86_64 and arm64 allmodconfig (W=1, sparse): no new warnings. Run-tested on QEMU (x86_64, KVM) with KASAN: a route through a dummy device with an LWT xmit program that pushes one byte with bpf_skb_change_head(), so the headroom check has to expand the head, and failslab limited to allocations under bpf_xmit(). Each of 10 pings then fails with ENOMEM. Without this patch each leaves a raw socket behind (RAW slab objects 6 -> 16); with it none does (6 -> 6), and nothing else is reported. Without injection both kernels go from 6 to 6.

Fixes 3a0af8fd61f9 ("bpf: BPF for lightweight tunnel infrastructure")
---
 net/core/lwt_bpf.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
net/core/lwt_bpf.c +3 -1
index 982599bb41c97..6d29da9f5460b 100644
@@ -341,8 +341,10 @@ static int bpf_xmit(struct sk_buff *skb)
 			 * made before LWT xmit.
 			 */
 			ret = xmit_check_headroom(skb, hroom);
-			if (unlikely(ret))
+			if (unlikely(ret)) {
+				kfree_skb(skb);
 				return ret;
+			}
 
 			return LWTUNNEL_XMIT_CONTINUE;
 		case BPF_REDIRECT:
Signature · 1 line
2.53.0
author maintainer
#132 lore raw

PATCH 131/990 net/mlx5: macsec: free struct mlx5_fs_id after an RCU grace period

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit 902407bc588575af0ceae5de4f635fe1e024f258 ]

macsec_fs_id_del() removes a struct mlx5_fs_id from its rhashtable with rhashtable_remove_fast() and then frees it with kfree() right away.

The TX (SCI) table is read locklessly from the transmit path:
mlx5e_macsec_handle_tx_skb() and mlx5e_macsec_tx_build_eseg() call mlx5_macsec_fs_get_fs_id_from_hashtable(), which does rhashtable_lookup() under rcu_read_lock() and then reads mlx5_fs_id->id. A transmit that looked the entry up just before it was removed reads freed memory.

Before commit d4ece08f4b1d ("net/mlx5: Maintain fs_id xarray per MACsec device inside macsec steering") the SCI table held struct mlx5e_macsec_sa directly, and mlx5e_macsec_del_txsa() freed it with kfree_rcu_mightsleep(). That commit moved the table into macsec_fs.c with the new struct mlx5_fs_id, but frees it with a plain kfree().

Add an rcu_head to struct mlx5_fs_id and free it with kfree_rcu().

The same issue was flagged by the Sashiko AI review as a pre-existing problem while reviewing the HW-GRO for PSP series.

Fixes d4ece08f4b1d ("net/mlx5: Maintain fs_id xarray per MACsec device inside macsec steering")
Assisted-by Yaga Agent HackerSec Claude:claude-opus-5-5
---
 drivers/net/ethernet/mellanox/mlx5/core/lib/macsec_fs.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/net/ethernet/mellanox/mlx5/core/lib/macsec_fs.c +2 -1
index e6be2f01daf4c..f6d09e4509e55 100644
@@ -94,6 +94,7 @@ struct mlx5_fs_id {
 	refcount_t refcnt;
 	sci_t sci;
 	struct rhash_head hash;
+	struct rcu_head rcu;
 };
 
 struct mlx5_macsec_device {
@@ -684,7 +685,7 @@ static void macsec_fs_id_del(struct list_head *macsec_devices_list, u32 fs_id,
 
 	xa_erase(fs_id_xa, fs_id);
 
-	kfree(fs_id_found);
+	kfree_rcu(fs_id_found, rcu);
 
 	if (macsec_fs_is_macsec_device_empty(macsec_device)) {
 		list_del(&macsec_device->macsec_devices_list_entry);
Signature · 1 line
2.53.0
author maintainer
#133 lore raw

PATCH 132/990 bnxt_en: Dont keep MSI-X vectors added before FW reserves them

In reply to Greg Kroah-Hartman

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

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

From: Vlad Poenaru <[email protected]>

[ Upstream commit af449230bd8de936d6e4f759240e787b9aad7cc0 ]

When dynamic MSI-X is supported, bnxt_check_rings() grows the MSI-X vectors with bnxt_change_msix() once FW says the new rings would fit, and keeps them. FW only reserves the extra IRQs later, when bnxt_reserve_rings() calls __bnxt_reserve_rings(). The MSI-X table entries beyond the function's reserved IRQs are not backed until then:
the MSI message written when the new vectors are activated is lost, and the entries read back as zero. After FW reserves them they are live but still zero, so the NQ rings bound to them signal address 0 and every completion on those rings is lost. The next ring change (for example ethtool -G) then times out freeing each of those rings and the TX watchdog fires:

bnxt_en 0002:01:00.0 eth0: Resp cmpl intr err msg: 0x51
bnxt_en 0002:01:00.0 eth0: hwrm_ring_free type 1 failed. rc:fffffff0 err:0
...
bnxt_en 0002:01:00.0 eth0: NETDEV WATCHDOG: CPU: 17: transmit queue 18 timed out 5716 ms

On x86 this is hidden: GENERIC_IRQ_RESERVATION_MODE makes the PCI MSI domains MSI_FLAG_MUST_REACTIVATE, so the message is composed and written again when the IRQ is requested, after FW has reserved the vector. Since commit 0d6a7c417983 ("irqchip/gic-v3-its: Enable dynamic MSI-X allocation"), arm64 GICv3 systems take the dynamic path as well, but write the message only once, at allocation. On an NVIDIA Grace system with a BCM57508, raising the channel count from 18 to 32 left MSI-X entries 18-31 all zero, and the 14 rings using them lost their interrupts.

Keep the allocation in bnxt_check_rings() as a check that enough vectors are available, but free the new vectors again right away when FW manages IRQ reservations (BNXT_NEW_RM). bnxt_reserve_rings() then allocates them after __bnxt_reserve_rings() has reserved them. Without BNXT_NEW_RM there is no IRQ reservation and bnxt_reserve_rings() does not grow the vectors, so keep the current behaviour there.

In bnxt_reserve_rings(), size that allocation from the rings FW actually reserved (bnxt_get_num_msix()) instead of the count computed before the reservation, so that a partial grant does not activate unreserved entries either, at least while no RoCE driver is registered.

The allocation can now fail after FW has committed the reservation. A later open would then find nothing to reserve and return before growing the vectors, and bnxt_request_irq() would use irq_tbl[] entries past bp->total_irqs, which still hold the freed virqs. Grow the vectors in that case as well, and clear irq_tbl[].vector when trimming.

---
 drivers/net/ethernet/broadcom/bnxt/bnxt.c | 34 ++++++++++++++++++++++-
 1 file changed, 33 insertions(+), 1 deletion(-)
drivers/net/ethernet/broadcom/bnxt/bnxt.c +33 -1
index 51c144584d240..2b1567616f51b 100644
@@ -11374,6 +11374,7 @@ static int bnxt_change_msix(struct bnxt *bp, int total)
 		map.index = i - 1;
 		map.virq = bp->irq_tbl[i - 1].vector;
 		pci_msix_free_irq(bp->pdev, map);
+		bp->irq_tbl[i - 1].vector = 0;
 		bp->total_irqs--;
 	}
 	return bp->total_irqs;
@@ -11551,8 +11552,23 @@ int bnxt_reserve_rings(struct bnxt *bp, bool irq_re_init)
 	int irqs_required;
 	int rc;
 
-	if (!bnxt_need_reserve_rings(bp))
+	if (!bnxt_need_reserve_rings(bp)) {
+		/* FW may already hold the reservation from an earlier
+		 * reservation that was not followed by growing the dynamic
+		 * MSI-X vectors, e.g. because the allocation failed.
+		 */
+		if (irq_re_init && BNXT_NEW_RM(bp) && bp->irq_tbl &&
+		    pci_msix_can_alloc_dyn(bp->pdev)) {
+			irqs_required = bnxt_get_num_msix(bp);
+			if (irqs_required > bp->total_irqs &&
+			    bnxt_change_msix(bp, irqs_required) != irqs_required) {
+				netdev_err(bp->dev, "Unable to allocate %d MSIX vectors, maximum available %d\n",
+					   irqs_required, bp->total_irqs);
+				return -ENOSPC;
+			}
+		}
 		return 0;
+	}
 
 	if (BNXT_NEW_RM(bp) && !bnxt_ulp_registered(edev)) {
 		int ulp_msix = bnxt_get_avail_msix(bp, bp->ulp_num_msix_want);
@@ -11578,6 +11594,10 @@ int bnxt_reserve_rings(struct bnxt *bp, bool irq_re_init)
 			rc = bnxt_init_int_mode(bp);
 		bnxt_ulp_irq_restart(bp, rc);
 	} else if (irq_change && !rc) {
+		/* Size the vectors from what FW actually reserved, which
+		 * can be less than what was requested.
+		 */
+		irqs_required = bnxt_get_num_msix(bp);
 		if (bnxt_change_msix(bp, irqs_required) != irqs_required)
 			rc = -ENOSPC;
 	}
@@ -14875,6 +14895,7 @@ int bnxt_check_rings(struct bnxt *bp, int tx, int rx, bool sh, int tcs,
 			hwr.cp = min_t(int, hwr.cp, bnxt_get_max_func_irqs(bp));
 		}
 		if (hwr.cp > bp->total_irqs) {
+			int old_total = bp->total_irqs;
 			int total_msix = bnxt_change_msix(bp, hwr.cp);
 
 			if (total_msix < hwr.cp) {
@@ -14882,6 +14903,17 @@ int bnxt_check_rings(struct bnxt *bp, int tx, int rx, bool sh, int tcs,
 					    hwr.cp, total_msix);
 				rc = -ENOSPC;
 			}
+			/* FW has not reserved the new vectors yet, and writes to
+			 * MSI-X table entries beyond the reserved IRQs don't
+			 * stick (seen on BCM57508).  Free them again;
+			 * bnxt_reserve_rings() allocates them after
+			 * __bnxt_reserve_rings().  Without the new resource
+			 * manager there is no IRQ reservation and
+			 * bnxt_reserve_rings() does not grow the vectors, so
+			 * keep them.
+			 */
+			if (BNXT_NEW_RM(bp))
+				bnxt_change_msix(bp, old_total);
 		}
 	}
 	return rc;
Signature · 1 line
2.53.0
author maintainer
#134 lore raw

PATCH 133/990 ipv6: fix fib6 walker UAF on NLM_F_REPLACE

In reply to Greg Kroah-Hartman

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

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

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

[ Upstream commit 23fec4bd76904e9df7a8cc0a81ceb14c36971da4 ]

fib6_walker uses w->leaf to remember the next fib6_info to dump, so an RTM_GETROUTE dump can continue there on the next recvmsg(). This assumes that whoever removes a route from the tree also updates the walkers pointing at it. fib6_del_route() does: it moves w->leaf to the next route. The NLM_F_REPLACE branch of fib6_add_rt2node() does
not: it removes the old route, fib6_add() frees it, and w->leaf keeps pointing at the freed object.

The fn_sernum version check in fib6_dump_table() normally protects against resuming on a stale w->leaf, but it can be bypassed:
ip6_link_failure() resets fn_sernum to -1 when the default route fails, which an unprivileged user in a user+net namespace can cause:

1) link failure fn_sernum = -1
2) dump pauses on route R

  3) replace R               fn_sernum changed, R freed
  4) link failure            fn_sernum = -1
  5) dump resumes            -1 == -1, reads freed R  <- UAF
  BUG: KASAN: slab-use-after-free in rt6_fill_node+0x1c22/0x2cd0
  Read of size 4 at addr ff11000011fa0064 by task poc/101
   rt6_fill_node <- rt6_dump_route

Fix by adjusting walkers separately for replacement and deletion. For replacement, add fib6_walkers_replace_leaf() points w->leaf at the new route. For deletion and ECMP sibling removal, fib6_walkers_skip_rt() calls fib6_walkers_replace_leaf() with the next route. Reset w->skip_in_node when updating w->leaf, and set w->state to FWS_U when no next route remains.

Fixes 4a287eba2de3 ("IPv6 routing, NLM_F_* flag support: REPLACE and EXCL flags support, warn about missing CREATE flag")
---
 net/ipv6/ip6_fib.c | 50 ++++++++++++++++++++++++++++++++++------------
 1 file changed, 37 insertions(+), 13 deletions(-)
net/ipv6/ip6_fib.c +37 -13
index 9fc2d2677b747..962d01b9954e4 100644
@@ -89,6 +89,40 @@ static void fib6_walker_unlink(struct net *net, struct fib6_walker *w)
 	write_unlock_bh(&net->ipv6.fib6_walker_lock);
 }
 
+/* @old is leaving the tree.  Walkers resting on it continue from @new, or
+ * climb to the parent node when there is no @new.  Called with tb6_lock
+ * held.
+ */
+static void fib6_walkers_replace_leaf(struct net *net, struct fib6_info *old,
+				      struct fib6_info *new)
+{
+	struct fib6_walker *w;
+
+	read_lock(&net->ipv6.fib6_walker_lock);
+	FOR_WALKERS(net, w) {
+		if (w->state == FWS_C && w->leaf == old) {
+			pr_debug("walker %p adjusted by unlink of %p\n", w, old);
+			w->leaf = new;
+			w->skip_in_node = 0;
+			if (!new)
+				w->state = FWS_U;
+		}
+	}
+	read_unlock(&net->ipv6.fib6_walker_lock);
+}
+
+/* @rt is removed from its node: walkers resting on it continue from the
+ * next route of the node.
+ */
+static void fib6_walkers_skip_rt(struct net *net, struct fib6_info *rt)
+{
+	struct fib6_info *next;
+
+	next = rcu_dereference_protected(rt->fib6_next,
+					 lockdep_is_held(&rt->fib6_table->tb6_lock));
+	fib6_walkers_replace_leaf(net, rt, next);
+}
+
 static int fib6_new_sernum(struct net *net)
 {
 	int new, old = atomic_read(&net->ipv6.fib6_sernum);
@@ -1306,6 +1340,7 @@ static int fib6_add_rt2node(struct fib6_node *fn, struct fib6_info *rt,
 		rcu_assign_pointer(rt->fib6_node, fn);
 		rt->fib6_next = iter->fib6_next;
 		rcu_assign_pointer(*ins, rt);
+		fib6_walkers_replace_leaf(info->nl_net, iter, rt);
 		if (!info->skip_notify)
 			inet6_rt_notify(RTM_NEWROUTE, rt, info, NLM_F_REPLACE);
 		if (!(fn->fn_flags & RTN_RTINFO)) {
@@ -1327,6 +1362,7 @@ static int fib6_add_rt2node(struct fib6_node *fn, struct fib6_info *rt,
 				if (iter->fib6_metric > rt->fib6_metric)
 					break;
 				if (rt6_qualify_for_ecmp(iter)) {
+					fib6_walkers_skip_rt(info->nl_net, iter);
 					*ins = iter->fib6_next;
 					iter->fib6_node = NULL;
 					list_add(&iter->purge_link, purge_list);
@@ -1967,7 +2003,6 @@ static void fib6_del_route(struct fib6_table *table, struct fib6_node *fn,
 			   struct fib6_info __rcu **rtp, struct nl_info *info)
 {
 	struct fib6_info *leaf, *replace_rt = NULL;
-	struct fib6_walker *w;
 	struct fib6_info *rt = rcu_dereference_protected(*rtp,
 				    lockdep_is_held(&table->tb6_lock));
 	struct net *net = info->nl_net;
@@ -2018,18 +2053,7 @@ static void fib6_del_route(struct fib6_table *table, struct fib6_node *fn,
 		rt6_multipath_rebalance(next_sibling);
 	}
 
-	/* Adjust walkers */
-	read_lock(&net->ipv6.fib6_walker_lock);
-	FOR_WALKERS(net, w) {
-		if (w->state == FWS_C && w->leaf == rt) {
-			pr_debug("walker %p adjusted by delroute\n", w);
-			w->leaf = rcu_dereference_protected(rt->fib6_next,
-					    lockdep_is_held(&table->tb6_lock));
-			if (!w->leaf)
-				w->state = FWS_U;
-		}
-	}
-	read_unlock(&net->ipv6.fib6_walker_lock);
+	fib6_walkers_skip_rt(net, rt);
 
 	/* If it was last route, call fib6_repair_tree() to:
 	 * 1. For root node, put back null_entry as how the table was created.
Signature · 1 line
2.53.0
author maintainer
#135 lore raw

PATCH 134/990 tcp: do not let tcp_collapse() drive sk_forward_alloc negative

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit 031c403d13e5046750e2abebd4e770631e7c4627 ]

tcp_collapse() charges each newly allocated skb with skb_set_owner_r() before the skbs it replaces are freed, without scheduling memory first.

Since sk_mem_uncharge() reclaims eagerly, sk->sk_forward_alloc has no cushion and can become negative. This can be durable when the collapsed skbs had a high payload/truesize ratio or were partially read, because the new skbs can have a bigger total truesize than the old ones.

A negative sk_forward_alloc then confuses tcp_wmem_schedule(), which can return a negative length to tcp_sendmsg_locked(), triggering a WARN_ON_ONCE(bytes > INT_MAX) in check_copy_size().

Call sk_forced_mem_schedule() before charging nskb.

Fixes 4890b686f408 ("net: keep sk->sk_forward_alloc as small as possible")
---
 net/ipv4/tcp_input.c | 4 ++++
 1 file changed, 4 insertions(+)
net/ipv4/tcp_input.c +4 -0
index 28db1353445bf..5d8da3c23e2c8 100644
@@ -5646,6 +5646,10 @@ tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct rb_root *root,
 			__skb_queue_before(list, skb, nskb);
 		else
 			__skb_queue_tail(&tmp, nskb); /* defer rbtree insertion */
+		/* nskb is charged before the skbs it replaces are freed.
+		 * Make sure sk->sk_forward_alloc can not become negative.
+		 */
+		sk_forced_mem_schedule(sk, nskb->truesize);
 		skb_set_owner_r(nskb, sk);
 		mptcp_skb_ext_move(nskb, skb);
 
Signature · 1 line
2.53.0
author maintainer
#136 lore raw

PATCH 135/990 ata: libata-sata: allow re-enabling NCQ with the same queue_depth

In reply to Greg Kroah-Hartman

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

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

From: Igor Pylypiv <[email protected]>

[ Upstream commit d7c5cc8cc21c1264cce07feb4a51be158688280e ]

When ata_eh_speed_down() disables NCQ due to excessive errors, it sets ATA_DFLAG_NCQ_OFF without changing sdev->queue_depth. Userspace can re-enable NCQ by writing a queue depth > 1 to the sysfs queue_depth attribute, which invokes ata_change_queue_depth() to clear ATA_DFLAG_NCQ_OFF.

However, ata_change_queue_depth() returns early if the requested queue_depth is equal to sdev->queue_depth before clearing ATA_DFLAG_NCQ_OFF. As a result, writing a different queue depth > 1 re-enables NCQ, whereas writing the current sdev->queue_depth value leaves ATA_DFLAG_NCQ_OFF set.

Since ata_change_queue_depth() already checks whether queue_depth equals sdev->queue_depth before calling scsi_change_queue_depth(), remove the early check so that writing the current queue_depth > 1 clears ATA_DFLAG_NCQ_OFF and re-enables NCQ.

Fixes 45623d33bfc0 ("ata: libata-sata: Improve ata_change_queue_depth()")
---
 drivers/ata/libata-sata.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/ata/libata-sata.c +1 -1
index 9b374e8f99384..9eb28dab46195 100644
@@ -1287,7 +1287,7 @@ int ata_change_queue_depth(struct ata_port *ap, struct scsi_device *sdev,
 	spin_lock_irqsave(ap->lock, flags);
 
 	dev = ata_scsi_find_dev(ap, sdev);
-	if (!dev || queue_depth < 1 || queue_depth == sdev->queue_depth) {
+	if (!dev || queue_depth < 1) {
 		spin_unlock_irqrestore(ap->lock, flags);
 		return sdev->queue_depth;
 	}
Signature · 1 line
2.53.0
author maintainer
#137 lore raw

PATCH 136/990 ata: libata-eh: Retry non-NCQ commands when their sense data asks for it

In reply to Greg Kroah-Hartman

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

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

From: Niklas Cassel <[email protected]>

[ Upstream commit 597be4104c4045d73979c05307fa5fc778d1dbde ]

When a failed command has valid sense data, ata_eh_analyze_tf() asks scsi_check_sense() whether the command should be retried, and sets ATA_QCFLAG_RETRY if it should. ata_eh_link_autopsy() then clears AC_ERR_DEV and AC_ERR_OTHER from qc->err_mask, relying on that decision.

For an NCQ command, qc->err_mask still has AC_ERR_NCQ, so ata_eh_finish() honors ATA_QCFLAG_RETRY. For a non-NCQ command, whose sense data comes from REQUEST SENSE DATA EXT, qc->err_mask is now zero, and ata_eh_finish() completes the command with scmd->retries set to scmd->allowed, without looking at ATA_QCFLAG_RETRY. Such a command is thus never retried, even when its sense data asks for a retry, e.g. a transient error reported as ABORTED COMMAND.

Make ata_eh_finish() honor ATA_QCFLAG_RETRY for commands with valid sense data. ata_eh_qc_retry() cannot be used for this: as qc->err_mask is zero, it increments scmd->allowed, so every retry would allow one more, and a persistent error would be retried forever. Instead, complete the command without touching scmd->allowed or scmd->retries, so that the SCSI midlayer retries it at most scmd->allowed times, like any other failed command.

---
 drivers/ata/libata-eh.c | 16 ++++++++++++++--
 1 file changed, 14 insertions(+), 2 deletions(-)
drivers/ata/libata-eh.c +14 -2
index 9d35b4f8d3929..1e5946c0a7434 100644
@@ -4061,8 +4061,20 @@ void ata_eh_finish(struct ata_port *ap)
 				ata_eh_qc_complete(qc);
 			}
 		} else {
-			if (qc->flags & ATA_QCFLAG_SENSE_VALID ||
-			    qc->flags & ATA_QCFLAG_EH_SUCCESS_CMD) {
+			if (qc->flags & ATA_QCFLAG_SENSE_VALID &&
+			    qc->flags & ATA_QCFLAG_RETRY) {
+				/*
+				 * The sense data asks for a retry, see
+				 * ata_eh_analyze_tf(). ata_eh_link_autopsy()
+				 * cleared qc->err_mask, so ata_eh_qc_retry()
+				 * would increment scmd->allowed. Leave
+				 * scmd->allowed alone, so that upper layer
+				 * only retries the command if it has not
+				 * already been retried too many times.
+				 */
+				__ata_eh_qc_complete(qc);
+			} else if (qc->flags & ATA_QCFLAG_SENSE_VALID ||
+				   qc->flags & ATA_QCFLAG_EH_SUCCESS_CMD) {
 				ata_eh_qc_complete(qc);
 			} else {
 				/* feed zero TF to sense generation */
Signature · 1 line
2.53.0
author maintainer
#138 lore raw

PATCH 137/990 net: stmmac: take ownership of saved RX state at poll entry

In reply to Greg Kroah-Hartman

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

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

From: James Hilliard <[email protected]>

[ Upstream commit 26219e9402c22181f021034f127a8e278d40545f ]

When a saved partial packet completes with a poll budget of one, the old loop can leave state_saved and state.skb pointing at an skb that has already been delivered or freed. The next poll then reuses that pointer, causing a use-after-free or double free.

Take the saved state at poll entry and clear the stored ownership immediately. Save it again only if the packet remains incomplete, including when the next descriptor is still DMA-owned.

Track the frame-in-progress flag independently of the status read from the next descriptor. The old code keyed the save on the status of the last descriptor looked at, so a loop stopped at a DMA-owned descriptor (rx status not yet valid) could drop the saved error/length bookkeeping in stmmac_rx_zc().

Drop the saved state both when the queue parameters are reset and when the ring is destroyed. stmmac_reset_rx_queue() is reached from __stmmac_open(), stmmac_xdp_open(), stmmac_resume() and stmmac_enable_rx_queue(); without draining it there, a partial frame saved before suspend (or before a queue is disabled and re-enabled) survives while cur_rx and dirty_rx are rewound to zero. On the resume path the ring is only re-armed in place: stmmac_clear_descriptors() sets the ownership bits and stmmac_init_dma_engine() restores the tail pointer, but the RX buffer addresses are not reprogrammed. The first poll would then resume the stale skb against a ring position that no longer matches the descriptors it was built from. __free_dma_rx_desc_resources() releases it on teardown.

Apply the same state handling to stmmac_rx_zc(), which also leaves state_saved set when a saved frame finishes at the budget boundary. That path saves only error and length bookkeeping, not an skb pointer.

Fixes ec222003bd94 ("net: stmmac: Prepare to add Split Header support")
Fixes bba2556efad6 ("net: stmmac: Enable RX via AF_XDP zero-copy")
---
 .../net/ethernet/stmicro/stmmac/stmmac_main.c | 72 +++++++++++--------
 1 file changed, 42 insertions(+), 30 deletions(-)
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +42 -30
index 98e6d2cc544ce..67606fd618494 100644
@@ -1939,6 +1939,9 @@ static void __free_dma_rx_desc_resources(struct stmmac_priv *priv,
 	else
 		dma_free_rx_skbufs(priv, dma_conf, queue);
 
+	dev_kfree_skb_any(rx_q->state.skb);
+	rx_q->state.skb = NULL;
+	rx_q->state_saved = false;
 	rx_q->buf_alloc_num = 0;
 	rx_q->xsk_pool = NULL;
 
@@ -5324,12 +5327,12 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue)
 	unsigned int count = 0, error = 0, len = 0;
 	int dirty = stmmac_rx_dirty(priv, queue);
 	unsigned int next_entry = rx_q->cur_rx;
+	bool in_progress = rx_q->state_saved;
 	u32 rx_errors = 0, rx_dropped = 0;
 	unsigned int desc_size;
 	struct bpf_prog *prog;
 	bool failure = false;
 	int xdp_status = 0;
-	int status = 0;
 
 	if (netif_msg_rx_status(priv)) {
 		void *rx_head;
@@ -5346,23 +5349,25 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue)
 		stmmac_display_ring(priv, rx_head, priv->dma_conf.dma_rx_size, true,
 				    rx_q->dma_rx_phy, desc_size);
 	}
+
+	if (rx_q->state_saved) {
+		error = rx_q->state.error;
+		len = rx_q->state.len;
+		rx_q->state_saved = false;
+	}
+
 	while (count < limit) {
 		struct stmmac_rx_buffer *buf;
 		struct stmmac_xdp_buff *ctx;
 		unsigned int buf1_len = 0;
 		struct dma_desc *np, *p;
-		int entry;
+		int entry, status;
 		int res;
 
-		if (!count && rx_q->state_saved) {
-			error = rx_q->state.error;
-			len = rx_q->state.len;
-		} else {
-			rx_q->state_saved = false;
+		if (!in_progress) {
 			error = 0;
 			len = 0;
 		}
-
 read_again:
 		if (count >= limit)
 			break;
@@ -5407,6 +5412,8 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue)
 		if (!buf->xdp)
 			break;
 
+		in_progress = status & rx_not_ls;
+
 		if (priv->extend_desc) {
 			/* Read the extended status after the own bit */
 			dma_rmb();
@@ -5483,7 +5490,7 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue)
 		count++;
 	}
 
-	if (status & rx_not_ls) {
+	if (in_progress) {
 		rx_q->state_saved = true;
 		rx_q->state.error = error;
 		rx_q->state.len = len;
@@ -5525,9 +5532,10 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)
 	struct stmmac_rx_queue *rx_q = &priv->dma_conf.rx_queue[queue];
 	struct stmmac_channel *ch = &priv->channel[queue];
 	unsigned int count = 0, error = 0, len = 0;
-	int status = 0, coe = priv->hw->rx_csum;
 	unsigned int next_entry = rx_q->cur_rx;
+	bool in_progress = rx_q->state_saved;
 	enum dma_data_direction dma_dir;
+	int coe = priv->hw->rx_csum;
 	unsigned int desc_size;
 	struct sk_buff *skb = NULL;
 	struct stmmac_xdp_buff ctx;
@@ -5553,25 +5561,28 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)
 		stmmac_display_ring(priv, rx_head, priv->dma_conf.dma_rx_size, true,
 				    rx_q->dma_rx_phy, desc_size);
 	}
+
+	if (rx_q->state_saved) {
+		skb = rx_q->state.skb;
+		error = rx_q->state.error;
+		len = rx_q->state.len;
+		rx_q->state.skb = NULL;
+		rx_q->state_saved = false;
+	}
+
 	while (count < limit) {
 		unsigned int buf1_len = 0, buf2_len = 0;
 		enum pkt_hash_types hash_type;
 		struct stmmac_rx_buffer *buf;
 		struct dma_desc *np, *p;
-		int entry;
+		int entry, status;
 		u32 hash;
 
-		if (!count && rx_q->state_saved) {
-			skb = rx_q->state.skb;
-			error = rx_q->state.error;
-			len = rx_q->state.len;
-		} else {
-			rx_q->state_saved = false;
+		if (!in_progress) {
 			skb = NULL;
 			error = 0;
 			len = 0;
 		}
-
 read_again:
 		if (count >= limit)
 			break;
@@ -5606,6 +5617,8 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)
 
 		prefetch(np);
 
+		in_progress = status & rx_not_ls;
+
 		if (priv->extend_desc) {
 			/* Read the extended status after the own bit */
 			dma_rmb();
@@ -5623,11 +5636,10 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)
 
 		if (unlikely(error && (status & rx_not_ls)))
 			goto read_again;
+
 		if (unlikely(error)) {
 			dev_kfree_skb(skb);
-			skb = NULL;
-			count++;
-			continue;
+			goto next;
 		}
 
 		/* Buffer is good. Go on. */
@@ -5701,9 +5713,7 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)
 						      STMMAC_XDP_REDIRECT)) {
 					xdp_status |= xdp_res;
 					buf->page = NULL;
-					skb = NULL;
-					count++;
-					continue;
+					goto next;
 				}
 			}
 		}
@@ -5760,10 +5770,8 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)
 		/* Remove FCS if needed */
 		if (!fcs_stripped && pskb_trim(skb, len)) {
 			dev_kfree_skb_any(skb);
-			skb = NULL;
 			rx_dropped++;
-			count++;
-			continue;
+			goto next;
 		}
 
 		stmmac_get_rx_hwtstamp(priv, p, np, skb);
@@ -5788,14 +5796,15 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)
 
 		skb_record_rx_queue(skb, queue);
 		napi_gro_receive(&ch->rx_napi, skb);
-		skb = NULL;
-
 		rx_packets++;
 		rx_bytes += len;
+next:
+		in_progress = false;
+		skb = NULL;
 		count++;
 	}
 
-	if (status & rx_not_ls || skb) {
+	if (in_progress || skb) {
 		rx_q->state_saved = true;
 		rx_q->state.skb = skb;
 		rx_q->state.error = error;
@@ -7948,6 +7957,9 @@ static void stmmac_reset_rx_queue(struct stmmac_priv *priv, u32 queue)
 {
 	struct stmmac_rx_queue *rx_q = &priv->dma_conf.rx_queue[queue];
 
+	dev_kfree_skb_any(rx_q->state.skb);
+	rx_q->state.skb = NULL;
+	rx_q->state_saved = false;
 	rx_q->cur_rx = 0;
 	rx_q->dirty_rx = 0;
 }
Signature · 1 line
2.53.0
author maintainer
#139 lore raw

PATCH 138/990 net: stmmac: drop split frames on AF_XDP zero-copy RX

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Bianconi <[email protected]>

[ Upstream commit 834ec95308320cbd8c162d86788ab95cc3fd6bf8 ]

stmmac_rx_zc() assumes a 1:1 mapping between a received frame and an XSK pool buffer and drops any frame that spans more than one RX descriptor:

        /* XSK pool expects RX frame 1:1 mapped to XSK buffer */
        if (likely(status & rx_not_ls)) {
                xsk_buff_free(buf->xdp);
                buf->xdp = NULL;
                dirty++;
                count++;
                goto read_again;
        }

The non-last descriptors are freed and dropped, but the frame is not marked as errored. When the poll reaches the last descriptor of the same frame, error is still 0, so the fragment is handled as a complete
frame: it is passed to the XDP program, copied into an skb on XDP_PASS, or converted for XDP_TX. The tail starts in the middle of the original payload at a predictable offset and, parsed as a fresh frame (len == 0), stmmac_rx_buf1_len() reports the full dma_buf_sz length for it even though the DMA engine only wrote the tail remainder into that buffer, so the reads extend past the received bytes and can reach beyond the end of the XSK pool buffer. GMAC4 always enables jumbo frames (GMAC_CONFIG_JE in GMAC_CORE_INIT), so an on-link peer can trigger such a split even when the interface MTU is left at 1500.

Set error when the 1:1 mapping check drops a descriptor, so the remaining descriptors of the frame - including the last one - are drained and released with xsk_buff_free() instead of being processed as a new frame. Account every freed buffer with dirty and count the dropped frame once in the poll budget / rx_pkt_n. The direct 1:1 mapping drop also increments rx_dropped.

Use a bit test instead of an equality test for discard_frame. Commit 644b8437ccef9e ("net: stmmac: dwmac4: report Rx checksum errors in status") made dwmac4_wrback_get_rx_status() set discard_frame on RDES3_ERROR_SUMMARY and OR in csum_none on RDES1_IP_HDR_ERROR or RDES1_IP_PAYLOAD_ERROR, so it can return discard_frame | csum_none. The old "status == discard_frame" test missed that value and delivered frames with CRC, overflow, watchdog or giant errors to the stack in stmmac_rx() - or to XDP/XSK in stmmac_rx_zc() - when they also failed the IP checksum. The change therefore affects the regular RX path, not only zero-copy. The bit test is also required for the discard_frame | rx_not_ls value returned for non-last legacy descriptors below.

Normalize the legacy normal and enhanced descriptor callbacks to report rx_not_ls together with discard_frame for non-last descriptors. This allows both stmmac_rx_zc() and stmmac_rx() to drain split frames on dwmac100 and dwmac1000 instead of reparsing the final fragment as a new packet.

Fixes bba2556efad6 ("net: stmmac: Enable RX via AF_XDP zero-copy")
Fixes 644b8437ccef9e ("net: stmmac: dwmac4: report Rx checksum errors in status")
---
 .../net/ethernet/stmicro/stmmac/enh_desc.c    |  2 +-
 .../net/ethernet/stmicro/stmmac/norm_desc.c   |  2 +-
 .../net/ethernet/stmicro/stmmac/stmmac_main.c | 21 ++++++++++++-------
 3 files changed, 15 insertions(+), 10 deletions(-)
drivers/net/ethernet/stmicro/stmmac/enh_desc.c +1 -1
index 963579518405c..9833db1fed0c4 100644
@@ -210,7 +210,7 @@ static int enh_desc_get_rx_status(struct stmmac_extra_stats *x,
 
 	if (unlikely(!(rdes0 & RDES0_LAST_DESCRIPTOR))) {
 		x->rx_length++;
-		return discard_frame;
+		return discard_frame | rx_not_ls;
 	}
 
 	if (unlikely(rdes0 & RDES0_ERROR_SUMMARY)) {
drivers/net/ethernet/stmicro/stmmac/norm_desc.c +1 -1
index 68a7cfcb1d8f3..c08846da03eb7 100644
@@ -77,7 +77,7 @@ static int ndesc_get_rx_status(struct stmmac_extra_stats *x,
 
 	if (unlikely(!(rdes0 & RDES0_LAST_DESCRIPTOR))) {
 		x->rx_length++;
-		return discard_frame;
+		return discard_frame | rx_not_ls;
 	}
 
 	if (unlikely(rdes0 & RDES0_ERROR_SUMMARY)) {
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +13 -8
index 67606fd618494..022d308bb95f6 100644
@@ -5421,18 +5421,21 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue)
 							   &rx_q->dma_erx[entry],
 							   status);
 		}
-		if (unlikely(status == discard_frame)) {
-			xsk_buff_free(buf->xdp);
-			buf->xdp = NULL;
-			dirty++;
+
+		if (unlikely(!error && (status & discard_frame))) {
 			error = 1;
 			if (!priv->hwts_rx_en)
 				rx_errors++;
 		}
 
-		if (unlikely(error && (status & rx_not_ls)))
-			goto read_again;
 		if (unlikely(error)) {
+			xsk_buff_free(buf->xdp);
+			buf->xdp = NULL;
+			dirty++;
+
+			if (status & rx_not_ls)
+				goto read_again;
+
 			count++;
 			continue;
 		}
@@ -5441,8 +5444,9 @@ static int stmmac_rx_zc(struct stmmac_priv *priv, int limit, u32 queue)
 		if (likely(status & rx_not_ls)) {
 			xsk_buff_free(buf->xdp);
 			buf->xdp = NULL;
+			rx_dropped++;
+			error = 1;
 			dirty++;
-			count++;
 			goto read_again;
 		}
 
@@ -5626,7 +5630,8 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)
 							   &rx_q->dma_erx[entry],
 							   status);
 		}
-		if (unlikely(status == discard_frame)) {
+
+		if (unlikely(status & discard_frame)) {
 			page_pool_put_page(rx_q->page_pool, buf->page, 0, true);
 			buf->page = NULL;
 			error = 1;
Signature · 1 line
2.53.0
author maintainer
#140 lore raw

PATCH 139/990 net: stmmac: drop multi-buffer frames in XDP mode

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Bianconi <[email protected]>

[ Upstream commit 52ffd771e0029c5ad0504b1b4a8b7f932b65eea3 ]

stmmac_rx() runs the XDP program once per descriptor buffer and uses skb == NULL as the only marker for the start of a frame. A frame larger than one buffer is split by the hardware across several descriptors; GMAC4 enables jumbo frames unconditionally (GMAC_CONFIG_JE in GMAC_CORE_INIT), so an on-link peer can deliver such a frame even when the interface MTU is left at 1500.

When an XDP verdict ends a non-last descriptor, skb is cleared and the next descriptor of the same hardware frame is parsed as a new frame. For XDP_CONSUMED this happens via read_again with len preserved, so stmmac_rx_buf1_len() then returns min(dma_buf_sz, plen - len) for the last descriptor, which can be as small as 0-3 bytes. buf1_len -= ETH_FCS_LEN underflows and xdp_prepare_buff() puts data_end far past data; on XDP_PASS this produces an skb whose length is close to 4G that reaches the network stack (skb->tail and skb->len are 32-bit and wrap below skb->end, so skb_over_panic() does not fire). A 4+ byte tail is instead offered to the XDP program and delivered as a standalone mid-payload Ethernet frame on XDP_PASS. XDP_TX/XDP_REDIRECT instead falls through to the next iteration, resetting the running length, so the tail is re-parsed as a full-size new frame.

The same fault exists when a single descriptor uses its second buffer:
buffer2 is now handed to the hardware for non-SPH frames on GMAC4/XGMAC, so a frame up to 2 * dma_buf_sz can land on a single descriptor while the XDP program still only sees the first buffer. XDP_TX then transmits a truncated frame, and XDP_PASS appends the second buffer only after the program has already run over the first one.

XDP does not support scatter-gather frames until the multi-buffer rework, so drop the whole frame instead. When a non-last descriptor is seen while an XDP program is attached, mark the frame as errored and drain the remaining descriptors, including the last. A descriptor that uses its second buffer is dropped directly before the program runs as well; in XDP mode it is necessarily the last descriptor of the frame, so it does not need the error marker. Removing the re-parse lets both XDP verdict branches simply complete the packet via next.

The buffers consumed by the discard path are no longer returned to the page pool, and the new SG and second-buffer drops do not return them either. They stay in rx_q->buf_pool[] and stmmac_rx_refill() reuses them in place, allocating only when a slot is empty. This is safe because the drop checks run before the buffer is synced for CPU access or prefetched. The discard-path change and the in-place reuse apply with or without an XDP program attached.

The !error guard on the discard check also changes the accounting for errored multi-descriptor frames on dwmac100/dwmac1000: rx_errors is incremented once per frame instead of once per descriptor. This too is independent of XDP mode.

Note: the subsequent "net: stmmac: rework stmmac_rx to support XDP rx multi-buff" accumulates the whole frame into a single xdp_buff and supersedes this patch; the fix is kept so the net portion of the series stands on its own.

Fixes 5fabb01207a2 ("net: stmmac: Add initial XDP support")
Fixes 88095728511e ("net: stmmac: fix rx Scatter-Gather support")
---
 .../net/ethernet/stmicro/stmmac/stmmac_main.c | 35 ++++++++++---------
 1 file changed, 19 insertions(+), 16 deletions(-)
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +19 -16
index 022d308bb95f6..a79332f92be79 100644
@@ -5631,18 +5631,23 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)
 							   status);
 		}
 
-		if (unlikely(status & discard_frame)) {
-			page_pool_put_page(rx_q->page_pool, buf->page, 0, true);
-			buf->page = NULL;
+		if (unlikely(!error && (status & discard_frame))) {
 			error = 1;
 			if (!priv->hwts_rx_en)
 				rx_errors++;
 		}
 
-		if (unlikely(error && (status & rx_not_ls)))
-			goto read_again;
+		/* We do not support SG in XDP mode */
+		if (unlikely(!error && (status & rx_not_ls) &&
+			     stmmac_xdp_is_enabled(priv))) {
+			rx_dropped++;
+			error = 1;
+		}
 
 		if (unlikely(error)) {
+			if (status & rx_not_ls)
+				goto read_again;
+
 			dev_kfree_skb(skb);
 			goto next;
 		}
@@ -5654,6 +5659,14 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)
 		buf2_len = stmmac_rx_buf2_len(priv, p, status, len);
 		len += buf2_len;
 
+		/* Drop the packet if it is split over buf1 and buf2 on a
+		 * single descriptor if the interface is running in XDP mode.
+		 */
+		if (unlikely(stmmac_xdp_is_enabled(priv) && buf2_len)) {
+			rx_dropped++;
+			goto next;
+		}
+
 		/* ACS is disabled; strip manually. */
 		if (likely(!(status & rx_not_ls)))
 			len -= ETH_FCS_LEN;
@@ -5703,17 +5716,7 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)
 							   sync_len, true);
 					buf->page = NULL;
 					rx_dropped++;
-
-					/* Clear skb as it was set as
-					 * status by XDP program.
-					 */
-					skb = NULL;
-
-					if (unlikely((status & rx_not_ls)))
-						goto read_again;
-
-					count++;
-					continue;
+					goto next;
 				} else if (xdp_res & (STMMAC_XDP_TX |
 						      STMMAC_XDP_REDIRECT)) {
 					xdp_status |= xdp_res;
Signature · 1 line
2.53.0
author maintainer
#114 lore raw

PATCH 113/990 bpf: Refuse to map an arena at address 0

In reply to Greg Kroah-Hartman

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

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

From: Alexei Starovoitov <[email protected]>

[ Upstream commit ca580b034380fa9a69cc973637d1859ec4f5b344 ]

The first mmap() of an arena sets user_vm_start and user_vm_end. Each subsequent mmap() must use the same range. The value 0 in user_vm_start means that the range is not set, but a mapping can start at address 0. Then arena_map_mmap() does not check vm_start and sets user_vm_start again. The range tree counts pages from user_vm_start. With a new user_vm_start it reports allocated pages as free, and apply_range_set_cb() fails with -EBUSY.

An arena at address 0 is not useful, because the verifier rejects all progs that refer to it. Return -EINVAL from arena_get_unmapped_area(). It runs before mmap() removes the old mappings in the range.

Fixes 317460317a02 ("bpf: Introduce bpf_arena.")
---
 kernel/bpf/arena.c | 3 +++
 1 file changed, 3 insertions(+)
kernel/bpf/arena.c +3 -0
index 51227c8d2b1e4..d1f0a7222d941 100644
@@ -349,6 +349,9 @@ static unsigned long arena_get_unmapped_area(struct file *filp, unsigned long ad
 	ret = mm_get_unmapped_area(current->mm, filp, addr, len * 2, 0, flags);
 	if (IS_ERR_VALUE(ret))
 		return ret;
+	if (!ret)
+		/* user_vm_start == 0 means that the user range is not set yet */
+		return -EINVAL;
 	if ((ret >> 32) == ((ret + len - 1) >> 32))
 		return ret;
 	if (WARN_ON_ONCE(arena->user_vm_start))
Signature · 1 line
2.53.0
author maintainer
#141 lore raw

PATCH 140/990 net: stmmac: copy XDP metadata in AF_XDP zero-copy RX

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Bianconi <[email protected]>

[ Upstream commit 41d78e9ac0984f0e9577e5312e62400b5a6760c8 ]

stmmac_construct_skb_zc() reserves headroom for the XDP metadata and records the length reported by the XDP program, but only copies the packet data starting at xdp->data. The bytes in [xdp->data_meta, xdp->data) are never copied into the new skb, so the skb advertises metadata that is not there: after eth_type_trans() anchors mac_header, data_meta points at uninitialized headroom instead of what the program wrote.

Copy the metadata together with the packet data starting at xdp->data_meta, leaving skb->data at the start of the frame and the metadata immediately before it, and record its length. This keeps data_meta valid for the stack and TC BPF after eth_type_trans() anchors mac_header.

Fixes bba2556efad6 ("net: stmmac: Enable RX via AF_XDP zero-copy")
---
 drivers/net/ethernet/stmicro/stmmac/stmmac_main.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +2 -1
index a79332f92be79..4d5e3ec64dfa5 100644
@@ -5201,7 +5201,8 @@ static struct sk_buff *stmmac_construct_skb_zc(struct stmmac_channel *ch,
 		return NULL;
 
 	skb_reserve(skb, xdp->data - xdp->data_hard_start);
-	memcpy(__skb_put(skb, datasize), xdp->data, datasize);
+	__skb_put(skb, datasize);
+	memcpy(skb->data - metasize, xdp->data_meta, datasize + metasize);
 	if (metasize)
 		skb_metadata_set(skb, metasize);
 
Signature · 1 line
2.53.0
author maintainer
#142 lore raw

PATCH 141/990 net: stmmac: fix VLAN tag stripping on short and non-linear RX frames

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Bianconi <[email protected]>

[ Upstream commit 68bdbffcae08699af5c16f7a2ec61a5489b78dbe ]

stmmac_rx_vlan() reads the VLAN header straight from skb->data and removes it with skb_pull(), assuming the header is fully present in the linear part of the skb. XDP can change the frame length and head layout before the tag is stripped.

An XDP program can use bpf_xdp_adjust_tail() to shrink a frame to as little as ETH_HLEN while bytes 12-13 still contain a VLAN ethertype. The driver then reads h_vlan_TCI past skb->len and pops the tag, leaving less than ETH_HLEN in the skb. eth_type_trans() cannot pull the MAC header, so a malformed skb is passed up. The TCI is also read from the wrong place when the tag is not fully in the linear head, e.g. when it spans into a frag.

Read h_vlan_proto after pulling ETH_HLEN into the linear part, and check it together with the device features. Only if the tag is actually going to be popped, pull VLAN_ETH_HLEN and re-derive the header pointer afterwards, as pskb_may_pull() may reallocate the skb head. Return an error so the callers can drop a frame that claims a VLAN tag but cannot provide the full header. This also drops and counts frames shorter than ETH_HLEN in rx_dropped, even when VLAN RX offload is disabled; bpf_xdp_adjust_head() and bpf_xdp_adjust_tail() cannot produce such a frame, so it only affects a runt that reaches the driver, and dropping it is safer than handing it to eth_type_trans().

Also move the XDP metadata written with bpf_xdp_adjust_meta() together with the MAC header when the tag is popped, so data_meta still points at the metadata after eth_type_trans() anchors mac_header, instead of at the first bytes of the destination MAC.

---
 .../net/ethernet/stmicro/stmmac/stmmac_main.c | 48 +++++++++++++------
 1 file changed, 33 insertions(+), 15 deletions(-)
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +33 -15
index 4d5e3ec64dfa5..123f2415e745e 100644
@@ -4832,22 +4832,35 @@ static netdev_features_t stmmac_features_check(struct sk_buff *skb,
 	return vlan_features_check(skb, features);
 }
 
-static void stmmac_rx_vlan(struct net_device *dev, struct sk_buff *skb)
+static int stmmac_rx_vlan(struct net_device *dev, struct sk_buff *skb)
 {
-	struct vlan_ethhdr *veth = skb_vlan_eth_hdr(skb);
-	__be16 vlan_proto = veth->h_vlan_proto;
-	u16 vlanid;
+	struct vlan_ethhdr *veth;
 
-	if ((vlan_proto == htons(ETH_P_8021Q) &&
+	if (!pskb_may_pull(skb, ETH_HLEN))
+		return -EINVAL;
+
+	veth = skb_vlan_eth_hdr(skb);
+	if ((veth->h_vlan_proto == htons(ETH_P_8021Q) &&
 	     dev->features & NETIF_F_HW_VLAN_CTAG_RX) ||
-	    (vlan_proto == htons(ETH_P_8021AD) &&
+	    (veth->h_vlan_proto == htons(ETH_P_8021AD) &&
 	     dev->features & NETIF_F_HW_VLAN_STAG_RX)) {
+		__be16 vlan_proto = veth->h_vlan_proto;
+		u8 meta_len = skb_metadata_len(skb);
+		u16 vlanid;
+
 		/* pop the vlan tag */
+		if (!pskb_may_pull(skb, VLAN_ETH_HLEN))
+			return -EINVAL;
+
+		veth = skb_vlan_eth_hdr(skb);
 		vlanid = ntohs(veth->h_vlan_TCI);
-		memmove(skb->data + VLAN_HLEN, veth, ETH_ALEN * 2);
+		memmove(skb->data - meta_len + VLAN_HLEN,
+			skb->data - meta_len, meta_len + ETH_ALEN * 2);
 		skb_pull(skb, VLAN_HLEN);
 		__vlan_hwaccel_put_tag(skb, vlan_proto, vlanid);
 	}
+
+	return 0;
 }
 
 /**
@@ -5228,12 +5241,15 @@ static void stmmac_dispatch_skb_zc(struct stmmac_priv *priv, u32 queue,
 	}
 
 	stmmac_get_rx_hwtstamp(priv, p, np, skb);
-	if (priv->hw->hw_vlan_en)
+	if (priv->hw->hw_vlan_en) {
 		/* MAC level stripping. */
 		stmmac_rx_hw_vlan(priv, priv->hw, p, skb);
-	else
-		/* Driver level stripping. */
-		stmmac_rx_vlan(priv->dev, skb);
+	} else if (stmmac_rx_vlan(priv->dev, skb)) {
+		dev_kfree_skb_any(skb);
+		priv->xstats.rx_dropped++;
+		return;
+	}
+
 	skb->protocol = eth_type_trans(skb, priv->dev);
 
 	if (unlikely(!coe) || !stmmac_has_ip_ethertype(skb))
@@ -5785,12 +5801,14 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)
 
 		stmmac_get_rx_hwtstamp(priv, p, np, skb);
 
-		if (priv->hw->hw_vlan_en)
+		if (priv->hw->hw_vlan_en) {
 			/* MAC level stripping. */
 			stmmac_rx_hw_vlan(priv, priv->hw, p, skb);
-		else
-			/* Driver level stripping. */
-			stmmac_rx_vlan(priv->dev, skb);
+		} else if (stmmac_rx_vlan(priv->dev, skb)) {
+			dev_kfree_skb_any(skb);
+			rx_dropped++;
+			goto next;
+		}
 
 		skb->protocol = eth_type_trans(skb, priv->dev);
 
Signature · 1 line
2.53.0
author maintainer
#143 lore raw

PATCH 142/990 net: stmmac: fix XDP RX buffer DMA sync length

In reply to Greg Kroah-Hartman

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

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

From: Lorenzo Bianconi <[email protected]>

[ Upstream commit 363ff816277d4c7064514b160e655bed1dfb3ed8 ]

stmmac_rx() bounded the DMA sync length by the largest data_end seen before and after the XDP program and passed it to page_pool_put_page() on the XDP_CONSUMED path. bpf_xdp_adjust_tail() zeroes the grown area, which dirties the CPU cache, but a later negative adjust only moves data_end back. If the program grows and then shrinks the tail, both endpoints miss the zeroed range, so those dirty cache lines are not written back before the page is reused.

The length was also wrong since commit 88095728511e ("net: stmmac: fix rx Scatter-Gather support") moved the page_pool DMA window to offset 0 and set max_len to dma_buf_sz + page_offset: the driver still subtracted buf->page_offset, so it synced [base, data_end - page_offset) instead of [base, data_end).

On a non-coherent platform those dirty lines can be evicted after the device has DMA'd the next frame into the recycled page and corrupt it.

Sync the whole page_pool DMA window on the XDP_CONSUMED path with page_pool_recycle_direct(), as the PASS path and page_pool allocation already do. The device only writes [page_offset, page_offset + dma_buf_sz), so syncing [base, base + max_len) covers every cache line it can touch, regardless of how the program adjusted the packet.

Fixes be8b38a722e6 ("net: stmmac: Add support for XDP_TX action")
Fixes 88095728511e ("net: stmmac: fix rx Scatter-Gather support")
---
 .../net/ethernet/stmicro/stmmac/stmmac_main.c   | 17 ++---------------
 1 file changed, 2 insertions(+), 15 deletions(-)
drivers/net/ethernet/stmicro/stmmac/stmmac_main.c +2 -15
index 123f2415e745e..2e7b146895ba8 100644
@@ -5689,8 +5689,6 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)
 			len -= ETH_FCS_LEN;
 
 		if (!skb) {
-			unsigned int pre_len, sync_len;
-
 			/* Each frame starts here: reset the FCS handling */
 			fcs_stripped = false;
 
@@ -5708,29 +5706,18 @@ static int stmmac_rx(struct stmmac_priv *priv, int limit, u32 queue)
 			xdp_prepare_buff(&ctx.xdp, page_address(buf->page),
 					 buf->page_offset, buf1_len, true);
 
-			pre_len = ctx.xdp.data_end - ctx.xdp.data_hard_start -
-				  buf->page_offset;
-
 			ctx.priv = priv;
 			ctx.desc = p;
 			ctx.ndesc = np;
 
 			skb = stmmac_xdp_run_prog(priv, &ctx.xdp);
-			/* Due xdp_adjust_tail: DMA sync for_device
-			 * cover max len CPU touch
-			 */
-			sync_len = ctx.xdp.data_end - ctx.xdp.data_hard_start -
-				   buf->page_offset;
-			sync_len = max(sync_len, pre_len);
-
 			/* For Not XDP_PASS verdict */
 			if (IS_ERR(skb)) {
 				unsigned int xdp_res = -PTR_ERR(skb);
 
 				if (xdp_res & STMMAC_XDP_CONSUMED) {
-					page_pool_put_page(rx_q->page_pool,
-							   virt_to_head_page(ctx.xdp.data),
-							   sync_len, true);
+					page_pool_recycle_direct(rx_q->page_pool,
+								 virt_to_head_page(ctx.xdp.data));
 					buf->page = NULL;
 					rx_dropped++;
 					goto next;
Signature · 1 line
2.53.0
author maintainer
#144 lore raw

PATCH 143/990 ata: libata-core: Check device support before querying power state

In reply to Greg Kroah-Hartman

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

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

From: Giuseppe Piscitelli <[email protected]>

[ Upstream commit ec585ac78742527f80495dd8f451dcda7e9e7f59 ]

The standby path queries the power state before checking whether the device accepts ATA power-management commands. This sends CHECK POWER MODE to ATAPI devices, including the QEMU DVD-ROM, which rejects it.

Run the existing taskfile initialization and device-class check first, as the active-power path already does.

Fixes 9cec467d0502 ("ata: libata-core: Do not call ata_dev_power_set_standby() twice")
---
 drivers/ata/libata-core.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
drivers/ata/libata-core.c +4 -4
index 29394d18e7e83..209bd48ee8615 100644
@@ -2046,6 +2046,10 @@ void ata_dev_power_set_standby(struct ata_device *dev)
 	struct ata_taskfile tf;
 	unsigned int err_mask;
 
+	/* Issue STANDBY IMMEDIATE command only if supported by the device */
+	if (!ata_dev_power_init_tf(dev, &tf, false))
+		return;
+
 	/* If the device is already sleeping or in standby, do nothing. */
 	if ((dev->flags & ATA_DFLAG_SLEEPING) ||
 	    !ata_dev_power_is_active(dev))
@@ -2064,10 +2068,6 @@ void ata_dev_power_set_standby(struct ata_device *dev)
 	    system_entering_hibernation())
 		return;
 
-	/* Issue STANDBY IMMEDIATE command only if supported by the device */
-	if (!ata_dev_power_init_tf(dev, &tf, false))
-		return;
-
 	ata_dev_notice(dev, "Entering standby power mode\n");
 
 	err_mask = ata_exec_internal(dev, &tf, NULL, DMA_NONE, NULL, 0, 0);
Signature · 1 line
2.53.0
author maintainer
#145 lore raw

PATCH 144/990 net: lan966x: dont free XDP buffers in fdma tx clear with budget 0

In reply to Greg Kroah-Hartman

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

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

From: Daniel Machon <[email protected]>

[ Upstream commit 263a5514cb9535380734b5e300b298f82570eb57 ]

lan966x_fdma_tx_clear_buf() runs from the NAPI poll and frees the buffers of completed tx DCBs with napi_consume_skb(), page_pool_recycle_direct() and xdp_return_frame_bulk().

netpoll calls the NAPI poll with a budget of 0 and hardirqs disabled. With a budget of 0, a driver cannot call any XDP or page pool API.

Before this patch, the XDP_TX pages and ndo_xdp_xmit frames are freed regardless of the budget. With netconsole on the port that owns the FDMA NAPI, such a buffer is freed with hardirqs disabled, and __page_pool_put_page() warns via lockdep_assert_no_hardirq().

Leave the XDP buffers of completed DCBs in place when the budget is 0, and free them in the next NAPI poll. napi_consume_skb() already handles a budget of 0, so skbs are still freed.

Found by an AI code review agent. Reproduced on a lan9668 board with a modified kernel that runs the NAPI poll with a budget of 0 and hardirqs disabled. With the fix the warning is gone.

---
 drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c | 6 ++++++
 1 file changed, 6 insertions(+)
drivers/net/ethernet/microchip/lan966x/lan966x_fdma.c +6 -0
index 11a341fc45779..6dad3c019f01c 100644
@@ -354,6 +354,12 @@ static void lan966x_fdma_tx_clear_buf(struct lan966x *lan966x, int weight)
 		if (!fdma_db_is_done(db))
 			continue;
 
+		/* XDP and page pool APIs can't be used with a budget of 0.
+		 * Leave these buffers for the next NAPI poll.
+		 */
+		if (!weight && !dcb_buf->use_skb)
+			continue;
+
 		dcb_buf->dev->stats.tx_packets++;
 		dcb_buf->dev->stats.tx_bytes += dcb_buf->len;
 
Signature · 1 line
2.53.0
author maintainer
#146 lore raw

PATCH 145/990 drm/panel: visionox-r66451: Send the brightness value MSB first

In reply to Greg Kroah-Hartman

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

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

From: Vladimir Zapolskiy <[email protected]>

[ Upstream commit 00fe6be187ffde738fdb71ea7deb671fc939e583 ]

The panel expects to get two bytes of the DCS Set Display Brightness command with the most significant byte first, and it uses the lower 12 bits of the value, use mipi_dsi_dcs_set_display_brightness_large() to correct the programmed brightness values.

Tested on the SM8350-HDK display card, the display brightness increases gradually with:

  for v in $(seq 16 16 4095); do sleep 0.1; \
    echo $v > /sys/class/backlight/ae94000.dsi.0/brightness; \
  done

while without the change the display is dark during all writes.

Fixes a6dfab2738fc ("drm/panel: Add driver for Visionox r66451 panel")
---
 drivers/gpu/drm/panel/panel-visionox-r66451.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/panel/panel-visionox-r66451.c +1 -1
index 690cccedd438f..0ce5c670dbb9b 100644
@@ -227,7 +227,7 @@ static int visionox_r66451_bl_update_status(struct backlight_device *bl)
 	struct mipi_dsi_device *dsi = bl_get_data(bl);
 	u16 brightness = backlight_get_brightness(bl);
 
-	return mipi_dsi_dcs_set_display_brightness(dsi, brightness);
+	return mipi_dsi_dcs_set_display_brightness_large(dsi, brightness);
 }
 
 static const struct backlight_ops visionox_r66451_bl_ops = {
Signature · 1 line
2.53.0
author maintainer
#147 lore raw

PATCH 146/990 drm/panel: visionox-r66451: Wait longer after the panel reset

In reply to Greg Kroah-Hartman

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

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

From: Vladimir Zapolskiy <[email protected]>

[ Upstream commit b4b2778d5e175b166e4a27e5df5d61da468ad004 ]

The initialization sequence is sent 10ms after the panel reset is deasserted, however on the SM8350-HDK display card the panel does not answer a DCS read at that time, as a result the panel initialization commands are lost, and the panel does not exit sleep mode and the display stays black. With the first command sent about 15ms after the reset the panel comes up reliably, so wait 20ms after deasserting the reset.

Fixes a6dfab2738fc ("drm/panel: Add driver for Visionox r66451 panel")
---
 drivers/gpu/drm/panel/panel-visionox-r66451.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/gpu/drm/panel/panel-visionox-r66451.c +1 -1
index 0ce5c670dbb9b..d2cbc60af1179 100644
@@ -36,7 +36,7 @@ static void visionox_r66451_reset(struct visionox_r66451 *ctx)
 	gpiod_set_value_cansleep(ctx->reset_gpio, 1);
 	usleep_range(10000, 10100);
 	gpiod_set_value_cansleep(ctx->reset_gpio, 0);
-	usleep_range(10000, 10100);
+	usleep_range(20000, 21000);
 }
 
 static int visionox_r66451_on(struct visionox_r66451 *ctx)
Signature · 1 line
2.53.0
author maintainer
#148 lore raw

PATCH 147/990 sfc: ptp: drop the stale frequency reset in efx_ptp_start()

In reply to Greg Kroah-Hartman

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

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

From: Alex Austin <[email protected]>

[ Upstream commit 21d4917cfc8b6837c44d8aa186941a6a16ec17a0 ]

FW does not touch the clock frequency state on MC_CMD_PTP_OP_DISABLE or MC_CMD_PTP_OP_ENABLE, so the driver doesn't need to either. Doing so just desyncs the driver's cached current_adjfreq from what FW still has programmed.

Resetting current_adjfreq to 0 here means the first efx_phc_adjtime() call after efx_ptp_start() reprograms the NIC's clock frequency to 0, since efx_phc_adjtime() always sends current_adjfreq to FW alongside the time step. efx_ptp_start() runs on every SIOCSHWTSTAMP mode change, on ifup, and on the reset_required path in efx_ptp_worker(), so each of those silently drops any frequency correction the PTP servo had already applied.

efx_ptp_start() is also reached from reset recovery, but that is fine:
on an FLR or PCIe reset FW does not touch the NIC clock, and on a full MC reboot the clock is reset to 1970, so a stale current_adjfreq from before the reset is hardly consequential - especially as it is bound to MAX_PPB, 1000000 ppb.

Fixes 7c236c43b838 ("sfc: Add support for IEEE-1588 PTP")
---
 drivers/net/ethernet/sfc/ptp.c | 1 -
 1 file changed, 1 deletion(-)
drivers/net/ethernet/sfc/ptp.c +0 -1
index 4c7222bf26bec..dbd7281f44b3e 100644
@@ -1446,7 +1446,6 @@ static int efx_ptp_start(struct efx_nic *efx)
 		goto fail;
 
 	ptp->evt_frag_idx = 0;
-	ptp->current_adjfreq = 0;
 
 	return 0;
 
Signature · 1 line
2.53.0
author maintainer
#149 lore raw

PATCH 148/990 sfc: ptp: serialize host and MC synchronization transactions

In reply to Greg Kroah-Hartman

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

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

From: Alex Austin <[email protected]>

[ Upstream commit f707347b33feebdd67633bccea52f96807c18d6e ]

efx_ptp_synchronize() clears the MC-ready DMA flag before efx_mcdi_rpc_start() acquires the MCDI interface, and processes results into ptp->timeset[] after efx_mcdi_rpc_finish() has released it. The PPS worker and the hwtstamp enable path can therefore clobber each other's handshake flag and timesets.

Hold a PHC mutex across the whole transaction and over the clock operations, so efx_phc_settime() reads and adjusts atomically and current_adjfreq is consistently read and written under one lock. Also bail out when efx_mcdi_rpc_start() fails rather than finishing an RPC that was never acquired.

---
 drivers/net/ethernet/sfc/ptp.c | 81 +++++++++++++++++++++++-----------
 1 file changed, 55 insertions(+), 26 deletions(-)
drivers/net/ethernet/sfc/ptp.c +55 -26
index dbd7281f44b3e..f8a88133b15b1 100644
@@ -36,6 +36,7 @@
 #include <linux/errno.h>
 #include <linux/ktime.h>
 #include <linux/module.h>
+#include <linux/mutex.h>
 #include <linux/pps_kernel.h>
 #include <linux/ptp_clock_kernel.h>
 #include "net_driver.h"
@@ -272,6 +273,8 @@ struct efx_ptp_rxfilter {
  * frequency adjustment into a fixed point fractional nanosecond format.
  * @current_adjfreq: Current ppb adjustment.
  * @phc_clock: Pointer to registered phc device (if primary function)
+ * @phc_lock: Serializes PHC commands and synchronization, and protects
+ *	      @current_adjfreq
  * @phc_clock_info: Registration structure for phc device
  * @pps_work: pps work task for handling pps events
  * @pps_workwq: pps work queue
@@ -331,6 +334,7 @@ struct efx_ptp_data {
 	unsigned int adjfreq_ppb_shift;
 	s64 current_adjfreq;
 	struct ptp_clock *phc_clock;
+	struct mutex phc_lock;
 	struct ptp_clock_info phc_clock_info;
 	struct work_struct pps_work;
 	struct workqueue_struct *pps_workwq;
@@ -1008,7 +1012,14 @@ efx_ptp_process_times(struct efx_nic *efx, MCDI_DECLARE_STRUCT_PTR(synch_buf),
 	return 0;
 }
 
-/* Synchronize times between the host and the MC */
+/* Synchronize times between the host and the MC.
+ *
+ * The MC serializes PTP requests, so MC_CMD_PTP_OP_ADJUST cannot be applied
+ * while MC_CMD_PTP_OP_SYNCHRONIZE is collecting timesets. This holds across
+ * functions of a controller, which share the clock but adjust it only through
+ * the function that registered it, so a secondary function can capture here
+ * without serializing against the primary.
+ */
 static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings)
 {
 	struct efx_ptp_data *ptp = efx->ptp_data;
@@ -1027,11 +1038,14 @@ static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings)
 	MCDI_SET_QWORD(synch_buf, PTP_IN_SYNCHRONIZE_START_ADDR,
 		       ptp->start.dma_addr);
 
+	mutex_lock(&ptp->phc_lock);
+
 	/* Clear flag that signals MC ready */
 	WRITE_ONCE(*start, 0);
 	rc = efx_mcdi_rpc_start(efx, MC_CMD_PTP, synch_buf,
 				MC_CMD_PTP_IN_SYNCHRONIZE_LEN);
-	EFX_WARN_ON_ONCE_PARANOID(rc);
+	if (rc)
+		goto out;
 
 	/* Wait for start from MCDI (or timeout) */
 	timeout = jiffies + msecs_to_jiffies(MAX_SYNCHRONISE_WAIT_MS);
@@ -1062,11 +1076,13 @@ static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings)
 			++ptp->no_time_syncs;
 	}
 
+out:
 	/* Increment the bad syncs counter if the synchronize fails, whatever
 	 * the reason.
 	 */
 	if (rc != 0)
 		++ptp->bad_syncs;
+	mutex_unlock(&ptp->phc_lock);
 
 	return rc;
 }
@@ -1569,6 +1585,7 @@ int efx_ptp_probe(struct efx_nic *efx, struct efx_channel *channel)
 	if (!efx->ptp_data)
 		return -ENOMEM;
 
+	mutex_init(&ptp->phc_lock);
 	ptp->efx = efx;
 	ptp->channel = channel;
 
@@ -1640,6 +1657,7 @@ int efx_ptp_probe(struct efx_nic *efx, struct efx_channel *channel)
 	efx_nic_free_buffer(efx, &ptp->start);
 
 fail1:
+	mutex_destroy(&ptp->phc_lock);
 	kfree(efx->ptp_data);
 	efx->ptp_data = NULL;
 
@@ -1694,6 +1712,7 @@ void efx_ptp_remove(struct efx_nic *efx)
 	destroy_workqueue(efx->ptp_data->workwq);
 
 	efx_nic_free_buffer(efx, &efx->ptp_data->start);
+	mutex_destroy(&efx->ptp_data->phc_lock);
 	kfree(efx->ptp_data);
 	efx->ptp_data = NULL;
 }
@@ -2105,23 +2124,23 @@ static int efx_phc_adjfine(struct ptp_clock_info *ptp, long scaled_ppm)
 	MCDI_SET_QWORD(inadj, PTP_IN_ADJUST_FREQ, adjustment_ns);
 	MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_SECONDS, 0);
 	MCDI_SET_DWORD(inadj, PTP_IN_ADJUST_NANOSECONDS, 0);
+	mutex_lock(&ptp_data->phc_lock);
 	rc = efx_mcdi_rpc(efx, MC_CMD_PTP, inadj, sizeof(inadj),
 			  NULL, 0, NULL);
-	if (rc != 0)
-		return rc;
-
-	ptp_data->current_adjfreq = adjustment_ns;
-	return 0;
+	if (!rc)
+		ptp_data->current_adjfreq = adjustment_ns;
+	mutex_unlock(&ptp_data->phc_lock);
+	return rc;
 }
 
-static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta)
+static int _efx_phc_adjtime(struct efx_ptp_data *ptp_data, s64 delta)
+	__must_hold(&ptp_data->phc_lock)
 {
-	u32 nic_major, nic_minor;
-	struct efx_ptp_data *ptp_data = container_of(ptp,
-						     struct efx_ptp_data,
-						     phc_clock_info);
-	struct efx_nic *efx = ptp_data->efx;
 	MCDI_DECLARE_BUF(inbuf, MC_CMD_PTP_IN_ADJUST_LEN);
+	struct efx_nic *efx = ptp_data->efx;
+	u32 nic_major, nic_minor;
+
+	lockdep_assert_held(&ptp_data->phc_lock);
 
 	efx->ptp_data->ns_to_nic_time(delta, &nic_major, &nic_minor);
 
@@ -2134,6 +2153,18 @@ static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta)
 			    NULL, 0, NULL);
 }
 
+static int efx_phc_adjtime(struct ptp_clock_info *ptp, s64 delta)
+{
+	struct efx_ptp_data *ptp_data = container_of(ptp, struct efx_ptp_data,
+						  phc_clock_info);
+	int rc;
+
+	mutex_lock(&ptp_data->phc_lock);
+	rc = _efx_phc_adjtime(ptp_data, delta);
+	mutex_unlock(&ptp_data->phc_lock);
+	return rc;
+}
+
 static int efx_phc_gettime(struct ptp_clock_info *ptp, struct timespec64 *ts)
 {
 	struct efx_ptp_data *ptp_data = container_of(ptp,
@@ -2165,23 +2196,21 @@ static int efx_phc_settime(struct ptp_clock_info *ptp,
 {
 	/* Get the current NIC time, efx_phc_gettime.
 	 * Subtract from the desired time to get the offset
-	 * call efx_phc_adjtime with the offset
+	 * call _efx_phc_adjtime with the offset
 	 */
+	struct efx_ptp_data *ptp_data = container_of(ptp, struct efx_ptp_data,
+						  phc_clock_info);
+	struct timespec64 time_now, delta;
 	int rc;
-	struct timespec64 time_now;
-	struct timespec64 delta;
 
+	mutex_lock(&ptp_data->phc_lock);
 	rc = efx_phc_gettime(ptp, &time_now);
-	if (rc != 0)
-		return rc;
-
-	delta = timespec64_sub(*e_ts, time_now);
-
-	rc = efx_phc_adjtime(ptp, timespec64_to_ns(&delta));
-	if (rc != 0)
-		return rc;
-
-	return 0;
+	if (!rc) {
+		delta = timespec64_sub(*e_ts, time_now);
+		rc = _efx_phc_adjtime(ptp_data, timespec64_to_ns(&delta));
+	}
+	mutex_unlock(&ptp_data->phc_lock);
+	return rc;
 }
 
 static int efx_phc_enable(struct ptp_clock_info *ptp,
Signature · 1 line
2.53.0
author maintainer
#150 lore raw

PATCH 149/990 sfc: ptp: avoid racing PPS timestamp updates

In reply to Greg Kroah-Hartman

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

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

From: Alex Austin <[email protected]>

[ Upstream commit 23d23e6c6517d0fea4f64340a23e33c89f82c03c ]

efx_ptp_pps_worker() can race with SIOCHWTSTAMP via efx_ptp_change_mode(). After the worker completes synchronization, the ioctl can start another synchronization and update host_time_pps while the worker copies it into the PPS event. This can report a partially updated timestamp. Serializing synchronization transactions alone does not protect this copy, which happens after phc_lock is released.

Return the timestamp through the caller's own pps_event_time rather than the shared field in efx_ptp_data, so the worker reads storage no one else can write.

---
 drivers/net/ethernet/sfc/ptp.c | 26 ++++++++++++++++----------
 1 file changed, 16 insertions(+), 10 deletions(-)
drivers/net/ethernet/sfc/ptp.c +16 -10
index f8a88133b15b1..66a5342660a8e 100644
@@ -268,7 +268,6 @@ struct efx_ptp_rxfilter {
  * @evt_frag_idx: Current fragment number
  * @evt_code: Last event code
  * @start: Address at which MC indicates ready for synchronisation
- * @host_time_pps: Host time at last PPS
  * @adjfreq_ppb_shift: Shift required to convert scaled parts-per-billion
  * frequency adjustment into a fixed point fractional nanosecond format.
  * @current_adjfreq: Current ppb adjustment.
@@ -330,7 +329,6 @@ struct efx_ptp_data {
 	int evt_frag_idx;
 	int evt_code;
 	struct efx_buffer start;
-	struct pps_event_time host_time_pps;
 	unsigned int adjfreq_ppb_shift;
 	s64 current_adjfreq;
 	struct ptp_clock *phc_clock;
@@ -912,7 +910,8 @@ static void efx_ptp_read_timeset(MCDI_DECLARE_STRUCT_PTR(data),
 static int
 efx_ptp_process_times(struct efx_nic *efx, MCDI_DECLARE_STRUCT_PTR(synch_buf),
 		      size_t response_length,
-		      const struct pps_event_time *last_time)
+		      const struct pps_event_time *last_time,
+		      struct pps_event_time *host_time_pps)
 {
 	unsigned number_readings =
 		MCDI_VAR_ARRAY_LEN(response_length,
@@ -990,6 +989,10 @@ efx_ptp_process_times(struct efx_nic *efx, MCDI_DECLARE_STRUCT_PTR(synch_buf),
 			   "PTP bad synchronisation seconds\n");
 		return -EAGAIN;
 	}
+
+	if (!host_time_pps)
+		return 0;
+
 	delta.tv_sec = (last_sec - start_sec) & 1;
 	delta.tv_nsec =
 		last_time->ts_real.tv_nsec -
@@ -1006,8 +1009,8 @@ efx_ptp_process_times(struct efx_nic *efx, MCDI_DECLARE_STRUCT_PTR(synch_buf),
 	delta.tv_nsec += ktime_to_timespec64(mc_time).tv_nsec;
 
 	/* Set PPS timestamp to match NIC top of second */
-	ptp->host_time_pps = *last_time;
-	pps_sub_ts(&ptp->host_time_pps, delta);
+	*host_time_pps = *last_time;
+	pps_sub_ts(host_time_pps, delta);
 
 	return 0;
 }
@@ -1020,7 +1023,8 @@ efx_ptp_process_times(struct efx_nic *efx, MCDI_DECLARE_STRUCT_PTR(synch_buf),
  * the function that registered it, so a secondary function can capture here
  * without serializing against the primary.
  */
-static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings)
+static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings,
+			       struct pps_event_time *host_time_pps)
 {
 	struct efx_ptp_data *ptp = efx->ptp_data;
 	MCDI_DECLARE_BUF(synch_buf, MC_CMD_PTP_OUT_SYNCHRONIZE_LENMAX);
@@ -1069,7 +1073,7 @@ static int efx_ptp_synchronize(struct efx_nic *efx, unsigned int num_readings)
 				 &response_length);
 	if (rc == 0) {
 		rc = efx_ptp_process_times(efx, synch_buf, response_length,
-					   &last_time);
+					   &last_time, host_time_pps);
 		if (rc == 0)
 			++ptp->good_syncs;
 		else
@@ -1501,14 +1505,15 @@ static void efx_ptp_pps_worker(struct work_struct *work)
 {
 	struct efx_ptp_data *ptp =
 		container_of(work, struct efx_ptp_data, pps_work);
+	struct pps_event_time host_time_pps = {};
 	struct efx_nic *efx = ptp->efx;
 	struct ptp_clock_event ptp_evt;
 
-	if (efx_ptp_synchronize(efx, PTP_SYNC_ATTEMPTS))
+	if (efx_ptp_synchronize(efx, PTP_SYNC_ATTEMPTS, &host_time_pps))
 		return;
 
 	ptp_evt.type = PTP_CLOCK_PPSUSR;
-	ptp_evt.pps_times = ptp->host_time_pps;
+	ptp_evt.pps_times = host_time_pps;
 	ptp_clock_event(ptp->phc_clock, &ptp_evt);
 }
 
@@ -1844,7 +1849,8 @@ int efx_ptp_change_mode(struct efx_nic *efx, bool enable_wanted,
 				rc = efx_ptp_start(efx);
 			if (rc == 0) {
 				rc = efx_ptp_synchronize(efx,
-							 PTP_SYNC_ATTEMPTS * 2);
+							 PTP_SYNC_ATTEMPTS * 2,
+							 NULL);
 				if (rc != 0)
 					efx_ptp_stop(efx);
 			}
Signature · 1 line
2.53.0
author maintainer
#115 lore raw

PATCH 114/990 bpf: Refuse an arena mmap() longer than max_entries pages

In reply to Greg Kroah-Hartman

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

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

From: Alexei Starovoitov <[email protected]>

[ Upstream commit 1e01345b87f13c354687360cb81ed2a521ff2b13 ]

arena_map_alloc() puts max_entries free pages in the range tree of an arena. But the arena kfuncs check their arguments against user_vm_start and user_vm_end. Without map_extra, arena_map_mmap() takes both from the first vma. This vma can be up to 4 GiB long. Then arena_free_pages() also marks pages as free that were never in the range tree. Thus max_entries does not limit the memory of the arena, but these pages are inside kern_vm.

Refuse an mmap() longer than max_entries pages with -E2BIG. With map_extra this limit exists already. libbpf always maps max_entries pages. Replace both SZ_4G checks with this limit, because it is at most 4 GiB.

Fixes 317460317a02 ("bpf: Introduce bpf_arena.")
---
 kernel/bpf/arena.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
kernel/bpf/arena.c +2 -2
index d1f0a7222d941..b3c70596c576e 100644
@@ -333,7 +333,7 @@ static unsigned long arena_get_unmapped_area(struct file *filp, unsigned long ad
 
 	if (pgoff)
 		return -EINVAL;
-	if (len > SZ_4G)
+	if (len > (u64)map->max_entries * PAGE_SIZE)
 		return -E2BIG;
 
 	/* if user_vm_start was specified at arena creation time */
@@ -381,7 +381,7 @@ static int arena_map_mmap(struct bpf_map *map, struct vm_area_struct *vma)
 		return -EBUSY;
 
 	/* Earlier checks should prevent this */
-	if (WARN_ON_ONCE(vma->vm_end - vma->vm_start > SZ_4G || vma->vm_pgoff))
+	if (WARN_ON_ONCE(vma_pages(vma) > map->max_entries || vma->vm_pgoff))
 		return -EFAULT;
 
 	if (remember_vma(arena, vma))
Signature · 1 line
2.53.0
author maintainer
#151 lore raw

PATCH 150/990 virtio-spi: Fix virtio_spi_config kernel-doc

In reply to Greg Kroah-Hartman

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

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

From: Karl Mehltretter <[email protected]>

[ Upstream commit 62b0a9b11e94a4bc7f67c89348d0619cba82b54b ]

struct virtio_spi_config contains max_cs_inactive_ns, but its kernel-doc describes max_cs_incative_ns. This leaves the real member undescribed and adds a nonexistent member to the generated documentation.

Correct the spelling.

Fixes 6a1f3390fafe ("virtio-spi: Add virtio-spi.h")
Assisted-by LLM

Message-ID: <[email protected]>

---
 include/uapi/linux/virtio_spi.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
include/uapi/linux/virtio_spi.h +1 -1
index 8ab3c970cdd31..459c2276c938c 100644
@@ -73,7 +73,7 @@
  * @max_cs_hold_ns: the maximum delay supported before chipselect is deasserted,
  *   in ns unit, 0 means delay is not supported to introduce before chipselect
  *   is deasserted.
- * @max_cs_incative_ns: maximum delay supported after chipselect is deasserted,
+ * @max_cs_inactive_ns: maximum delay supported after chipselect is deasserted,
  *   in ns unit, 0 means delay is not supported to introduce after chipselect is
  *   deasserted.
  */
Signature · 1 line
2.53.0
author maintainer
#152 lore raw

PATCH 151/990 vdpa_sim: serialize IOTLB updates with dataplane access

In reply to Greg Kroah-Hartman

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

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

From: Linfeng Sun <[email protected]>

[ Upstream commit 8517ed4429a2eefd002dce00ea46e23e6714350b ]

The simulator translates IOTLB entries into iovecs or bvecs under iommu_lock, then drops the lock before copying data. A concurrent DMA unmap can delete the mapping and release its pinned backing pages while the copy is still in progress, leading to a UAF in _copy_from_iter().

Use the existing simulator mutex to serialize DMA map changes with the full backend work function. Also make vhost-vdpa stop device access before unpinning the backing pages. Otherwise, waiting in the simulator DMA unmap callback happens after the pages have already been released and cannot protect their lifetime.

Keep iommu_lock for the IOTLB table itself and avoid adding a second long-lived lock to the simulator.

I found this bug myself, though the patch was written with AI assistance.

Fixes 2c53d0f64c06 ("vdpasim: vDPA device simulator")
Assisted-by OpenAI-Codex:GPT-5

Message-ID: <[email protected]>

---
 drivers/vdpa/vdpa_sim/vdpa_sim.c | 4 ++++
 drivers/vhost/vdpa.c             | 3 ++-
 2 files changed, 6 insertions(+), 1 deletion(-)
drivers/vdpa/vdpa_sim/vdpa_sim.c +4 -0
index 44055778b6940..50a28e35d185a 100644
@@ -716,6 +716,7 @@ static int vdpasim_dma_map(struct vdpa_device *vdpa, unsigned int asid,
 	if (asid >= vdpasim->dev_attr.nas)
 		return -EINVAL;
 
+	mutex_lock(&vdpasim->mutex);
 	spin_lock(&vdpasim->iommu_lock);
 	if (vdpasim->iommu_pt[asid]) {
 		vhost_iotlb_reset(&vdpasim->iommu[asid]);
@@ -724,6 +725,7 @@ static int vdpasim_dma_map(struct vdpa_device *vdpa, unsigned int asid,
 	ret = vhost_iotlb_add_range_ctx(&vdpasim->iommu[asid], iova,
 					iova + size - 1, pa, perm, opaque);
 	spin_unlock(&vdpasim->iommu_lock);
+	mutex_unlock(&vdpasim->mutex);
 
 	return ret;
 }
@@ -736,6 +738,7 @@ static int vdpasim_dma_unmap(struct vdpa_device *vdpa, unsigned int asid,
 	if (asid >= vdpasim->dev_attr.nas)
 		return -EINVAL;
 
+	mutex_lock(&vdpasim->mutex);
 	spin_lock(&vdpasim->iommu_lock);
 	if (vdpasim->iommu_pt[asid]) {
 		vhost_iotlb_reset(&vdpasim->iommu[asid]);
@@ -743,6 +746,7 @@ static int vdpasim_dma_unmap(struct vdpa_device *vdpa, unsigned int asid,
 	}
 	vhost_iotlb_del_range(&vdpasim->iommu[asid], iova, iova + size - 1);
 	spin_unlock(&vdpasim->iommu_lock);
+	mutex_unlock(&vdpasim->mutex);
 
 	return 0;
 }
drivers/vhost/vdpa.c +2 -1
index e4ddaf0e5abc6..62c2ea705b38b 100644
@@ -974,6 +974,8 @@ static void vhost_vdpa_pa_unmap(struct vhost_vdpa *v, struct vhost_iotlb *iotlb,
 	unsigned long pfn, pinned;
 
 	while ((map = vhost_iotlb_itree_first(iotlb, start, last)) != NULL) {
+		/* Stop device access before releasing the pinned pages. */
+		vhost_vdpa_general_unmap(v, map, asid);
 		pinned = PFN_DOWN(map->size);
 		for (pfn = PFN_DOWN(map->addr);
 		     pinned > 0; pfn++, pinned--) {
@@ -983,7 +985,6 @@ static void vhost_vdpa_pa_unmap(struct vhost_vdpa *v, struct vhost_iotlb *iotlb,
 			unpin_user_page(page);
 		}
 		atomic64_sub(PFN_DOWN(map->size), &dev->mm->pinned_vm);
-		vhost_vdpa_general_unmap(v, map, asid);
 		vhost_iotlb_map_free(iotlb, map);
 	}
 }
Signature · 1 line
2.53.0
author maintainer
#153 lore raw

PATCH 152/990 vdpa: invalidate DMA mappings before releasing memory

In reply to Greg Kroah-Hartman

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

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

From: Linfeng Sun <[email protected]>

[ Upstream commit acbf36deb53d9e14e4768bf58883795a8232aa5b ]

vdpa can release pinned pages and file references before the device stops using the corresponding mappings, allowing stale DMA to corrupt memory.

Invalidate mappings before dropping their backing references. For set_map backends, publish an IOTLB without the invalidated range and keep the old references if that fails. Do this immediately even within a batch.

Serialize vdpa_sim set_map updates with its worker so publishing a new map cannot race an active transfer. Abort mlx5 map replacement when resumable virtqueues cannot be suspended, since changing the memory region while those queues remain active would preserve the same stale DMA window. Reject zero-sized and wrapping invalidations before calculating their inclusive range end.

I found this bug myself, though the patch was written with AI assistance.

Fixes 4c8cf31885f6 ("vhost: introduce vDPA-based backend")
Assisted-by OpenAI-Codex:GPT-5

Message-ID: <[email protected]>

---
 drivers/vdpa/mlx5/net/mlx5_vnet.c | 10 +++++++-
 drivers/vdpa/vdpa_sim/vdpa_sim.c  |  3 +++
 drivers/vhost/vdpa.c              | 40 ++++++++++++++++++++++++-------
 3 files changed, 43 insertions(+), 10 deletions(-)
drivers/vdpa/mlx5/net/mlx5_vnet.c +9 -1
index c49167d760a62..6cf55ce8ad4a8 100644
@@ -3048,7 +3048,15 @@ static int mlx5_vdpa_change_map(struct mlx5_vdpa_dev *mvdev,
 	bool teardown = !is_resumable(ndev);
 	int err;
 
-	suspend_vqs(ndev, 0, ndev->cur_num_vqs);
+	if ((mvdev->status & VIRTIO_CONFIG_S_DRIVER_OK) && !mvdev->suspended) {
+		err = suspend_vqs(ndev, 0, ndev->cur_num_vqs);
+		if (err && !teardown) {
+			for (int i = 0; i < ndev->cur_num_vqs; i++)
+				resume_vqs(ndev, i, 1);
+			mlx5_vdpa_put_mr(mvdev, new_mr);
+			return err;
+		}
+	}
 	if (teardown) {
 		err = save_channels_info(ndev);
 		if (err) {
drivers/vdpa/vdpa_sim/vdpa_sim.c +3 -0
index 50a28e35d185a..aeed6bab3e174 100644
@@ -641,6 +641,7 @@ static int vdpasim_set_map(struct vdpa_device *vdpa, unsigned int asid,
 	if (asid >= vdpasim->dev_attr.nas)
 		return -EINVAL;
 
+	mutex_lock(&vdpasim->mutex);
 	spin_lock(&vdpasim->iommu_lock);
 
 	iommu = &vdpasim->iommu[asid];
@@ -655,11 +656,13 @@ static int vdpasim_set_map(struct vdpa_device *vdpa, unsigned int asid,
 			goto err;
 	}
 	spin_unlock(&vdpasim->iommu_lock);
+	mutex_unlock(&vdpasim->mutex);
 	return 0;
 
 err:
 	vhost_iotlb_reset(iommu);
 	spin_unlock(&vdpasim->iommu_lock);
+	mutex_unlock(&vdpasim->mutex);
 	return ret;
 }
 
drivers/vhost/vdpa.c +31 -9
index 62c2ea705b38b..eeb57c832d740 100644
@@ -996,10 +996,10 @@ static void vhost_vdpa_va_unmap(struct vhost_vdpa *v, struct vhost_iotlb *iotlb,
 	struct vdpa_map_file *map_file;
 
 	while ((map = vhost_iotlb_itree_first(iotlb, start, last)) != NULL) {
+		vhost_vdpa_general_unmap(v, map, asid);
 		map_file = (struct vdpa_map_file *)map->opaque;
 		fput(map_file->file);
 		kfree(map_file);
-		vhost_vdpa_general_unmap(v, map, asid);
 		vhost_iotlb_map_free(iotlb, map);
 	}
 }
@@ -1073,21 +1073,39 @@ static int vhost_vdpa_map(struct vhost_vdpa *v, struct vhost_iotlb *iotlb,
 	return 0;
 }
 
-static void vhost_vdpa_unmap(struct vhost_vdpa *v,
-			     struct vhost_iotlb *iotlb,
-			     u64 iova, u64 size)
+static int vhost_vdpa_unmap(struct vhost_vdpa *v,
+			    struct vhost_iotlb *iotlb,
+			    u64 iova, u64 size)
 {
 	struct vdpa_device *vdpa = v->vdpa;
 	const struct vdpa_config_ops *ops = vdpa->config;
+	struct vhost_iotlb_map *map;
+	struct vhost_iotlb new_iotlb;
 	u32 asid = iotlb_to_asid(iotlb);
+	u64 last = iova + size - 1;
+	int ret;
 
-	vhost_vdpa_iotlb_unmap(v, iotlb, iova, iova + size - 1, asid);
+	if (ops->set_map && !ops->dma_map) {
+		vhost_iotlb_init(&new_iotlb, iotlb->limit, iotlb->flags);
+		list_for_each_entry(map, &iotlb->list, link) {
+			if (map->start <= last && map->last >= iova)
+				continue;
+			ret = vhost_iotlb_add_range_ctx(&new_iotlb, map->start,
+							map->last, map->addr,
+							map->perm, map->opaque);
+			if (ret)
+				goto reset;
+		}
 
-	if (ops->set_map) {
-		if (!v->in_batch)
-			ops->set_map(vdpa, asid, iotlb);
+		ret = ops->set_map(vdpa, asid, &new_iotlb);
+reset:
+		vhost_iotlb_reset(&new_iotlb);
+		if (ret)
+			return ret;
 	}
 
+	vhost_vdpa_iotlb_unmap(v, iotlb, iova, last, asid);
+	return 0;
 }
 
 static int vhost_vdpa_va_map(struct vhost_vdpa *v,
@@ -1337,7 +1355,11 @@ static int vhost_vdpa_process_iotlb_msg(struct vhost_dev *dev, u32 asid,
 		r = vhost_vdpa_process_iotlb_update(v, iotlb, msg);
 		break;
 	case VHOST_IOTLB_INVALIDATE:
-		vhost_vdpa_unmap(v, iotlb, msg->iova, msg->size);
+		if (!msg->size || msg->iova > U64_MAX - msg->size + 1) {
+			r = -EINVAL;
+			break;
+		}
+		r = vhost_vdpa_unmap(v, iotlb, msg->iova, msg->size);
 		break;
 	case VHOST_IOTLB_BATCH_BEGIN:
 		v->batch_asid = asid;
Signature · 1 line
2.53.0
author maintainer
#154 lore raw

PATCH 153/990 vhost-scsi: preserve event ordering

In reply to Greg Kroah-Hartman

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

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

From: Jia Jia <[email protected]>

[ Upstream commit a9a428115b7d8aa45e12e41899f90f60551bfa82 ]

vhost_scsi_send_evt() uses llist_add(), so pending events are LIFO. vhost_scsi_complete_events() walks the detached list directly. This can deliver a later hotplug or hotunplug event before an earlier one.

Reverse the detached list before processing it.
This keeps delivery in enqueue order.

Fixes a6c9af87363c ("tcm_vhost: Add hotplug/hotunplug support")

Message-ID: <[email protected]>

---
 drivers/vhost/scsi.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/vhost/scsi.c +1 -1
index fac400b25dad7..4e078d439836a 100644
@@ -636,7 +636,7 @@ static void vhost_scsi_complete_events(struct vhost_scsi *vs, bool drop)
 	struct llist_node *llnode;
 
 	mutex_lock(&vq->mutex);
-	llnode = llist_del_all(&vs->vs_event_list);
+	llnode = llist_reverse_order(llist_del_all(&vs->vs_event_list));
 	llist_for_each_entry_safe(evt, t, llnode, list) {
 		if (!drop)
 			vhost_scsi_do_evt_work(vs, evt);
Signature · 1 line
2.53.0
author maintainer
#155 lore raw

PATCH 154/990 vhost-scsi: do not relock event vq mutex on send_evt fallback

In reply to Greg Kroah-Hartman

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

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

From: Jia Jia <[email protected]>

[ Upstream commit a016d03a9cfe29aeeba438f32f8e8f63291e3275 ]

vhost_scsi_send_evt() is called with the event virtqueue mutex held. If the worker is gone, the fallback currently calls vhost_scsi_complete_events(), which tries to acquire the same mutex again and deadlocks the caller.

Split event completion into a helper for callers that already hold the mutex and a locking wrapper for the event worker. Use the helper on the fallback path.

Fixes b1b2ce58ed23 ("vhost-scsi: Handle vhost_vq_work_queue failures for events")

Message-ID: <[email protected]>

---
 drivers/vhost/scsi.c | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)
drivers/vhost/scsi.c +11 -4
index 4e078d439836a..d39dc7d215c09 100644
@@ -629,19 +629,26 @@ vhost_scsi_do_evt_work(struct vhost_scsi *vs, struct vhost_scsi_evt *evt)
 	vhost_scsi_log_write(vq, vq_log, log_num);
 }
 
-static void vhost_scsi_complete_events(struct vhost_scsi *vs, bool drop)
+/* Caller must hold the event virtqueue mutex. */
+static void __vhost_scsi_complete_events(struct vhost_scsi *vs, bool drop)
 {
-	struct vhost_virtqueue *vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
 	struct vhost_scsi_evt *evt, *t;
 	struct llist_node *llnode;
 
-	mutex_lock(&vq->mutex);
 	llnode = llist_reverse_order(llist_del_all(&vs->vs_event_list));
 	llist_for_each_entry_safe(evt, t, llnode, list) {
 		if (!drop)
 			vhost_scsi_do_evt_work(vs, evt);
 		vhost_scsi_free_evt(vs, evt);
 	}
+}
+
+static void vhost_scsi_complete_events(struct vhost_scsi *vs, bool drop)
+{
+	struct vhost_virtqueue *vq = &vs->vqs[VHOST_SCSI_VQ_EVT].vq;
+
+	mutex_lock(&vq->mutex);
+	__vhost_scsi_complete_events(vs, drop);
 	mutex_unlock(&vq->mutex);
 }
 
@@ -1835,7 +1842,7 @@ vhost_scsi_send_evt(struct vhost_scsi *vs, struct vhost_virtqueue *vq,
 
 	llist_add(&evt->list, &vs->vs_event_list);
 	if (!vhost_vq_work_queue(vq, &vs->vs_event_work))
-		vhost_scsi_complete_events(vs, true);
+		__vhost_scsi_complete_events(vs, true);
 }
 
 static void vhost_scsi_evt_handle_kick(struct vhost_work *work)
Signature · 1 line
2.53.0
author maintainer
#156 lore raw

PATCH 155/990 vhost: fix dirty logging for in-order used ring entries

In reply to Greg Kroah-Hartman

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

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

From: Linfeng Sun <[email protected]>

[ Upstream commit bfcde6b64769bc168037b8bd882de4def4b2b3f4 ]

With VIRTIO_F_IN_ORDER, one used ring element can represent multiple buffers, so vhost_add_used_n_in_order() can write consecutive elements to nonadjacent slots. Dirty logging combines the initial slot with a length based on the final position, which can miss written elements or log past the end of the ring.

Replay nheads[] after the write barrier and log the written slots, coalescing adjacent elements and splitting at gaps and wraps.

Fixes 67a873df0c41 ("vhost: basic in order support")

Message-ID: <[email protected]>

---
 drivers/vhost/vhost.c | 30 +++++++++++++++++++++++-------
 1 file changed, 23 insertions(+), 7 deletions(-)
drivers/vhost/vhost.c +23 -7
index 78cee55cedf85..87079382c9714 100644
@@ -3136,7 +3136,6 @@ static int vhost_add_used_n_in_order(struct vhost_virtqueue *vq,
 		return -EINVAL;
 
 	start = vq->last_used_idx & (vq->num - 1);
-	used = vq->used->ring + start;
 
 	for (i = 0; i < count; i++) {
 		if (vhost_put_used(vq, &heads[i], start, 1)) {
@@ -3149,14 +3148,31 @@ static int vhost_add_used_n_in_order(struct vhost_virtqueue *vq,
 	}
 
 	if (unlikely(vq->log_used)) {
+		unsigned int log_count = 0;
+		int log_start = 0, next;
+
 		/* Make sure data is seen before log. */
 		smp_wmb();
-		/* Log used ring entry write. */
-		log_used(vq, ((void __user *)used - (void __user *)vq->used),
-			 (vq->num - start) * sizeof *used);
-		if (start + count > vq->num)
-			log_used(vq, 0,
-				 (start + count - vq->num) * sizeof *used);
+		/* Log contiguous runs of used ring entries that were written. */
+		start = vq->last_used_idx & (vq->num - 1);
+		for (i = 0; i < count; i++) {
+			if (!log_count)
+				log_start = start;
+			log_count++;
+
+			next = start + nheads[i];
+			if (next >= vq->num)
+				next -= vq->num;
+			if (i + 1 == count || next != start + 1) {
+				used = vq->used->ring + log_start;
+				log_used(vq,
+					 ((void __user *)used -
+					  (void __user *)vq->used),
+					 log_count * sizeof(*used));
+				log_count = 0;
+			}
+			start = next;
+		}
 	}
 
 	old = vq->last_used_idx;
Signature · 1 line
2.53.0
author maintainer
#157 lore raw

PATCH 156/990 virtio_pci: add missing newline to the pmcsr error message

In reply to Greg Kroah-Hartman

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

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

From: Maoxia <[email protected]>

[ Upstream commit 104d58a6d2592898fbb6989732600b07d543a8e5 ]

The error message emitted when the PCI power management control register cannot be read is not newline-terminated, so the next kernel message is appended to it on the same line.

Add the missing '\n'.

Fixes dff4fa0e5785 ("virtio: Add support for no-reset virtio PCI PM")

Message-ID: <[email protected]>

---
 drivers/virtio/virtio_pci_common.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/virtio/virtio_pci_common.c +1 -1
index 64806d042dbb2..9d4f0f0d70879 100644
@@ -636,7 +636,7 @@ static bool vp_supports_pm_no_reset(struct device *dev)
 
 	pci_read_config_word(pci_dev, pci_dev->pm_cap + PCI_PM_CTRL, &pmcsr);
 	if (PCI_POSSIBLE_ERROR(pmcsr)) {
-		dev_err(dev, "Unable to query pmcsr");
+		dev_err(dev, "Unable to query pmcsr\n");
 		return false;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#158 lore raw

PATCH 157/990 vdpa: fix double free of the reply skb in vdpa_nl_cmd_dev_config_get_doit()

In reply to Greg Kroah-Hartman

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

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

From: Xiang Mei <[email protected]>

[ Upstream commit 1f8824fe7f6eaaf2355404db08d3cd05a28aa576 ]

genlmsg_reply() consumes the reply skb on every outcome: netlink_unicast() frees it whether it queues it, drops it, or bails out early. vdpa_nl_cmd_dev_config_get_doit() lets its return value fall through to the shared error label, which calls nlmsg_free(msg) again and double-frees the sk_buff on any reply failure. The failure is reachable unprivileged:
VDPA_CMD_DEV_CONFIG_GET carries no GENL_ADMIN_PERM, so batching several requests into one sendto() on a socket with a shrunken SO_RCVBUF fills the receive queue, and netlink_attachskb() then takes its MSG_DONTWAIT path, freeing the skb and returning -EAGAIN.

Set msg to NULL once genlmsg_reply() has consumed it so the shared exit path frees the skb only on the early error gotos that still own it; nlmsg_free(NULL) is a no-op.

  BUG: KASAN: slab-use-after-free in sk_skb_reason_drop (net/core/skbuff.c:1220)
  Read of size 4 at addr ffff88800d99d49c by task exploit/147
  Call Trace:
   sk_skb_reason_drop (net/core/skbuff.c:1220)
   vdpa_nl_cmd_dev_config_get_doit (drivers/vdpa/vdpa.c:1324)
   genl_family_rcv_msg_doit (net/netlink/genetlink.c:1114)
   genl_rcv_msg (net/netlink/genetlink.c:1194)
   netlink_rcv_skb (net/netlink/af_netlink.c:2556)
   genl_rcv (net/netlink/genetlink.c:1218)
   netlink_unicast (net/netlink/af_netlink.c:1345)
   netlink_sendmsg (net/netlink/af_netlink.c:1900)
   __sys_sendto (net/socket.c:2281)
   __x64_sys_sendto (net/socket.c:2284)
   entry_SYSCALL_64_after_hwframe (arch/x86/entry/entry_64.S:121)

  The buggy address belongs to the object at ffff88800d99d3c0
   which belongs to the cache skbuff_head_cache of size 232
  The buggy address is located 220 bytes inside of
   freed 232-byte region [ffff88800d99d3c0, ffff88800d99d4a8)
Fixes ad69dd0bf26b ("vdpa: Introduce query of device config layout")
Reported-by [email protected]
Assisted-by Claude:claude-opus-5

Message-ID: <[email protected]>

---
 drivers/vdpa/vdpa.c | 7 ++++---
 1 file changed, 4 insertions(+), 3 deletions(-)
drivers/vdpa/vdpa.c +4 -3
index caf0ee5d6856c..3d25238873afb 100644
@@ -1314,15 +1314,16 @@ static int vdpa_nl_cmd_dev_config_get_doit(struct sk_buff *skb, struct genl_info
 	}
 	err = vdpa_dev_config_fill(vdev, msg, info->snd_portid, info->snd_seq,
 				   0, info->extack);
-	if (!err)
+	if (!err) {
 		err = genlmsg_reply(msg, info);
+		msg = NULL;
+	}
 
 mdev_err:
 	put_device(dev);
 dev_err:
 	up_read(&vdpa_dev_lock);
-	if (err)
-		nlmsg_free(msg);
+	nlmsg_free(msg);
 	return err;
 }
 
Signature · 1 line
2.53.0
author maintainer
#116 lore raw

PATCH 115/990 bpf: Remove the WARN from arena_get_unmapped_area()

In reply to Greg Kroah-Hartman

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

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

From: Alexei Starovoitov <[email protected]>

[ Upstream commit 15dedd4b259289bffb8a5485b81722fdaebac71a ]

The user range of an arena must not cross a 4 GiB boundary. Thus arena_get_unmapped_area() asks the mm for 2 * len bytes and rounds the result up if necessary. If user_vm_start is not 0, addr must be equal to it. A WARN_ON_ONCE() assumes that the mm returns addr. But addr is only a hint without MAP_FIXED, and the mm can return a different range that crosses a boundary. This is not a kernel bug.

Remove the WARN_ON_ONCE() and its -EFAULT. arena_map_mmap() already compares vm_start with user_vm_start under arena->lock. If the rounded result is user_vm_start, mmap() succeeds. If not, it returns -EBUSY.

Fixes 317460317a02 ("bpf: Introduce bpf_arena.")
---
 kernel/bpf/arena.c | 3 ---
 1 file changed, 3 deletions(-)
kernel/bpf/arena.c +0 -3
index b3c70596c576e..3d3bad292bad0 100644
@@ -354,9 +354,6 @@ static unsigned long arena_get_unmapped_area(struct file *filp, unsigned long ad
 		return -EINVAL;
 	if ((ret >> 32) == ((ret + len - 1) >> 32))
 		return ret;
-	if (WARN_ON_ONCE(arena->user_vm_start))
-		/* checks at map creation time should prevent this */
-		return -EFAULT;
 	return round_up(ret, SZ_4G);
 }
 
Signature · 1 line
2.53.0
author maintainer
#117 lore raw

PATCH 116/990 bpf: Require prog fd or capability for cgroup detach

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit 2962329f7c86fc51c177d4049c0f15a95ebd270c ]

Since the commit below a cgroup prog detach does not require CAP_NET_ADMIN. The fd of the attached prog gives the permission instead. But the detach requires this fd only with BPF_F_ALLOW_MULTI. Without this flag a cgroup has only one prog per attach type. Then find_detach_entry() returns this prog and does not compare it with the prog of the caller. Thus the kernel detaches this prog for a caller with neither the fd nor a capability.

Compare the two progs. If they are different, require CAP_NET_ADMIN or CAP_SYS_ADMIN in the initial user namespace. The error is -EPERM. A detach from tcx or netkit without a prog fd already requires these capabilities. With BPF_F_ALLOW_MULTI nothing changes.

Without these capabilities, a caller of bpf_prog_detach() of libbpf must now use bpf_prog_detach2() with the fd of the attached prog.

---
 kernel/bpf/cgroup.c | 9 +++++++--
 1 file changed, 7 insertions(+), 2 deletions(-)
kernel/bpf/cgroup.c +7 -2
index c652ba01bc8bd..9223d76774f21 100644
@@ -1125,9 +1125,14 @@ static struct bpf_prog_list *find_detach_entry(struct hlist_head *progs,
 			return ERR_PTR(-ENOENT);
 
 		/* to maintain backward compatibility NONE and OVERRIDE cgroups
-		 * allow detaching with invalid FD (prog==NULL) in legacy mode
+		 * allow detaching with invalid FD (prog==NULL) in legacy mode.
+		 * Without the FD of the attached program the caller needs
+		 * CAP_NET_ADMIN or CAP_SYS_ADMIN in the initial user namespace.
 		 */
-		return hlist_entry(progs->first, typeof(*pl), node);
+		pl = hlist_entry(progs->first, typeof(*pl), node);
+		if (pl->prog != prog && !bpf_net_capable())
+			return ERR_PTR(-EPERM);
+		return pl;
 	}
 
 	if (!prog && !link)
Signature · 1 line
2.53.0
author maintainer
#118 lore raw

PATCH 117/990 bpf, cgroup: Keep the skb network offset signed

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit 3f9780d62dd1112ca15b5ae73568d29d42ccc950 ]

cgroup_skb progs see a packet from its network header. While they run, __cgroup_bpf_run_filter_skb() moves skb->data there. It assumes that the network header is not after skb->data. It negates skb_network_offset(skb) and pushes skb->data by this offset. The offset is an unsigned int.

But ip6mr_cache_report() and bpf_lwt_xmit_reroute() can pass an skb that has data before the network header. Then the offset wraps. On a 64-bit kernel skb->data is then far below skb->head.

skb->len has 32 bits and wraps to the correct value, thus only skb->data is wrong. A read of packet data faults or gets other memory.

Keep the offset in an int. Pull skb->data when the network header is after it. Otherwise push it, as today.

Fixes 3007098494be ("cgroup: add support for eBPF programs")
---
 kernel/bpf/cgroup.c | 17 ++++++++++++++---
 1 file changed, 14 insertions(+), 3 deletions(-)
kernel/bpf/cgroup.c +14 -3
index 9223d76774f21..14521bd99c7a8 100644
@@ -1630,7 +1630,7 @@ int __cgroup_bpf_run_filter_skb(struct sock *sk,
 				struct sk_buff *skb,
 				enum cgroup_bpf_attach_type atype)
 {
-	unsigned int offset = -skb_network_offset(skb);
+	int offset = skb_network_offset(skb);
 	struct sock *save_sk;
 	void *saved_data_end;
 	struct cgroup *cgrp;
@@ -1642,7 +1642,15 @@ int __cgroup_bpf_run_filter_skb(struct sock *sk,
 	cgrp = sock_cgroup_ptr(&sk->sk_cgrp_data);
 	save_sk = skb->sk;
 	skb->sk = sk;
-	__skb_push(skb, offset);
+
+	/*
+	 * The program sees the packet from its network header on, on
+	 * whichever side of skb->data that header lies.
+	 */
+	if (offset > 0)
+		__skb_pull(skb, offset);
+	else
+		__skb_push(skb, -offset);
 
 	/* compute pointers for the bpf prog */
 	bpf_compute_and_save_data_end(skb, &saved_data_end);
@@ -1684,7 +1692,10 @@ int __cgroup_bpf_run_filter_skb(struct sock *sk,
 			ret = -EFAULT;
 	}
 	bpf_restore_data_end(skb, saved_data_end);
-	__skb_pull(skb, offset);
+	if (offset > 0)
+		__skb_push(skb, offset);
+	else
+		__skb_pull(skb, -offset);
 	skb->sk = save_sk;
 
 	return ret;
Signature · 1 line
2.53.0
author maintainer
#119 lore raw

PATCH 118/990 bpf: Dont let bpf_skb_adjust_room() raise gso_size to GSO_BY_FRAGS

In reply to Greg Kroah-Hartman

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

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

From: Alexei Starovoitov <[email protected]>

[ Upstream commit 6d8118937ba477e03fa2e94e9bd9abac7291a2a2 ]

When bpf_skb_adjust_room() shrinks a TCP GSO skb, it adds the number of removed bytes to gso_size. gso_size has 16 bits, and nothing checks the sum. Thus gso_size can wrap to 0 or to a small size, or it can be GSO_BY_FRAGS. GSO_BY_FRAGS is not a size. It tells skb_segment() to read the length of each segment from the frag_list. If the TCP GSO skb has no frag_list, skb_segment() dereferences a NULL pointer.

Return -ENOTSUPP and do not change the skb if the sum is GSO_BY_FRAGS or larger. With BPF_F_ADJ_ROOM_FIXED_GSO the helper does not change gso_size, so it shrinks the skb as before.

Fixes 2be7e212d541 ("bpf: add bpf_skb_adjust_room helper")
---
 net/core/filter.c | 8 ++++++++
 1 file changed, 8 insertions(+)
net/core/filter.c +8 -0
index 8f92e2bf85517..9463c10d0c907 100644
@@ -3701,6 +3701,14 @@ static int bpf_skb_net_shrink(struct sk_buff *skb, u32 off, u32 len_diff,
 			return -ENOTSUPP;
 	}
 
+	/*
+	 * The MSS is raised by len_diff. It has 16 bits, and GSO_BY_FRAGS is
+	 * not a size.
+	 */
+	if (skb_is_gso(skb) && !(flags & BPF_F_ADJ_ROOM_FIXED_GSO) &&
+	    skb_shinfo(skb)->gso_size + len_diff >= GSO_BY_FRAGS)
+		return -ENOTSUPP;
+
 	ret = skb_unclone(skb, GFP_ATOMIC);
 	if (unlikely(ret < 0))
 		return ret;
Signature · 1 line
2.53.0
author maintainer
#120 lore raw

PATCH 119/990 bpf: Reject non-IPv6 packets in BPF_LWT_ENCAP_SEG6

In reply to Greg Kroah-Hartman

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

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

From: Chris Mason <[email protected]>

[ Upstream commit 58e39f8d58b141b96c030008a20dde9d625ec997 ]

The mode BPF_LWT_ENCAP_SEG6 of bpf_lwt_push_encap() pushes an IPv6 header and an SRH, and it replaces the dst. The SRH says that IPv6 follows, and skb->protocol does not change. Thus the mode assumes an IPv6 packet, but an lwt_in prog also runs for IPv4 packets. After the prog, bpf_input() calls orig_input() of the old dst. This IPv4 handler reads the pushed headers as IPv4. It can write after the packet data, and the kernel crashes.

                 after the push         orig_input() expects
                 ---------------------  --------------------
  skb->protocol  ETH_P_IP               ETH_P_IP
  dst            rt6_info               rtable
  packet         | IPv6 | SRH | IPv4 |  | IPv4 |

The mode BPF_LWT_ENCAP_SEG6_INLINE returns -EBADMSG for non-IPv6 packets. Apply this check to both modes. End.BPF does not change, because seg6_local_input() drops non-IPv6 packets.

Fixes fe94cc290f53 ("bpf: Add IPv6 Segment Routing helpers")
---
 net/core/filter.c | 10 +++++++---
 1 file changed, 7 insertions(+), 3 deletions(-)
net/core/filter.c +7 -3
index 9463c10d0c907..2df3e5cfc3fcd 100644
@@ -6611,11 +6611,15 @@ static int bpf_push_seg6_encap(struct sk_buff *skb, u32 type, void *hdr, u32 len
 	if (!seg6_validate_srh(srh, len, false))
 		return -EINVAL;
 
+	/*
+	 * The encap mode names IPv6 as the inner protocol, and neither mode
+	 * updates skb->protocol.
+	 */
+	if (skb->protocol != htons(ETH_P_IPV6))
+		return -EBADMSG;
+
 	switch (type) {
 	case BPF_LWT_ENCAP_SEG6_INLINE:
-		if (skb->protocol != htons(ETH_P_IPV6))
-			return -EBADMSG;
-
 		err = seg6_do_srh_inline(skb, srh);
 		break;
 	case BPF_LWT_ENCAP_SEG6:
Signature · 1 line
2.53.0
author maintainer
#111 lore raw

PATCH 110/990 bpf: Clamp the trace length in __bpf_get_stack() again

In reply to Greg Kroah-Hartman

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

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

From: Josef Bacik <[email protected]>

[ Upstream commit 007fd460798be9af7d4874734f934afa47742f29 ]

get_perf_callchain() and get_callchain_entry_for_task() store a trace in a per-CPU entry, one per context. They release the entry before they return it. Thus a second user in the same context can write to the entry while the first user reads it. preempt_disable() stops only other tasks.

__bpf_get_stack() requests at most max_depth frames. This is skip plus the frames that fit in the buffer, but not more than perf_event_max_stack. Since the commit below, it copies 'trace->nr - skip' frames with no limit. But a second user can store a longer trace. The unwinders of PowerPC add context markers that max_depth does not limit. In both cases the copy writes after the end of the buffer.

Read trace->nr one time. Clamp the value to max_depth before the skip test, as __bpf_get_stack_pe() does. Thus when max_depth is less than skip, the helper returns -EFAULT, and 'trace_nr - skip' does not underflow. The copied frames can still be those of the second user.

Fixes e17d62fedd10 ("bpf: Refactor stack map trace depth calculation into helper function")
---
 kernel/bpf/stackmap.c | 24 +++++++++++++++++-------
 1 file changed, 17 insertions(+), 7 deletions(-)
kernel/bpf/stackmap.c +17 -7
index 2749985910855..f56333c9a8053 100644
@@ -706,14 +706,20 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
 					   crosstask, false);
 	}
 
-	if (unlikely(!trace) || trace->nr < skip) {
-		if (may_fault)
-			rcu_read_unlock();
-		preempt_enable();
-		goto err_fault;
-	}
+	if (unlikely(!trace))
+		goto err_unlock;
+
+	/*
+	 * trace->nr can be above max_depth. The per-CPU entry is released
+	 * already: a tracing program or an NMI which takes a callchain in the
+	 * same context before the copy below reuses it. And the unwinders of
+	 * PowerPC store context markers on top of max_depth.
+	 */
+	trace_nr = min_t(u32, READ_ONCE(trace->nr), max_depth);
+	if (trace_nr < skip)
+		goto err_unlock;
 
-	trace_nr = callchain_store(trace, trace->nr, buf, elem_size, flags);
+	trace_nr = callchain_store(trace, trace_nr, buf, elem_size, flags);
 
 	/* trace should not be dereferenced after this point */
 	if (may_fault)
@@ -722,6 +728,10 @@ static long __bpf_get_stack(struct pt_regs *regs, struct task_struct *task,
 
 	return callchain_finalize(buf, size, trace_nr, elem_size, flags, may_fault);
 
+err_unlock:
+	if (may_fault)
+		rcu_read_unlock();
+	preempt_enable();
 err_fault:
 	err = -EFAULT;
 clear:
Signature · 1 line
2.53.0
author maintainer
#160 lore raw

PATCH 159/990 vhost-vdpa: drop the parents vq callback before the call fd is released

In reply to Greg Kroah-Hartman

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

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

From: Yu Zhang <[email protected]>

[ Upstream commit c9c1c1b7b31fc8b9a5d6c04f5f0ae647d081a39d ]

VHOST_SET_VRING_CALL releases the previous call eventfd inside vhost_vring_ioctl() -- it swaps the new context into vq->call_ctx.ctx and then eventfd_ctx_put()s the old one, which is a synchronous kfree(). The parent vdpa device is only told about the change afterwards, when vhost_vdpa_vring_ioctl() reaches ops->set_vq_cb().

Parent drivers cache the pointer handed to them in vdpa_callback::trigger and do not take a reference on it, so throughout that window the parent holds a dangling eventfd_ctx and may signal it. The documentation added with the field describes what signalling it means but says nothing about how long it stays valid.

This is the same hazard that "vhost_vdpa: assign irq bypass producer token correctly" addressed for the irq bypass producer token, by moving vhost_vdpa_unsetup_vq_irq() ahead of the vhost_vring_ioctl() call. The producer token was only one of the two consumers of that pointer; the one the parent keeps via ->set_vq_cb() was left behind the free.

With VDUSE the window is directly reachable from userspace, because the device emulation daemon can inject an interrupt at any time from a different fd, and neither side shares a lock with the other: VDUSE takes vq->irq_lock, vhost takes vhost_dev.mutex + vq->mutex.

  BUG: KASAN: slab-use-after-free in _raw_spin_lock_irqsave+0x76/0xe0
  Write of size 4 at addr ffff8881084e8788 by task vduse_uaf/2987

  _raw_spin_lock_irqsave+0x76/0xe0
  eventfd_signal_mask+0x69/0x120
  vduse_dev_ioctl+0x337/0x1a60     <- vduse_vq_signal_irqfd(), inlined
  __x64_sys_ioctl+0x120/0x170      <- VDUSE_VQ_INJECT_IRQ

  Allocated by task 2986:
   do_eventfd+0x50/0x200
   __x64_sys_eventfd2+0x2e/0x40

kmalloc-64, freed 64-byte region [ffff8881084e8780, ffff8881084e87c0)

One thread loops VHOST_SET_VRING_CALL on /dev/vhost-vdpa-N with a fresh eventfd and then unbinds it, while another loops VDUSE_VQ_INJECT_IRQ on /dev/vduse/<name>. This reproduces in 5 out of 5 ten-second runs on v7.1.6 and 3 out of 3 on v7.2-rc6. With the patch there are no reports in 3 out of 3 runs on either, while the same workload still gets ~30000 interrupts per run delivered into live eventfds, so the path is still being exercised.

Tell the parent to drop the callback before vhost_vring_ioctl() can free the eventfd, mirroring what is already done for the bypass producer, and restore it if the ioctl fails -- on failure the swap never happened, the old context is still installed, and leaving the parent without a callback would silently drop that vq's interrupts.

Clearing the callback only stops a parent from starting to use the context; a handler that already loaded it can still be running. For parents with a real interrupt, wait for it with synchronize_irq() on the vq's irq. VDUSE does not implement get_vq_irq, so that case stays covered by the teardown above.

Fixes 5e68470f4e80 ("vdpa: Add eventfd for the vdpa callback")

Message-ID: <[email protected]>

---
 drivers/vhost/vdpa.c | 35 ++++++++++++++++++++++++++++++++++-
 1 file changed, 34 insertions(+), 1 deletion(-)
drivers/vhost/vdpa.c +34 -1
index eeb57c832d740..665739ba03f8e 100644
@@ -765,13 +765,46 @@ static long vhost_vdpa_vring_ioctl(struct vhost_vdpa *v, unsigned int cmd,
 			if (ops->get_status(vdpa) &
 			    VIRTIO_CONFIG_S_DRIVER_OK)
 				vhost_vdpa_unsetup_vq_irq(v, idx);
+			/*
+			 * The parent caches call_ctx.ctx in cb.trigger without
+			 * holding a reference, so it has to stop using it
+			 * before vhost_vring_ioctl() drops the last one.
+			 */
+			cb.callback = NULL;
+			cb.private = NULL;
+			cb.trigger = NULL;
+			ops->set_vq_cb(vdpa, idx, &cb);
+
+			/*
+			 * A parent interrupt handler that loaded the callback
+			 * before that store can still be running, so wait for
+			 * it to finish with the context too.
+			 */
+			if (ops->get_vq_irq) {
+				int irq = ops->get_vq_irq(vdpa, idx);
+
+				if (irq >= 0)
+					synchronize_irq(irq);
+			}
 		}
 		break;
 	}
 
 	r = vhost_vring_ioctl(&v->vdev, cmd, argp);
-	if (r)
+	if (r) {
+		/*
+		 * A failure here means the swap never happened and the old
+		 * context is still installed, so give the parent back the
+		 * callback that was torn down above.
+		 */
+		if (cmd == VHOST_SET_VRING_CALL && vq->call_ctx.ctx) {
+			cb.callback = vhost_vdpa_virtqueue_cb;
+			cb.private = vq;
+			cb.trigger = vq->call_ctx.ctx;
+			ops->set_vq_cb(vdpa, idx, &cb);
+		}
 		return r;
+	}
 
 	switch (cmd) {
 	case VHOST_SET_VRING_ADDR:
Signature · 1 line
2.53.0
author maintainer
#169 lore raw

PATCH 168/990 wifi: ath12k: add EHT rate handling to existing set rate functions

In reply to Greg Kroah-Hartman

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

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

From: Muna Sinada <[email protected]>

[ Upstream commit ec1d9b79be5df30f1998f37a49bf14d34ecd6c50 ]

Add EHT rate handling to the existing rate functions that validate, prepare and set rates.

Tested-on: QCN9274 hw2.0 PCI WLAN.WBE.1.0.1-00029-QCAHKSWPL_SILICONZ-1

Stable-dep-of: 83d689bbe8f9 ("wifi: ath12k: don't advertise EHT-MCS15 to firmware unless we support it")

---
 drivers/net/wireless/ath/ath12k/mac.c | 215 +++++++++++++++++++++-----
 1 file changed, 173 insertions(+), 42 deletions(-)
drivers/net/wireless/ath/ath12k/mac.c +173 -42
index af6163169364f..99d80a0aafe4a 100644
@@ -533,6 +533,18 @@ ath12k_mac_max_he_nss(const u16 he_mcs_mask[NL80211_HE_NSS_MAX])
 	return 1;
 }
 
+static u32
+ath12k_mac_max_eht_nss(const u16 eht_mcs_mask[NL80211_EHT_NSS_MAX])
+{
+	int nss;
+
+	for (nss = NL80211_EHT_NSS_MAX - 1; nss >= 0; nss--)
+		if (eht_mcs_mask[nss])
+			return nss + 1;
+
+	return 1;
+}
+
 static u8 ath12k_parse_mpdudensity(u8 mpdudensity)
 {
 /*  From IEEE Std 802.11-2020 defined values for "Minimum MPDU Start Spacing":
@@ -3102,37 +3114,50 @@ static void ath12k_peer_assoc_h_phymode(struct ath12k *ar,
 	WARN_ON(phymode == MODE_UNKNOWN);
 }
 
+#define ATH12K_EHT_MCS_7_ENABLED	0x00FF
+#define ATH12K_EHT_MCS_9_ENABLED	0x0300
+#define ATH12K_EHT_MCS_11_ENABLED	0x0C00
+#define ATH12K_EHT_MCS_13_ENABLED	0x3000
+
 static void ath12k_mac_set_eht_mcs(u8 rx_tx_mcs7, u8 rx_tx_mcs9,
 				   u8 rx_tx_mcs11, u8 rx_tx_mcs13,
-				   u32 *rx_mcs, u32 *tx_mcs)
-{
-	*rx_mcs = 0;
-	u32p_replace_bits(rx_mcs,
-			  u8_get_bits(rx_tx_mcs7, IEEE80211_EHT_MCS_NSS_RX),
-			  WMI_EHT_MCS_NSS_0_7);
-	u32p_replace_bits(rx_mcs,
-			  u8_get_bits(rx_tx_mcs9, IEEE80211_EHT_MCS_NSS_RX),
-			  WMI_EHT_MCS_NSS_8_9);
-	u32p_replace_bits(rx_mcs,
-			  u8_get_bits(rx_tx_mcs11, IEEE80211_EHT_MCS_NSS_RX),
-			  WMI_EHT_MCS_NSS_10_11);
-	u32p_replace_bits(rx_mcs,
-			  u8_get_bits(rx_tx_mcs13, IEEE80211_EHT_MCS_NSS_RX),
-			  WMI_EHT_MCS_NSS_12_13);
-
-	*tx_mcs = 0;
-	u32p_replace_bits(tx_mcs,
-			  u8_get_bits(rx_tx_mcs7, IEEE80211_EHT_MCS_NSS_TX),
-			  WMI_EHT_MCS_NSS_0_7);
-	u32p_replace_bits(tx_mcs,
-			  u8_get_bits(rx_tx_mcs9, IEEE80211_EHT_MCS_NSS_TX),
-			  WMI_EHT_MCS_NSS_8_9);
-	u32p_replace_bits(tx_mcs,
-			  u8_get_bits(rx_tx_mcs11, IEEE80211_EHT_MCS_NSS_TX),
-			  WMI_EHT_MCS_NSS_10_11);
-	u32p_replace_bits(tx_mcs,
-			  u8_get_bits(rx_tx_mcs13, IEEE80211_EHT_MCS_NSS_TX),
-			  WMI_EHT_MCS_NSS_12_13);
+				   u32 *rx_mcs, u32 *tx_mcs,
+				   const u16 eht_mcs_limit[NL80211_EHT_NSS_MAX])
+{
+	int nss;
+	u8 mcs_7 = 0, mcs_9 = 0, mcs_11 = 0, mcs_13 = 0;
+	u8 peer_mcs_7, peer_mcs_9, peer_mcs_11, peer_mcs_13;
+
+	for (nss = 0; nss < NL80211_EHT_NSS_MAX; nss++) {
+		if (eht_mcs_limit[nss] & ATH12K_EHT_MCS_7_ENABLED)
+			mcs_7++;
+		if (eht_mcs_limit[nss] & ATH12K_EHT_MCS_9_ENABLED)
+			mcs_9++;
+		if (eht_mcs_limit[nss] & ATH12K_EHT_MCS_11_ENABLED)
+			mcs_11++;
+		if (eht_mcs_limit[nss] & ATH12K_EHT_MCS_13_ENABLED)
+			mcs_13++;
+	}
+
+	peer_mcs_7 = u8_get_bits(rx_tx_mcs7, IEEE80211_EHT_MCS_NSS_RX);
+	peer_mcs_9 = u8_get_bits(rx_tx_mcs9, IEEE80211_EHT_MCS_NSS_RX);
+	peer_mcs_11 = u8_get_bits(rx_tx_mcs11, IEEE80211_EHT_MCS_NSS_RX);
+	peer_mcs_13 = u8_get_bits(rx_tx_mcs13, IEEE80211_EHT_MCS_NSS_RX);
+
+	*rx_mcs = u32_encode_bits(min(peer_mcs_7, mcs_7), WMI_EHT_MCS_NSS_0_7) |
+		  u32_encode_bits(min(peer_mcs_9, mcs_9), WMI_EHT_MCS_NSS_8_9) |
+		  u32_encode_bits(min(peer_mcs_11, mcs_11), WMI_EHT_MCS_NSS_10_11) |
+		  u32_encode_bits(min(peer_mcs_13, mcs_13), WMI_EHT_MCS_NSS_12_13);
+
+	peer_mcs_7 = u8_get_bits(rx_tx_mcs7, IEEE80211_EHT_MCS_NSS_TX);
+	peer_mcs_9 = u8_get_bits(rx_tx_mcs9, IEEE80211_EHT_MCS_NSS_TX);
+	peer_mcs_11 = u8_get_bits(rx_tx_mcs11, IEEE80211_EHT_MCS_NSS_TX);
+	peer_mcs_13 = u8_get_bits(rx_tx_mcs13, IEEE80211_EHT_MCS_NSS_TX);
+
+	*tx_mcs = u32_encode_bits(min(peer_mcs_7, mcs_7), WMI_EHT_MCS_NSS_0_7) |
+		  u32_encode_bits(min(peer_mcs_9, mcs_9), WMI_EHT_MCS_NSS_8_9) |
+		  u32_encode_bits(min(peer_mcs_11, mcs_11), WMI_EHT_MCS_NSS_10_11) |
+		  u32_encode_bits(min(peer_mcs_13, mcs_13), WMI_EHT_MCS_NSS_12_13);
 }
 
 static void ath12k_mac_set_eht_ppe_threshold(const u8 *ppe_thres,
@@ -3171,13 +3196,17 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar,
 				    struct ath12k_wmi_peer_assoc_arg *arg)
 {
 	struct ieee80211_sta *sta = ath12k_ahsta_to_sta(arsta->ahsta);
+	struct ieee80211_vif *vif = ath12k_ahvif_to_vif(arvif->ahvif);
 	const struct ieee80211_eht_mcs_nss_supp_20mhz_only *bw_20;
 	const struct ieee80211_eht_mcs_nss_supp_bw *bw;
 	const struct ieee80211_sta_eht_cap *eht_cap;
 	const struct ieee80211_sta_he_cap *he_cap;
 	struct ieee80211_link_sta *link_sta;
 	struct ieee80211_bss_conf *link_conf;
+	struct cfg80211_chan_def def;
+	enum nl80211_band band;
 	u32 *rx_mcs, *tx_mcs;
+	u16 *eht_mcs_mask;
 
 	lockdep_assert_wiphy(ath12k_ar_to_hw(ar)->wiphy);
 
@@ -3199,6 +3228,12 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar,
 	if (!he_cap->has_he || !eht_cap->has_eht)
 		return;
 
+	if (WARN_ON(ath12k_mac_vif_link_chan(vif, arvif->link_id, &def)))
+		return;
+
+	band = def.chan->band;
+	eht_mcs_mask = arvif->bitrate_mask.control[band].eht_mcs;
+
 	arg->eht_flag = true;
 
 	if ((eht_cap->eht_cap_elem.phy_cap_info[5] &
@@ -3223,7 +3258,8 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar,
 				       bw->rx_tx_mcs11_max_nss,
 				       bw->rx_tx_mcs13_max_nss,
 				       &rx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_320],
-				       &tx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_320]);
+				       &tx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_320],
+				       eht_mcs_mask);
 		arg->peer_eht_mcs_count++;
 		fallthrough;
 	case IEEE80211_STA_RX_BW_160:
@@ -3233,7 +3269,8 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar,
 				       bw->rx_tx_mcs11_max_nss,
 				       bw->rx_tx_mcs13_max_nss,
 				       &rx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_160],
-				       &tx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_160]);
+				       &tx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_160],
+				       eht_mcs_mask);
 		arg->peer_eht_mcs_count++;
 		fallthrough;
 	default:
@@ -3249,7 +3286,8 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar,
 					       bw_20->rx_tx_mcs11_max_nss,
 					       bw_20->rx_tx_mcs13_max_nss,
 					       &rx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_80],
-					       &tx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_80]);
+					       &tx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_80],
+					       eht_mcs_mask);
 		} else {
 			bw = &eht_cap->eht_mcs_nss_supp.bw._80;
 			ath12k_mac_set_eht_mcs(bw->rx_tx_mcs9_max_nss,
@@ -3257,7 +3295,8 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar,
 					       bw->rx_tx_mcs11_max_nss,
 					       bw->rx_tx_mcs13_max_nss,
 					       &rx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_80],
-					       &tx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_80]);
+					       &tx_mcs[WMI_EHTCAP_TXRX_MCS_NSS_IDX_80],
+					       eht_mcs_mask);
 		}
 
 		arg->peer_eht_mcs_count++;
@@ -3875,6 +3914,8 @@ static void ath12k_mac_init_arvif(struct ath12k_vif *ahvif,
 		       sizeof(arvif->bitrate_mask.control[i].vht_mcs));
 		memset(arvif->bitrate_mask.control[i].he_mcs, 0xff,
 		       sizeof(arvif->bitrate_mask.control[i].he_mcs));
+		memset(arvif->bitrate_mask.control[i].eht_mcs, 0xff,
+		       sizeof(arvif->bitrate_mask.control[i].eht_mcs));
 	}
 
 	/* Handle MLO related assignments */
@@ -5722,6 +5763,20 @@ ath12k_mac_bitrate_mask_num_he_rates(struct ath12k *ar,
 	return num_rates;
 }
 
+static int
+ath12k_mac_bitrate_mask_num_eht_rates(struct ath12k *ar,
+				      enum nl80211_band band,
+				      const struct cfg80211_bitrate_mask *mask)
+{
+	int num_rates = 0;
+	int i;
+
+	for (i = 0; i < ARRAY_SIZE(mask->control[band].eht_mcs); i++)
+		num_rates += hweight16(mask->control[band].eht_mcs[i]);
+
+	return num_rates;
+}
+
 static int
 ath12k_mac_set_peer_vht_fixed_rate(struct ath12k_link_vif *arvif,
 				   struct ath12k_link_sta *arsta,
@@ -11925,6 +11980,9 @@ ath12k_mac_has_single_legacy_rate(struct ath12k *ar,
 	if (ath12k_mac_bitrate_mask_num_he_rates(ar, band, mask))
 		return false;
 
+	if (ath12k_mac_bitrate_mask_num_eht_rates(ar, band, mask))
+		return false;
+
 	return num_rates == 1;
 }
 
@@ -11947,11 +12005,15 @@ ath12k_mac_bitrate_mask_get_single_nss(struct ath12k *ar,
 {
 	struct ieee80211_supported_band *sband = &ar->mac.sbands[band];
 	u16 vht_mcs_map = le16_to_cpu(sband->vht_cap.vht_mcs.tx_mcs_map);
+	const struct ieee80211_sband_iftype_data *data;
 	const struct ieee80211_sta_he_cap *he_cap;
 	u16 he_mcs_map = 0;
+	u16 eht_mcs_map = 0;
 	u8 ht_nss_mask = 0;
 	u8 vht_nss_mask = 0;
 	u8 he_nss_mask = 0;
+	u8 eht_nss_mask = 0;
+	u8 mcs_nss_len;
 	int i;
 
 	/* No need to consider legacy here. Basic rates are always present
@@ -11995,7 +12057,60 @@ ath12k_mac_bitrate_mask_get_single_nss(struct ath12k *ar,
 			return false;
 	}
 
-	if (ht_nss_mask != vht_nss_mask || ht_nss_mask != he_nss_mask)
+	data = ieee80211_get_sband_iftype_data(sband, vif->type);
+
+	mcs_nss_len = ieee80211_eht_mcs_nss_size(&data->he_cap.he_cap_elem,
+						 &data->eht_cap.eht_cap_elem,
+						 false);
+	if (mcs_nss_len == 4) {
+		/* 20 MHz only STA case */
+		const struct ieee80211_eht_mcs_nss_supp_20mhz_only *eht_mcs_nss =
+			&data->eht_cap.eht_mcs_nss_supp.only_20mhz;
+		if (eht_mcs_nss->rx_tx_mcs13_max_nss)
+			eht_mcs_map = 0x1fff;
+		else if (eht_mcs_nss->rx_tx_mcs11_max_nss)
+			eht_mcs_map = 0x07ff;
+		else if (eht_mcs_nss->rx_tx_mcs9_max_nss)
+			eht_mcs_map = 0x01ff;
+		else
+			eht_mcs_map = 0x007f;
+	} else {
+		const struct ieee80211_eht_mcs_nss_supp_bw *eht_mcs_nss;
+
+		switch (mcs_nss_len) {
+		case 9:
+			eht_mcs_nss = &data->eht_cap.eht_mcs_nss_supp.bw._320;
+			break;
+		case 6:
+			eht_mcs_nss = &data->eht_cap.eht_mcs_nss_supp.bw._160;
+			break;
+		case 3:
+			eht_mcs_nss = &data->eht_cap.eht_mcs_nss_supp.bw._80;
+			break;
+		default:
+			return false;
+		}
+
+		if (eht_mcs_nss->rx_tx_mcs13_max_nss)
+			eht_mcs_map = 0x1fff;
+		else if (eht_mcs_nss->rx_tx_mcs11_max_nss)
+			eht_mcs_map = 0x7ff;
+		else
+			eht_mcs_map = 0x1ff;
+	}
+
+	for (i = 0; i < ARRAY_SIZE(mask->control[band].eht_mcs); i++) {
+		if (mask->control[band].eht_mcs[i] == 0)
+			continue;
+
+		if (mask->control[band].eht_mcs[i] < eht_mcs_map)
+			eht_nss_mask |= BIT(i);
+		else
+			return false;
+	}
+
+	if (ht_nss_mask != vht_nss_mask || ht_nss_mask != he_nss_mask ||
+	    ht_nss_mask != eht_nss_mask)
 		return false;
 
 	if (ht_nss_mask == 0)
@@ -12147,11 +12262,12 @@ static u32 ath12k_mac_nlgi_to_wmigi(enum nl80211_txrate_gi gi)
 
 static int ath12k_mac_set_rate_params(struct ath12k_link_vif *arvif,
 				      u32 rate, u8 nss, u8 sgi, u8 ldpc,
-				      u8 he_gi, u8 he_ltf, bool he_fixed_rate)
+				      u8 he_gi, u8 he_ltf, bool he_fixed_rate,
+				      bool eht_fixed_rate)
 {
 	struct ieee80211_bss_conf *link_conf;
 	struct ath12k *ar = arvif->ar;
-	bool he_support, gi_ltf_set = false;
+	bool he_support, eht_support, gi_ltf_set = false;
 	u32 vdev_param;
 	u32 param_value;
 	int ret;
@@ -12163,6 +12279,7 @@ static int ath12k_mac_set_rate_params(struct ath12k_link_vif *arvif,
 		return -EINVAL;
 
 	he_support = link_conf->he_support;
+	eht_support = link_conf->eht_support;
 
 	ath12k_dbg(ar->ab, ATH12K_DBG_MAC,
 		   "mac set rate params vdev %i rate 0x%02x nss 0x%02x sgi 0x%02x ldpc 0x%02x\n",
@@ -12172,7 +12289,10 @@ static int ath12k_mac_set_rate_params(struct ath12k_link_vif *arvif,
 		   "he_gi 0x%02x he_ltf 0x%02x he_fixed_rate %d\n", he_gi,
 		   he_ltf, he_fixed_rate);
 
-	if (!he_support) {
+	ath12k_dbg(ar->ab, ATH12K_DBG_MAC, "eht_fixed_rate %d\n",
+		   eht_fixed_rate);
+
+	if (!he_support && !eht_support) {
 		vdev_param = WMI_VDEV_PARAM_FIXED_RATE;
 		ret = ath12k_wmi_vdev_set_param_cmd(ar, arvif->vdev_id,
 						    vdev_param, rate);
@@ -12330,15 +12450,16 @@ ath12k_mac_validate_fixed_rate_settings(struct ath12k *ar, enum nl80211_band ban
 					const struct cfg80211_bitrate_mask *mask,
 					unsigned int link_id)
 {
-	bool he_fixed_rate = false, vht_fixed_rate = false;
-	const u16 *vht_mcs_mask, *he_mcs_mask;
+	bool eht_fixed_rate = false, he_fixed_rate = false, vht_fixed_rate = false;
+	const u16 *vht_mcs_mask, *he_mcs_mask, *eht_mcs_mask;
 	struct ieee80211_link_sta *link_sta;
 	struct ath12k_peer *peer, *tmp;
-	u8 vht_nss, he_nss;
+	u8 vht_nss, he_nss, eht_nss;
 	int ret = true;
 
 	vht_mcs_mask = mask->control[band].vht_mcs;
 	he_mcs_mask = mask->control[band].he_mcs;
+	eht_mcs_mask = mask->control[band].eht_mcs;
 
 	if (ath12k_mac_bitrate_mask_num_vht_rates(ar, band, mask) == 1)
 		vht_fixed_rate = true;
@@ -12346,11 +12467,15 @@ ath12k_mac_validate_fixed_rate_settings(struct ath12k *ar, enum nl80211_band ban
 	if (ath12k_mac_bitrate_mask_num_he_rates(ar, band, mask) == 1)
 		he_fixed_rate = true;
 
-	if (!vht_fixed_rate && !he_fixed_rate)
+	if (ath12k_mac_bitrate_mask_num_eht_rates(ar, band, mask) == 1)
+		eht_fixed_rate = true;
+
+	if (!vht_fixed_rate && !he_fixed_rate && !eht_fixed_rate)
 		return true;
 
 	vht_nss = ath12k_mac_max_vht_nss(vht_mcs_mask);
 	he_nss =  ath12k_mac_max_he_nss(he_mcs_mask);
+	eht_nss = ath12k_mac_max_eht_nss(eht_mcs_mask);
 
 	rcu_read_lock();
 	spin_lock_bh(&ar->ab->base_lock);
@@ -12372,6 +12497,11 @@ ath12k_mac_validate_fixed_rate_settings(struct ath12k *ar, enum nl80211_band ban
 				ret = false;
 				goto exit;
 			}
+			if (eht_fixed_rate && (!link_sta->eht_cap.has_eht ||
+					       link_sta->rx_nss < eht_nss)) {
+				ret = false;
+				goto exit;
+			}
 		}
 	}
 exit:
@@ -12403,6 +12533,7 @@ ath12k_mac_op_set_bitrate_mask(struct ieee80211_hw *hw,
 	int ret;
 	int num_rates;
 	bool he_fixed_rate = false;
+	bool eht_fixed_rate = false;
 
 	lockdep_assert_wiphy(hw->wiphy);
 
@@ -12527,7 +12658,7 @@ ath12k_mac_op_set_bitrate_mask(struct ieee80211_hw *hw,
 	}
 
 	ret = ath12k_mac_set_rate_params(arvif, rate, nss, sgi, ldpc, he_gi,
-					 he_ltf, he_fixed_rate);
+					 he_ltf, he_fixed_rate, eht_fixed_rate);
 	if (ret) {
 		ath12k_warn(ar->ab, "failed to set rate params on vdev %i: %d\n",
 			    arvif->vdev_id, ret);
Signature · 1 line
2.53.0
author maintainer
#170 lore raw

PATCH 169/990 wifi: ath12k: Add EHT MCS/NSS rates to Peer Assoc

In reply to Greg Kroah-Hartman

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

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

From: Muna Sinada <[email protected]>

[ Upstream commit 6c95151e2e776462de6b6fd9e577865e8b32203e ]

Add EHT MCS/NSS rate functionality to peer association. As part of ath12k_peer_assoc_h_eht() add the calculation of EHT MCS/NSS using intersection of link_sta and phy capability.

ath12k_mac_max_eht_mcs_nss() function is utilized when comparing the max NSS of link STA and phy capability since in split phy case, phy supports max NSS of 2 for 5G band.

Tested-on: QCN9274 hw2.0 PCI WLAN.WBE.1.0.1-00029-QCAHKSWPL_SILICONZ-1

Stable-dep-of: 83d689bbe8f9 ("wifi: ath12k: don't advertise EHT-MCS15 to firmware unless we support it")

---
 drivers/net/wireless/ath/ath12k/mac.c | 110 ++++++++++++++++++++++++--
 1 file changed, 103 insertions(+), 7 deletions(-)
drivers/net/wireless/ath/ath12k/mac.c +103 -7
index 99d80a0aafe4a..94e5af15cd618 100644
@@ -545,6 +545,18 @@ ath12k_mac_max_eht_nss(const u16 eht_mcs_mask[NL80211_EHT_NSS_MAX])
 	return 1;
 }
 
+static u32
+ath12k_mac_max_eht_mcs_nss(const u8 *eht_mcs, int eht_mcs_set_size)
+{
+	int i;
+	u8 nss = 0;
+
+	for (i = 0; i < eht_mcs_set_size; i++)
+		nss = max(nss, u8_get_bits(eht_mcs[i], IEEE80211_EHT_MCS_NSS_RX));
+
+	return nss;
+}
+
 static u8 ath12k_parse_mpdudensity(u8 mpdudensity)
 {
 /*  From IEEE Std 802.11-2020 defined values for "Minimum MPDU Start Spacing":
@@ -3016,6 +3028,18 @@ static enum wmi_phy_mode ath12k_mac_get_phymode_eht(struct ath12k *ar,
 	return MODE_UNKNOWN;
 }
 
+static bool
+ath12k_peer_assoc_h_eht_masked(const u16 eht_mcs_mask[NL80211_EHT_NSS_MAX])
+{
+	int nss;
+
+	for (nss = 0; nss < NL80211_EHT_NSS_MAX; nss++)
+		if (eht_mcs_mask[nss])
+			return false;
+
+	return true;
+}
+
 static void ath12k_peer_assoc_h_phymode(struct ath12k *ar,
 					struct ath12k_link_vif *arvif,
 					struct ath12k_link_sta *arsta,
@@ -3027,6 +3051,7 @@ static void ath12k_peer_assoc_h_phymode(struct ath12k *ar,
 	const u8 *ht_mcs_mask;
 	const u16 *vht_mcs_mask;
 	const u16 *he_mcs_mask;
+	const u16 *eht_mcs_mask;
 	enum wmi_phy_mode phymode = MODE_UNKNOWN;
 
 	lockdep_assert_wiphy(ath12k_ar_to_hw(ar)->wiphy);
@@ -3041,6 +3066,7 @@ static void ath12k_peer_assoc_h_phymode(struct ath12k *ar,
 	ht_mcs_mask = arvif->bitrate_mask.control[band].ht_mcs;
 	vht_mcs_mask = arvif->bitrate_mask.control[band].vht_mcs;
 	he_mcs_mask = arvif->bitrate_mask.control[band].he_mcs;
+	eht_mcs_mask = arvif->bitrate_mask.control[band].eht_mcs;
 
 	link_sta = ath12k_mac_get_link_sta(arsta);
 	if (!link_sta) {
@@ -3051,7 +3077,8 @@ static void ath12k_peer_assoc_h_phymode(struct ath12k *ar,
 
 	switch (band) {
 	case NL80211_BAND_2GHZ:
-		if (link_sta->eht_cap.has_eht) {
+		if (link_sta->eht_cap.has_eht &&
+		    !ath12k_peer_assoc_h_eht_masked(eht_mcs_mask)) {
 			if (link_sta->bandwidth == IEEE80211_STA_RX_BW_40)
 				phymode = MODE_11BE_EHT40_2G;
 			else
@@ -3197,16 +3224,21 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar,
 {
 	struct ieee80211_sta *sta = ath12k_ahsta_to_sta(arsta->ahsta);
 	struct ieee80211_vif *vif = ath12k_ahvif_to_vif(arvif->ahvif);
+	const struct ieee80211_eht_mcs_nss_supp *own_eht_mcs_nss_supp;
 	const struct ieee80211_eht_mcs_nss_supp_20mhz_only *bw_20;
+	const struct ieee80211_sta_eht_cap *eht_cap, *own_eht_cap;
+	const struct ieee80211_sband_iftype_data *iftd;
 	const struct ieee80211_eht_mcs_nss_supp_bw *bw;
-	const struct ieee80211_sta_eht_cap *eht_cap;
 	const struct ieee80211_sta_he_cap *he_cap;
 	struct ieee80211_link_sta *link_sta;
 	struct ieee80211_bss_conf *link_conf;
 	struct cfg80211_chan_def def;
+	bool user_rate_valid = true;
 	enum nl80211_band band;
+	int eht_nss, nss_idx;
 	u32 *rx_mcs, *tx_mcs;
 	u16 *eht_mcs_mask;
+	u8 max_nss = 0;
 
 	lockdep_assert_wiphy(ath12k_ar_to_hw(ar)->wiphy);
 
@@ -3234,6 +3266,16 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar,
 	band = def.chan->band;
 	eht_mcs_mask = arvif->bitrate_mask.control[band].eht_mcs;
 
+	iftd = ieee80211_get_sband_iftype_data(&ar->mac.sbands[band], vif->type);
+	if (!iftd) {
+		ath12k_warn(ar->ab,
+			    "unable to access iftype_data in struct ieee80211_supported_band\n");
+		return;
+	}
+
+	own_eht_cap = &iftd->eht_cap;
+	own_eht_mcs_nss_supp = &own_eht_cap->eht_mcs_nss_supp;
+
 	arg->eht_flag = true;
 
 	if ((eht_cap->eht_cap_elem.phy_cap_info[5] &
@@ -3250,6 +3292,28 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar,
 	rx_mcs = arg->peer_eht_rx_mcs_set;
 	tx_mcs = arg->peer_eht_tx_mcs_set;
 
+	eht_nss = ath12k_mac_max_eht_mcs_nss((void *)own_eht_mcs_nss_supp,
+					     sizeof(*own_eht_mcs_nss_supp));
+	if (eht_nss > link_sta->rx_nss) {
+		user_rate_valid = false;
+		for (nss_idx = (link_sta->rx_nss - 1); nss_idx >= 0; nss_idx--) {
+			if (eht_mcs_mask[nss_idx]) {
+				user_rate_valid = true;
+				break;
+			}
+		}
+	}
+
+	if (!user_rate_valid) {
+		ath12k_dbg(ar->ab, ATH12K_DBG_MAC,
+			   "Setting eht range MCS value to peer supported nss %d for peer %pM\n",
+			   link_sta->rx_nss, arsta->addr);
+		eht_mcs_mask[link_sta->rx_nss - 1] = eht_mcs_mask[eht_nss - 1];
+	}
+
+	bw_20 = &eht_cap->eht_mcs_nss_supp.only_20mhz;
+	bw = &eht_cap->eht_mcs_nss_supp.bw._80;
+
 	switch (link_sta->bandwidth) {
 	case IEEE80211_STA_RX_BW_320:
 		bw = &eht_cap->eht_mcs_nss_supp.bw._320;
@@ -3274,11 +3338,8 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar,
 		arg->peer_eht_mcs_count++;
 		fallthrough;
 	default:
-		if ((he_cap->he_cap_elem.phy_cap_info[0] &
-		     (IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_40MHZ_IN_2G |
-		      IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_40MHZ_80MHZ_IN_5G |
-		      IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_160MHZ_IN_5G |
-		      IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_80PLUS80_MHZ_IN_5G)) == 0) {
+		if (!(link_sta->he_cap.he_cap_elem.phy_cap_info[0] &
+		      IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_MASK_ALL)) {
 			bw_20 = &eht_cap->eht_mcs_nss_supp.only_20mhz;
 
 			ath12k_mac_set_eht_mcs(bw_20->rx_tx_mcs7_max_nss,
@@ -3305,6 +3366,41 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar,
 
 	arg->punct_bitmap = ~arvif->punct_bitmap;
 	arg->eht_disable_mcs15 = link_conf->eht_disable_mcs15;
+
+	if (!(link_sta->he_cap.he_cap_elem.phy_cap_info[0] &
+	      IEEE80211_HE_PHY_CAP0_CHANNEL_WIDTH_SET_MASK_ALL)) {
+		if (bw_20->rx_tx_mcs13_max_nss)
+			max_nss = max(max_nss, u8_get_bits(bw_20->rx_tx_mcs13_max_nss,
+							   IEEE80211_EHT_MCS_NSS_RX));
+		if (bw_20->rx_tx_mcs11_max_nss)
+			max_nss = max(max_nss, u8_get_bits(bw_20->rx_tx_mcs11_max_nss,
+							   IEEE80211_EHT_MCS_NSS_RX));
+		if (bw_20->rx_tx_mcs9_max_nss)
+			max_nss = max(max_nss, u8_get_bits(bw_20->rx_tx_mcs9_max_nss,
+							   IEEE80211_EHT_MCS_NSS_RX));
+		if (bw_20->rx_tx_mcs7_max_nss)
+			max_nss = max(max_nss, u8_get_bits(bw_20->rx_tx_mcs7_max_nss,
+							   IEEE80211_EHT_MCS_NSS_RX));
+	} else {
+		if (bw->rx_tx_mcs13_max_nss)
+			max_nss = max(max_nss, u8_get_bits(bw->rx_tx_mcs13_max_nss,
+							   IEEE80211_EHT_MCS_NSS_RX));
+		if (bw->rx_tx_mcs11_max_nss)
+			max_nss = max(max_nss, u8_get_bits(bw->rx_tx_mcs11_max_nss,
+							   IEEE80211_EHT_MCS_NSS_RX));
+		if (bw->rx_tx_mcs9_max_nss)
+			max_nss = max(max_nss, u8_get_bits(bw->rx_tx_mcs9_max_nss,
+							   IEEE80211_EHT_MCS_NSS_RX));
+	}
+
+	max_nss = min(max_nss, (uint8_t)eht_nss);
+
+	arg->peer_nss = min(link_sta->rx_nss, max_nss);
+
+	ath12k_dbg(ar->ab, ATH12K_DBG_MAC,
+		   "mac eht peer %pM nss %d mcs cnt %d ru_punct_bitmap 0x%x\n",
+		   arsta->addr, arg->peer_nss, arg->peer_eht_mcs_count,
+		   arg->punct_bitmap);
 }
 
 static void ath12k_peer_assoc_h_mlo(struct ath12k_link_sta *arsta,
Signature · 1 line
2.53.0
author maintainer
#171 lore raw

PATCH 170/990 wifi: ath12k: dont advertise EHT-MCS15 to firmware unless we support it

In reply to Greg Kroah-Hartman

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

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

From: Baochen Qiang <[email protected]>

[ Upstream commit 83d689bbe8f90ce39961bcc3a64f2ca2ec184019 ]

ath12k_peer_assoc_h_eht() copies the peer's EHT PHY capabilities into the WMI peer assoc command as is, including the EHT-MCS15 support bits. Firmware rate control enables EHT-MCS15 for TX whenever those bits are set, without checking whether the local PHY supports MCS15.

Currently WCN7850 firmware does not support EHT-MCS15 for TX and does not advertise it in its own EHT PHY capabilities. When connected to an AP that advertises MCS15 support, rate control may still select EHT-MCS15, and every PPDU at that rate is aborted by the PHY before it goes on the air. TX then stops for minutes while the association stays up, and frames sit in the queue until the firmware releases them as aged.

Keep only the peer's MCS15 support bits that we also support ourselves to fix it. Chips that support MCS15 are not affected.

Tested-on: WCN7850 hw2.0 PCI WLAN.HMT.1.1.c7-00108-QCAHMTSWPL_V1.0_V2.0_SILICONZ_UPSTREAM-3

---
 drivers/net/wireless/ath/ath12k/mac.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
drivers/net/wireless/ath/ath12k/mac.c +11 -0
index 94e5af15cd618..c3f761cc35558 100644
@@ -3239,6 +3239,7 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar,
 	u32 *rx_mcs, *tx_mcs;
 	u16 *eht_mcs_mask;
 	u8 max_nss = 0;
+	u8 mcs15;
 
 	lockdep_assert_wiphy(ath12k_ar_to_hw(ar)->wiphy);
 
@@ -3289,6 +3290,16 @@ static void ath12k_peer_assoc_h_eht(struct ath12k *ar,
 	memcpy(arg->peer_eht_cap_phy, eht_cap->eht_cap_elem.phy_cap_info,
 	       sizeof(eht_cap->eht_cap_elem.phy_cap_info));
 
+	/*
+	 * Firmware rate control enables EHT-MCS15 based only on the peer's
+	 * MCS15 support bits, so keep only the ones we support ourselves.
+	 */
+	mcs15 = u8_get_bits(eht_cap->eht_cap_elem.phy_cap_info[6] &
+			    own_eht_cap->eht_cap_elem.phy_cap_info[6],
+			    IEEE80211_EHT_PHY_CAP6_MCS15_SUPP_MASK);
+	u8p_replace_bits(&((u8 *)arg->peer_eht_cap_phy)[6], mcs15,
+			 IEEE80211_EHT_PHY_CAP6_MCS15_SUPP_MASK);
+
 	rx_mcs = arg->peer_eht_rx_mcs_set;
 	tx_mcs = arg->peer_eht_tx_mcs_set;
 
Signature · 1 line
2.53.0
author maintainer
#172 lore raw

PATCH 171/990 ASoC: meson: axg-fifo: request the irq with the clock enabled

In reply to Greg Kroah-Hartman

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

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

From: Jerome Brunet <[email protected]>

[ Upstream commit 82fa7bfab6b961a03d6575348334e0ec15fdc712 ]

The fifo irq handler accesses registers which need pclk, but the irq is requested before pclk is enabled on open and freed after it is disabled on close.

Request the irq after enabling pclk and masking the fifo irqs. Free it before disabling pclk.

---
 sound/soc/meson/axg-fifo.c | 28 ++++++++++++++--------------
 1 file changed, 14 insertions(+), 14 deletions(-)
sound/soc/meson/axg-fifo.c +14 -14
index 75909196b7698..edf43b7fb5cf5 100644
@@ -244,17 +244,10 @@ int axg_fifo_pcm_open(struct snd_soc_component *component,
 	if (ret)
 		return ret;
 
-	/* Use the threaded irq handler only with non-atomic links */
-	ret = request_threaded_irq(fifo->irq, NULL,
-				   axg_fifo_pcm_irq_block,
-				   IRQF_ONESHOT, dev_name(dev), ss);
-	if (ret)
-		return ret;
-
 	/* Enable pclk to access registers and clock the fifo ip */
 	ret = clk_prepare_enable(fifo->pclk);
 	if (ret)
-		goto free_irq;
+		return ret;
 
 	/* Setup status2 so it reports the memory pointer */
 	regmap_update_bits(fifo->map, FIFO_CTRL1,
@@ -271,17 +264,24 @@ int axg_fifo_pcm_open(struct snd_soc_component *component,
 	/* Clear any pending interrupt */
 	axg_fifo_ack_irq(fifo, FIFO_INT_MASK);
 
+	/* Use the threaded irq handler only with non-atomic links */
+	ret = request_threaded_irq(fifo->irq, NULL,
+				   axg_fifo_pcm_irq_block,
+				   IRQF_ONESHOT, dev_name(dev), ss);
+	if (ret)
+		goto free_clk;
+
 	/* Take memory arbitror out of reset */
 	ret = reset_control_deassert(fifo->arb);
 	if (ret)
-		goto free_clk;
+		goto free_irq;
 
 	return 0;
 
-free_clk:
-	clk_disable_unprepare(fifo->pclk);
 free_irq:
 	free_irq(fifo->irq, ss);
+free_clk:
+	clk_disable_unprepare(fifo->pclk);
 	return ret;
 }
 EXPORT_SYMBOL_GPL(axg_fifo_pcm_open);
@@ -295,12 +295,12 @@ int axg_fifo_pcm_close(struct snd_soc_component *component,
 	/* Put the memory arbitror back in reset */
 	ret = reset_control_assert(fifo->arb);
 
-	/* Disable fifo ip and register access */
-	clk_disable_unprepare(fifo->pclk);
-
 	/* remove IRQ */
 	free_irq(fifo->irq, ss);
 
+	/* Disable fifo ip and register access */
+	clk_disable_unprepare(fifo->pclk);
+
 	return ret;
 }
 EXPORT_SYMBOL_GPL(axg_fifo_pcm_close);
Signature · 1 line
2.53.0
author maintainer
#173 lore raw

PATCH 172/990 Bluetooth: hci_core: Initialize IRK before publication

In reply to Greg Kroah-Hartman

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

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

From: Binbin Deng <[email protected]>

[ Upstream commit f0cf5a24cefeb629876bd15d668ff062c8655e28 ]

hci_add_irk() initializes the identity address and address type of a newly allocated IRK, publishes it on hdev->identity_resolving_keys, and only then initializes its value and RPA. RCU readers such as hci_find_irk_by_rpa() and the debugfs identity_resolving_keys_show() can traverse the new entry during that window and see a zero or partially initialized IRK.

The race is reachable by racing an IRK addition with another CPU resolving or dumping IRKs. In particular, userspace can issue MGMT_OP_LOAD_IRKS while another process reads the corresponding debugfs file or triggers RPA resolution.

Initialize the IRK value and RPA before publishing a newly allocated IRK. Existing IRKs remain published and continue to be updated in place.

Found during a static-analysis-assisted audit: candidate sites were surfaced by a Coccinelle rule, and the reader/writer paths were confirmed by LLM-assisted (GLM-5.3) code inspection. The issue was not observed at runtime; it is identified by code inspection only.

Fixes adae20cb2d20 ("Bluetooth: Convert IRK list to RCU")
Assisted-by GLM-5.3 coccinelle
---
 net/bluetooth/hci_core.c | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
net/bluetooth/hci_core.c +6 -3
index bb5bbeefcc67e..78c4be8e7109e 100644
@@ -1351,9 +1351,10 @@ struct smp_ltk *hci_add_ltk(struct hci_dev *hdev, bdaddr_t *bdaddr,
 struct smp_irk *hci_add_irk(struct hci_dev *hdev, bdaddr_t *bdaddr,
 			    u8 addr_type, u8 val[16], bdaddr_t *rpa)
 {
-	struct smp_irk *irk;
+	struct smp_irk *irk, *old_irk;
 
-	irk = hci_find_irk_by_addr(hdev, bdaddr, addr_type);
+	old_irk = hci_find_irk_by_addr(hdev, bdaddr, addr_type);
+	irk = old_irk;
 	if (!irk) {
 		irk = kzalloc(sizeof(*irk), GFP_KERNEL);
 		if (!irk)
@@ -1362,12 +1363,14 @@ struct smp_irk *hci_add_irk(struct hci_dev *hdev, bdaddr_t *bdaddr,
 		bacpy(&irk->bdaddr, bdaddr);
 		irk->addr_type = addr_type;
 
-		list_add_rcu(&irk->list, &hdev->identity_resolving_keys);
 	}
 
 	memcpy(irk->val, val, 16);
 	bacpy(&irk->rpa, rpa);
 
+	if (!old_irk)
+		list_add_rcu(&irk->list, &hdev->identity_resolving_keys);
+
 	return irk;
 }
 
Signature · 1 line
2.53.0
author maintainer
#174 lore raw

PATCH 173/990 Bluetooth: hci_core: Initialize link key before publication

In reply to Greg Kroah-Hartman

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

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

From: Binbin Deng <[email protected]>

[ Upstream commit ae9c8df1ffb84560ac01cbdc26cfb19027f4d25f ]

hci_add_link_key() allocates a new link key with kzalloc(), inserts it into hdev->link_keys with list_add_rcu(), and only then initializes its address, value, type, and PIN length. RCU readers such as hci_find_link_key() and the debugfs link_keys_show() do not take hci_dev_lock, so they can traverse the new entry during that initialization window and observe a zero or partially initialized key.

This can be triggered by racing a link-key update with another CPU looking up or dumping keys. In particular, userspace can issue MGMT_OP_LOAD_LINK_KEYS while another process reads the corresponding debugfs file.

Complete all fields of a newly allocated key before publishing it with list_add_rcu(). Existing keys remain visible and keep their current in-place update behavior.

Found during a static-analysis-assisted audit: candidate sites were surfaced by a Coccinelle rule, and the reader/writer paths were confirmed by LLM-assisted (GLM-5.3) code inspection. The issue was not observed at runtime; it is identified by code inspection only.

Fixes 0378b5977013 ("Bluetooth: Convert link keys list to use RCU")
---
 net/bluetooth/hci_core.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
net/bluetooth/hci_core.c +3 -1
index 78c4be8e7109e..70f7e4da66f33 100644
@@ -1288,7 +1288,6 @@ struct link_key *hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn,
 		key = kzalloc(sizeof(*key), GFP_KERNEL);
 		if (!key)
 			return NULL;
-		list_add_rcu(&key->list, &hdev->link_keys);
 	}
 
 	BT_DBG("%s key for %pMR type %u", hdev->name, bdaddr, type);
@@ -1312,6 +1311,9 @@ struct link_key *hci_add_link_key(struct hci_dev *hdev, struct hci_conn *conn,
 	else
 		key->type = type;
 
+	if (!old_key)
+		list_add_rcu(&key->list, &hdev->link_keys);
+
 	if (persistent)
 		*persistent = hci_persistent_key(hdev, conn, type,
 						 old_key_type);
Signature · 1 line
2.53.0
author maintainer
#175 lore raw

PATCH 174/990 Bluetooth: hci_core: Initialize LTK before publication

In reply to Greg Kroah-Hartman

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

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

From: Binbin Deng <[email protected]>

[ Upstream commit 4335849380aa1081ee9a1c2b934cbdda0961fa57 ]

hci_add_ltk() publishes a newly allocated LTK on hdev->long_term_keys before initializing its address, type, value, authentication state, encryption size, EDIV, and random value. hci_find_ltk() and the debugfs long_term_keys_show() traverse this list under RCU and can therefore see a zero or partially initialized key before those stores complete.

The race is reachable by racing an LTK addition with another CPU looking up or dumping long-term keys. For example, userspace can issue MGMT_OP_LOAD_LONG_TERM_KEYS while another process reads the corresponding debugfs file.

Initialize all fields of a new LTK before list_add_rcu() makes it visible to RCU readers. Existing LTKs remain published and continue to be updated in place.

Found during a static-analysis-assisted audit: candidate sites were surfaced by a Coccinelle rule, and the reader/writer paths were confirmed by LLM-assisted (GLM-5.3) code inspection. The issue was not observed at runtime; it is identified by code inspection only.

Fixes 970d0f1b2803 ("Bluetooth: Convert LTK list to RCU")
Assisted-by GLM-5.3 coccinelle
---
 net/bluetooth/hci_core.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)
net/bluetooth/hci_core.c +3 -1
index 70f7e4da66f33..49788a7bdba29 100644
@@ -1335,7 +1335,6 @@ struct smp_ltk *hci_add_ltk(struct hci_dev *hdev, bdaddr_t *bdaddr,
 		key = kzalloc(sizeof(*key), GFP_KERNEL);
 		if (!key)
 			return NULL;
-		list_add_rcu(&key->list, &hdev->long_term_keys);
 	}
 
 	bacpy(&key->bdaddr, bdaddr);
@@ -1347,6 +1346,9 @@ struct smp_ltk *hci_add_ltk(struct hci_dev *hdev, bdaddr_t *bdaddr,
 	key->enc_size = enc_size;
 	key->type = type;
 
+	if (!old_key)
+		list_add_rcu(&key->list, &hdev->long_term_keys);
+
 	return key;
 }
 
Signature · 1 line
2.53.0
author maintainer
#176 lore raw

PATCH 175/990 Bluetooth: hci_core: Fix queuing rx_work while workqueue is drained

In reply to Greg Kroah-Hartman

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

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

From: Akhil Arul <[email protected]>

[ Upstream commit 19b4e5701712f74d005cc66a36374559e8dfd281 ]

hci_recv_frame() drops a frame unless HCI_UP or HCI_INIT is set, but the check is not synchronized with hci_dev_close_sync(). A driver can pass the check, then close clears HCI_UP, flushes rx_work and starts drain_workqueue(), and the late queue_work() of rx_work hits the draining workqueue:

workqueue: cannot queue hci_rx_work on wq hci0

  WARNING: kernel/workqueue.c:2352 at __queue_work+0x2c0/0x780
  Call Trace:
   queue_work_on+0xb2/0xc0
   hci_recv_frame+0x18f/0x330
   vhci_write+0x174/0x240
   vfs_write+0x271/0x680
   ksys_write+0x7c/0x110

Skipping the queue_work() while HCI_CMD_DRAIN_WORKQUEUE is set, as done for tx_work, does not work for rx_work: the flag covers the whole close, and events still have to be received in that window, for the commands sent by hdev->shutdown() and for the reset done with HCI_QUIRK_RESET_ON_CLOSE.

Run hci_recv_frame() under rcu_read_lock() and wait with synchronize_rcu() once HCI_UP has been cleared, so that every caller which still saw HCI_UP has queued its work before the workqueue is drained, and later callers drop the frame.

HCI_INIT does not reopen that window. Apart from the HCI_QUIRK_RESET_ON_CLOSE reset, which runs after drain_workqueue() has returned, it is only set by hci_dev_init_sync() during open, and open and close are serialized by hci_req_sync_lock. So once the grace period has ended, nothing can pass the check and queue rx_work until the drain is over.

Tested in qemu with the syzbot C reproducer, one run per boot: the warning showed up on 12 of 30 boots before and on none of 42 boots after. Bringing a vhci controller up and down 50 times behaves the same with and without this change.

Fixes 76727c02c1e1 ("Bluetooth: Call drain_workqueue() before resetting state")
Reported-by [email protected]
---
 net/bluetooth/hci_core.c | 9 +++++++++
 net/bluetooth/hci_sync.c | 5 +++++
 2 files changed, 14 insertions(+)
net/bluetooth/hci_core.c +9 -0
index 49788a7bdba29..e4caf79c2d7c3 100644
@@ -2940,8 +2940,14 @@ int hci_recv_frame(struct hci_dev *hdev, struct sk_buff *skb)
 {
 	u8 dev_pkt_type;
 
+	/* Pairs with synchronize_rcu() in hci_dev_close_sync(), so rx_work is
+	 * not queued once the workqueue is being drained.
+	 */
+	rcu_read_lock();
+
 	if (!hdev || (!test_bit(HCI_UP, &hdev->flags)
 		      && !test_bit(HCI_INIT, &hdev->flags))) {
+		rcu_read_unlock();
 		kfree_skb(skb);
 		return -ENXIO;
 	}
@@ -2976,6 +2982,7 @@ int hci_recv_frame(struct hci_dev *hdev, struct sk_buff *skb)
 	case HCI_DRV_PKT:
 		break;
 	default:
+		rcu_read_unlock();
 		kfree_skb(skb);
 		return -EINVAL;
 	}
@@ -2989,6 +2996,8 @@ int hci_recv_frame(struct hci_dev *hdev, struct sk_buff *skb)
 	skb_queue_tail(&hdev->rx_q, skb);
 	queue_work(hdev->workqueue, &hdev->rx_work);
 
+	rcu_read_unlock();
+
 	return 0;
 }
 EXPORT_SYMBOL(hci_recv_frame);
net/bluetooth/hci_sync.c +5 -0
index 6967da50aef05..5be062fdeb967 100644
@@ -5503,6 +5503,11 @@ int hci_dev_close_sync(struct hci_dev *hdev)
 		return err;
 	}
 
+	/* Wait for hci_recv_frame() callers that still saw HCI_UP, so that
+	 * none of them queues rx_work while the workqueue is drained below.
+	 */
+	synchronize_rcu();
+
 	hci_leds_update_powered(hdev, false);
 
 	/* Flush RX and TX works */
Signature · 1 line
2.53.0
author maintainer
#177 lore raw

PATCH 176/990 Bluetooth: btintel: fix buffer over-read in fw payload

In reply to Greg Kroah-Hartman

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

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

From: Catherine L <[email protected]>

[ Upstream commit f92b7bca985205082c86140d0bd7c86c5be00efc ]

The firmware decoder cast fw_ptr + frag_len to struct hci_command_hdr and read cmd->plen before confirming the header and payload still fit in the remaining firmware buffer.

Add explicit bounds checks before each dereference:
1. Reject if the command header is not fully contained in remain.
2. Reject if the full command including payload exceeds remain.
3. Log the offending fragment length and remaining size before returning -EINVAL.

Fixes fbbe83c52bc0d ("Bluetooth: btintel: Create common function for firmware download")
---
 drivers/bluetooth/btintel.c | 24 +++++++++++++++++++++++-
 1 file changed, 23 insertions(+), 1 deletion(-)
drivers/bluetooth/btintel.c +23 -1
index f56a4ebd26ed8..86c3b319ae2a7 100644
@@ -1089,7 +1089,29 @@ static int btintel_download_firmware_payload(struct hci_dev *hdev,
 	err = -EINVAL;
 
 	while (fw_ptr - fw->data < fw->size) {
-		struct hci_command_hdr *cmd = (void *)(fw_ptr + frag_len);
+		struct hci_command_hdr *cmd;
+		size_t remain = fw->size - (fw_ptr - fw->data);
+
+		/* Ensure the header fits before dereferencing */
+		if (frag_len + sizeof(*cmd) > remain) {
+			bt_dev_err(hdev,
+				   "Firmware buffer overrun at header (frag_len %u, need %zu, remain %zu)",
+				   frag_len, frag_len + sizeof(*cmd), remain);
+			err = -EINVAL;
+			goto done;
+		}
+
+		cmd = (void *)(fw_ptr + frag_len);
+
+		/* Ensure the full command (header + payload) fits before use */
+		if (frag_len + sizeof(*cmd) + cmd->plen > remain) {
+			bt_dev_err(hdev,
+				   "Firmware buffer overrun at payload (frag_len %u, plen %u, need %zu, remain %zu)",
+				   frag_len, cmd->plen,
+				   frag_len + sizeof(*cmd) + cmd->plen, remain);
+			err = -EINVAL;
+			goto done;
+		}
 
 		frag_len += sizeof(*cmd) + cmd->plen;
 
Signature · 1 line
2.53.0
author maintainer
#178 lore raw

PATCH 177/990 Bluetooth: hci_event: Clear explicit connect state on LE connection

In reply to Greg Kroah-Hartman

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

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

From: Kevin Dewald <[email protected]>

[ Upstream commit f5cd268af1c6f87fb3847e98274e22b8c6324aa4 ]

Since commit 6cd29ec6ae5e ("Bluetooth: hci_sync: Wait for proper events when connecting LE"), create_le_conn_complete() only runs once the LE Connection Complete event has been handled, and le_conn_complete_evt() has already removed the connection parameters from pend_le_conns by then. hci_connect_le_scan_cleanup() looks the parameters up in pend_le_conns, so after a successful connection it no longer clears explicit_connect, nor deletes the parameters that were only created for the explicit connect.

The parameters of every device connected through an explicit connect, such as an L2CAP or ATT connect or MGMT Pair Device, are thus left with explicit_connect set. MGMT Remove Device for all devices then keeps them as HCI_AUTO_CONN_EXPLICIT instead of freeing them, and if the device was set to auto-connect and is disconnected, they also stay on
pend_le_conns: the kernel keeps scanning for the device and connects to it as soon as it advertises, although no one asked for it any more.

Do the cleanup in le_conn_complete_evt() instead, where the explicit connect request is fulfilled: clear explicit_connect, delete the parameters if they only existed for it, and put report parameters back on pend_le_reports. Auto-connect parameters are added back to pend_le_conns on disconnection, as before. Update the comment in hci_explicit_conn_params_set() that names hci_connect_le_scan_cleanup() as the only place deleting them.

Fixes 6cd29ec6ae5e ("Bluetooth: hci_sync: Wait for proper events when connecting LE")
Assisted-by Claude:claude-opus-5.5
---
 net/bluetooth/hci_conn.c  |  5 +++--
 net/bluetooth/hci_event.c | 22 ++++++++++++++++++++++
 2 files changed, 25 insertions(+), 2 deletions(-)
net/bluetooth/hci_conn.c +3 -2
index 32cabe83351ac..f7645dc0ad2ae 100644
@@ -1488,8 +1488,9 @@ static int hci_explicit_conn_params_set(struct hci_dev *hdev,
 		if (!params)
 			return -ENOMEM;
 
-		/* If we created new params, mark them to be deleted in
-		 * hci_connect_le_scan_cleanup. It's different case than
+		/* If we created new params, mark them to be deleted once the
+		 * explicit connect is done, see le_conn_complete_evt() and
+		 * hci_connect_le_scan_cleanup(). It's different case than
 		 * existing disabled params, those will stay after cleanup.
 		 */
 		params->auto_connect = HCI_AUTO_CONN_EXPLICIT;
net/bluetooth/hci_event.c +22 -0
index 572f195f09c13..4be09dd9d9597 100644
@@ -5870,6 +5870,28 @@ static void le_conn_complete_evt(struct hci_dev *hdev, u8 status,
 			hci_conn_put(params->conn);
 			params->conn = NULL;
 		}
+
+		/* An explicit connect request is complete once connected, so
+		 * clean it up here: hci_connect_le_scan_cleanup() no longer
+		 * finds the params since they have just been removed from
+		 * pend_le_conns.
+		 */
+		if (params->explicit_connect) {
+			params->explicit_connect = false;
+
+			switch (params->auto_connect) {
+			case HCI_AUTO_CONN_EXPLICIT:
+				hci_conn_params_del(hdev, &conn->dst,
+						    conn->dst_type);
+				break;
+			case HCI_AUTO_CONN_REPORT:
+				hci_pend_le_list_add(params,
+						     &hdev->pend_le_reports);
+				break;
+			default:
+				break;
+			}
+		}
 	}
 
 unlock:
Signature · 1 line
2.53.0
author maintainer
#161 lore raw

PATCH 160/990 virtio-blk: clamp max_segments to virtqueue ring size

In reply to Greg Kroah-Hartman

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

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

From: Sergii Ushakov <[email protected]>

[ Upstream commit 434d2bc41bd0c0ac576d4d259bd9f2ab49071174 ]

In virtblk_add_req(), each request consumes 2 extra descriptors (out_hdr and in_hdr) in addition to the data scatter-gather segments.

When a hypervisor (e.g. QNX Hypervisor) advertises VIRTIO_BLK_F_SEG_MAX with seg_max = 1024 alongside a 1024-entry split ring (vring.num = 1024) and VIRTIO_RING_F_INDIRECT_DESC disabled, lim->max_segments is set to 1024. When the block layer submits requests with 1023 or 1024 data segments, total_sg reaches 1025 or 1026. This exceeds vring.num (1024), causing virtqueue_add_split() to return -ENOSPC and permanently wedge the blk-mq queue.

Furthermore, the Virtio specification (2.7.5.3.1) requires that a descriptor chain never exceed the Queue Size, and virtqueue_add_split() falls back to direct descriptors if indirect table allocation fails.

Fix this by:
1. Rejecting queues with ring_size < 3 at probe, or ring_size < (queue_max_segments + 2) during resume/reset recovery in init_vq().
2. Unconditionally clamping sg_elems to (ring_size - 2) across all virtqueues in virtblk_read_limits().

Fixes 0864b79a1533 ("virtio: block: dynamic maximum segments")

Message-ID: <[email protected]>

---
 drivers/block/virtio_blk.c | 44 +++++++++++++++++++++++++++++++++++++-
 1 file changed, 43 insertions(+), 1 deletion(-)
drivers/block/virtio_blk.c +43 -1
index feb4dab8eac7b..6cfad73bf47df 100644
@@ -1020,6 +1020,30 @@ static int init_vq(struct virtio_blk *vblk)
 		goto out;
 
 	for (i = 0; i < num_vqs; i++) {
+		unsigned int ring_size = virtqueue_get_vring_size(vqs[i]);
+		/*
+		 * Each request consumes 2 extra descriptors (out_hdr and
+		 * in_hdr) in addition to the data segments.
+		 *
+		 * At initial probe (!vblk->disk), each virtqueue must fit at
+		 * least 1 data segment + 2 header descriptors (3).
+		 * On resume/recovery (vblk->disk), each virtqueue must fit the
+		 * existing queue_max_segments() + 2 header descriptors.
+		 */
+		unsigned int min_ring_size = 3;
+
+		if (vblk->disk)
+			min_ring_size = queue_max_segments(vblk->disk->queue) + 2;
+
+		if (ring_size < min_ring_size) {
+			dev_err(&vdev->dev,
+				"virtqueue %u ring size %u is smaller than minimum %u\n",
+				i, ring_size, min_ring_size);
+			vdev->config->del_vqs(vdev);
+			err = -EINVAL;
+			goto out;
+		}
+
 		spin_lock_init(&vblk->vqs[i].lock);
 		vblk->vqs[i].vq = vqs[i];
 	}
@@ -1247,7 +1271,7 @@ static int virtblk_read_limits(struct virtio_blk *vblk,
 	u16 min_io_size;
 	u8 physical_block_exp, alignment_offset;
 	size_t max_dma_size;
-	int err;
+	int err, i;
 
 	/* We need to know how many segments before we allocate. */
 	err = virtio_cread_feature(vdev, VIRTIO_BLK_F_SEG_MAX,
@@ -1261,6 +1285,23 @@ static int virtblk_read_limits(struct virtio_blk *vblk,
 	/* Prevent integer overflows and honor max vq size */
 	sg_elems = min_t(u32, sg_elems, VIRTIO_BLK_MAX_SG_ELEMS - 2);
 
+	/*
+	 * virtblk_add_req() uses separate outgoing and incoming header
+	 * descriptors (out_hdr and in_hdr), consuming 2 extra descriptors
+	 * per request in addition to the data segments.
+	 *
+	 * Per virtio specification (2.7.5.3.1), a driver MUST NOT create a
+	 * descriptor chain longer than the Queue Size of the device.
+	 *
+	 * Clamp max_segments to (ring_size - 2) across all virtqueues so
+	 * that a request never exceeds the ring size of any queue.
+	 */
+	for (i = 0; i < vblk->num_vqs; i++) {
+		u32 ring_size = virtqueue_get_vring_size(vblk->vqs[i].vq);
+
+		sg_elems = min_t(u32, sg_elems, ring_size - 2);
+	}
+
 	/* We can handle whatever the host told us to handle. */
 	lim->max_segments = sg_elems;
 
@@ -1460,6 +1501,7 @@ static int virtblk_probe(struct virtio_device *vdev)
 	mutex_init(&vblk->vdev_mutex);
 
 	vblk->vdev = vdev;
+	vblk->disk = NULL;
 
 	INIT_WORK(&vblk->config_work, virtblk_config_changed_work);
 
Signature · 1 line
2.53.0
author maintainer
#179 lore raw

PATCH 178/990 Bluetooth: btmtk: drop zero-length ISO packets from endpoint padding

In reply to Greg Kroah-Hartman

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

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

From: Chris Lu <[email protected]>

[ Upstream commit 8524c3588fbb9d5c1b876e6f908c42926845650d ]

The ISO interrupt IN endpoint delivers a fixed-size transfer that holds one HCI ISO packet and zero-fills the remainder. That padding belongs to the transfer rather than to the stream, so it has to be dropped instead of reported to the host.

btmtk_recv_isopkt() keeps parsing it: the zero bytes read as an ISO header with handle 0 and a Data_Total_Length of zero, and each one is passed to hci_recv_frame() as a complete frame. A single transfer yields a long run of them, which is what fills the HCI log with malformed ISO packets, and iso_recv() drops the SDU it is reassembling whenever handle 0 belongs to a live CIS/BIS.

A zero Data_Total_Length carries no ISO Data Load, so such a packet is never part of the stream. Check for the zero-filled remainder before starting to parse the next frame, rather than after assembling a 4-byte
header: a remainder shorter than HCI_ISO_HDR_SIZE would otherwise be held across calls as a partial header, corrupting the next transfer's framing. This also means a fully zero-filled remainder no longer costs an skb allocation that gets immediately freed. Reaching a zero Data_Total_Length any other way is then a genuine error, not padding.

This was observed on MT7925, but btmtk_recv_isopkt() is shared by every MediaTek USB controller that supports ISO data.

Fixes ceac1cb0259d ("Bluetooth: btusb: mediatek: add ISO data transmission functions")
---
 drivers/bluetooth/btmtk.c | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)
drivers/bluetooth/btmtk.c +20 -0
index 961a47a9c8c43..51b55eceba5f1 100644
@@ -7,6 +7,7 @@
 #include <linux/usb.h>
 #include <linux/iopoll.h>
 #include <linux/overflow.h>
+#include <linux/string.h>
 #include <linux/unaligned.h>
 
 #include <net/bluetooth/bluetooth.h>
@@ -1176,6 +1177,14 @@ static int btmtk_recv_isopkt(struct hci_dev *hdev, void *buffer, int count)
 		int len;
 
 		if (!skb) {
+			/* Drop the endpoint's zero-filled padding before
+			 * allocating an skb for it; a zero Data_Total_Length
+			 * check below would miss a padding remainder
+			 * shorter than an ISO header.
+			 */
+			if (mem_is_zero(buffer, count))
+				break;
+
 			skb = bt_skb_alloc(HCI_MAX_ISO_SIZE, GFP_ATOMIC);
 			if (!skb) {
 				err = -ENOMEM;
@@ -1199,6 +1208,17 @@ static int btmtk_recv_isopkt(struct hci_dev *hdev, void *buffer, int count)
 			/* Complete ISO header */
 			hci_skb_expect(skb) = __le16_to_cpu(dlen);
 
+			if (!hci_skb_expect(skb)) {
+				/* Zero padding was ruled out above, so a
+				 * zero Data_Total_Length here is invalid.
+				 */
+				kfree_skb(skb);
+				skb = NULL;
+
+				err = -EILSEQ;
+				break;
+			}
+
 			if (skb_tailroom(skb) < hci_skb_expect(skb)) {
 				kfree_skb(skb);
 				skb = NULL;
Signature · 1 line
2.53.0
author maintainer
#180 lore raw

PATCH 179/990 Bluetooth: btmtk: bound the ISO payload length by the controllers MTU

In reply to Greg Kroah-Hartman

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

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

From: Chris Lu <[email protected]>

[ Upstream commit d015faf684129a276f2137ad2e11c6c985294648 ]

btmtk_recv_isopkt() bounds the Data_Total_Length reported by the controller with skb_tailroom(skb) < hci_skb_expect(skb). That keeps the reassembly inside the skb, but it enforces no protocol limit: the head allocation is rounded up to the next kmalloc bucket and skb_tailroom() reports what the bucket can hold rather than what was requested, which is several hundred bytes more. An oversized length therefore passes, and the parser keeps pulling bytes out of the following transfers to fill it, swallowing the real ISO packets they carry until the frame is handed to hci_recv_frame().

The controller reports the largest ISO_Data_Packet_Length it will send in LE Read Buffer Size [v2], which hci_cc_le_read_buffer_size_v2() keeps in hdev->iso_mtu. Once that is available, bound the length by it and size the receive skb to hold that much plus the 4-byte header. HCI_MAX_ISO_SIZE is kept only as a fallback for the window before the command completes.

Keep the skb_tailroom() test as well, because a fragment started before hdev->iso_mtu was populated sits in an skb sized for the fallback.

Fixes ceac1cb0259d ("Bluetooth: btusb: mediatek: add ISO data transmission functions")
---
 drivers/bluetooth/btmtk.c | 18 ++++++++++++++++--
 1 file changed, 16 insertions(+), 2 deletions(-)
drivers/bluetooth/btmtk.c +16 -2
index 51b55eceba5f1..1518b93f4676d 100644
@@ -1168,8 +1168,15 @@ static int btmtk_recv_isopkt(struct hci_dev *hdev, void *buffer, int count)
 	struct btmtk_data *btmtk_data = hci_get_priv(hdev);
 	struct sk_buff *skb;
 	unsigned long flags;
+	unsigned int iso_mtu;
 	int err = 0;
 
+	/* The controller reports the largest Data_Total_Length it will send in
+	 * LE Read Buffer Size [v2]. Fall back to HCI_MAX_ISO_SIZE while that
+	 * command has not completed yet.
+	 */
+	iso_mtu = hdev->iso_mtu ? hdev->iso_mtu : HCI_MAX_ISO_SIZE;
+
 	spin_lock_irqsave(&btmtk_data->isorxlock, flags);
 	skb = btmtk_data->isopkt_skb;
 
@@ -1185,7 +1192,8 @@ static int btmtk_recv_isopkt(struct hci_dev *hdev, void *buffer, int count)
 			if (mem_is_zero(buffer, count))
 				break;
 
-			skb = bt_skb_alloc(HCI_MAX_ISO_SIZE, GFP_ATOMIC);
+			skb = bt_skb_alloc(HCI_ISO_HDR_SIZE + iso_mtu,
+					   GFP_ATOMIC);
 			if (!skb) {
 				err = -ENOMEM;
 				break;
@@ -1219,7 +1227,13 @@ static int btmtk_recv_isopkt(struct hci_dev *hdev, void *buffer, int count)
 				break;
 			}
 
-			if (skb_tailroom(skb) < hci_skb_expect(skb)) {
+			/* Reject a length the controller said it would never
+			 * send. The skb_tailroom() test is kept because a
+			 * fragment started before hdev->iso_mtu was populated
+			 * sits in a smaller skb than iso_mtu now allows.
+			 */
+			if (hci_skb_expect(skb) > iso_mtu ||
+			    skb_tailroom(skb) < hci_skb_expect(skb)) {
 				kfree_skb(skb);
 				skb = NULL;
 
Signature · 1 line
2.53.0
author maintainer
#181 lore raw

PATCH 180/990 Bluetooth: btmtk: derive the firmware ISO setting from MTK_ISO_THRESHOLD

In reply to Greg Kroah-Hartman

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

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

From: Chris Lu <[email protected]>

[ Upstream commit 855c9a54608f1e94f4c52afe3790def30534155a ]

The ISO data transfer size is spelled out twice: as a raw byte pair in the vendor command sent by btmtk_usb_isointf_init(), and as MTK_ISO_THRESHOLD for the padding in btmtk_isopkt_pad(). Build the command payload from the macro so the size is stated once, and update the setting for current MediaTek controllers.

Fixes ceac1cb0259d ("Bluetooth: btusb: mediatek: add ISO data transmission functions")
---
 drivers/bluetooth/btmtk.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/bluetooth/btmtk.c +3 -3
index 1518b93f4676d..5863b63f5d3f0 100644
@@ -25,7 +25,7 @@
 #define MTK_SEC_MAP_NEED_SEND_SIZE	52
 
 /* It is for mt79xx iso data transmission setting */
-#define MTK_ISO_THRESHOLD	264
+#define MTK_ISO_THRESHOLD	342
 
 struct btmtk_patch_header {
 	u8 datetime[16];
@@ -1352,7 +1352,7 @@ static int btmtk_submit_intr_urb(struct hci_dev *hdev, gfp_t mem_flags)
 static int btmtk_usb_isointf_init(struct hci_dev *hdev)
 {
 	struct btmtk_data *btmtk_data = hci_get_priv(hdev);
-	u8 iso_param[2] = { 0x08, 0x01 };
+	__le16 iso_param = cpu_to_le16(MTK_ISO_THRESHOLD);
 	struct sk_buff *skb;
 	int err;
 
@@ -1367,7 +1367,7 @@ static int btmtk_usb_isointf_init(struct hci_dev *hdev)
 		return err;
 	}
 
-	skb = __hci_cmd_sync(hdev, 0xfd98, sizeof(iso_param), iso_param,
+	skb = __hci_cmd_sync(hdev, 0xfd98, sizeof(iso_param), &iso_param,
 			     HCI_INIT_TIMEOUT);
 	if (IS_ERR(skb)) {
 		bt_dev_err(hdev, "Failed to apply iso setting (%ld)", PTR_ERR(skb));
Signature · 1 line
2.53.0
author maintainer
#182 lore raw

PATCH 181/990 Bluetooth: hci_sync: Copy the LE accept list under hdev->lock

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit 674006912777747170ad70d7727804ad4f2d047f ]

The LE accept-list mirror consists of bdaddr_list entries that are added, removed and freed under hdev->lock. The ordinary branch of hci_update_accept_list_sync() traverses this list without that lock. The request worker's req_lock does not serialize raw HCI completions, and the RCU sections protect connection and pending-action lookups, not the accept-list nodes.

Changing connectability can reach this iterator through set_connectable_sync(), hci_update_connectable_sync(), hci_update_passive_scan_sync() and hci_passive_scan_sync(). With a populated mirror, a privileged raw HCI sender can issue HCI_OP_LE_CLEAR_ACCEPT_LIST while request work is reconciling it:

Request work HCI event work
select b and successor t
hci_cc_le_clear_accept_list()
hci_dev_lock(hdev) hci_bdaddr_list_clear()
unlink nodes and kfree(b)
hci_dev_unlock(hdev)
read b->bdaddr_type

The clear completion can therefore free the selected node before its field read, or the saved successor before the iterator advances. KASAN reported a one-byte read of bdaddr_type from the freed node.

Copy each entry's address and type under hdev->lock and reconcile the private array instead. Release the mutex before issuing synchronous commands, since their completion handlers also acquire it. Free the copy after iteration and use the existing error path to disable accept-list filtering if allocation fails.

This change has not been runtime-tested.

KASAN report as below:

    ==================================================================
    BUG: KASAN: slab-use-after-free in hci_passive_scan_sync+0x1cc4/0x1f80
    Read of size 1 at addr ffff888105ee6c56 by task kworker/u17:1/499

    Workqueue: hci0 hci_cmd_sync_work
    Call Trace:
     <TASK>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     ? hci_passive_scan_sync+0x1cc4/0x1f80
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __virt_addr_valid+0x20d/0x410
     ? hci_passive_scan_sync+0x1cc4/0x1f80
     kasan_report+0xe0/0x110
     ? hci_passive_scan_sync+0x1cc4/0x1f80
     hci_passive_scan_sync+0x1cc4/0x1f80
     ? pmbd_gate_site_armed+0x31/0x1c0
     ? __pfx_hci_passive_scan_sync+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? pmbd_probe_hit_cookie+0x10/0x1c0
     ? __pfx_pmbd_probe_hit_cookie+0x10/0x10
     ? hci_update_passive_scan_sync+0x43f/0x9e0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_release+0xc8/0x280
     hci_update_passive_scan_sync+0x473/0x9e0
     hci_update_connectable_sync+0x13c/0x250
     set_connectable_sync+0x39/0xb0
     hci_cmd_sync_work+0x1b3/0x450
     ? srso_alias_return_thunk+0x5/0xfbef5
     process_one_work+0x908/0x19c0
     ? __pfx_process_one_work+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_is_held_type+0x8f/0x100
     ? srso_alias_return_thunk+0x5/0xfbef5
     worker_thread+0x65c/0xe40
     ? __pfx_worker_thread+0x10/0x10
     kthread+0x34f/0x460
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_kthread+0x10/0x10
     ret_from_fork+0x659/0x940
     ? __pfx_ret_from_fork+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __switch_to+0x74f/0xf80
     ? __pfx_kthread+0x10/0x10
     ret_from_fork_asm+0x1a/0x30
     </TASK>

    Allocated by task 511:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_kmalloc+0xaa/0xb0
     __kmalloc_cache_noprof+0x251/0x610
     hci_bdaddr_list_add+0x179/0x390
     hci_cc_le_add_to_accept_list+0x189/0x2d0
     hci_cmd_complete_evt+0x373/0xab0
     hci_event_packet+0x4e8/0xc70
     hci_rx_work+0x367/0xf00
     process_one_work+0x908/0x19c0
     worker_thread+0x65c/0xe40
     kthread+0x34f/0x460
     ret_from_fork+0x659/0x940
     ret_from_fork_asm+0x1a/0x30

    Freed by task 511:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     kasan_save_free_info+0x3b/0x60
     __kasan_slab_free+0x5f/0x80
     kfree+0x307/0x580
     hci_bdaddr_list_clear+0x134/0x230
     hci_cc_le_clear_accept_list+0x80/0x1f0
     hci_cmd_complete_evt+0x373/0xab0
     hci_event_packet+0x4e8/0xc70
     hci_rx_work+0x367/0xf00
     process_one_work+0x908/0x19c0
     worker_thread+0x65c/0xe40
     kthread+0x34f/0x460
     ret_from_fork+0x659/0x940
     ret_from_fork_asm+0x1a/0x30

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

    The buggy address belongs to the physical page:
        page: refcount:0 mapcount:0 mapping:0000000000000000
    index:0xffff888105ee69c0 pfn:0x105ee6
    flags: 0x200000000000200(workingset|node=0|zone=2)
    page_type: f5(slab)
        raw: 0200000000000200 ffff888100042780 ffffea0004187150
    ffffea00042534d0
        raw: ffff888105ee69c0 000000000040003f 00000000f5000000
    0000000000000000
    page dumped because: kasan: bad access detected

    Memory state around the buggy address:
     ffff888105ee6b00: fa fb fb fb fc fc fc fc fa fb fb fb fc fc fc fc
     ffff888105ee6b80: fa fb fb fb fc fc fc fc fa fb fb fb fc fc fc fc
    >ffff888105ee6c00: fa fb fb fb fc fc fc fc fa fb fb fb fc fc fc fc
                                                     ^
     ffff888105ee6c80: fa fb fb fb fc fc fc fc fa fb fb fb fc fc fc fc
     ffff888105ee6d00: fa fb fb fb fc fc fc fc fa fb fb fb fc fc fc fc
    ==================================================================
Fixes e8907f76544f ("Bluetooth: hci_sync: Make use of hci_cmd_sync_queue set 3")
Assisted-by LLM
---
 net/bluetooth/hci_sync.c | 53 ++++++++++++++++++++++++++++++++--------
 1 file changed, 43 insertions(+), 10 deletions(-)
net/bluetooth/hci_sync.c +43 -10
index 5be062fdeb967..7403fff7d7855 100644
@@ -2906,6 +2906,31 @@ static struct conn_params *conn_params_copy(struct list_head *list, size_t *n)
 	return p;
 }
 
+static struct conn_params *le_accept_list_copy(struct hci_dev *hdev,
+					       size_t *n)
+{
+	struct bdaddr_list *entry;
+	struct conn_params *params;
+	size_t i = 0;
+
+	hci_dev_lock(hdev);
+
+	*n = list_count_nodes(&hdev->le_accept_list);
+	params = kvzalloc_objs(struct conn_params, *n);
+	if (!params)
+		goto unlock;
+
+	list_for_each_entry(entry, &hdev->le_accept_list, list) {
+		bacpy(&params[i].addr, &entry->bdaddr);
+		params[i].addr_type = entry->bdaddr_type;
+		i++;
+	}
+
+unlock:
+	hci_dev_unlock(hdev);
+	return params;
+}
+
 /* Clear LE Accept List */
 static int hci_le_clear_accept_list_sync(struct hci_dev *hdev)
 {
@@ -2936,7 +2961,6 @@ static int hci_le_clear_accept_list_sync(struct hci_dev *hdev)
 static u8 hci_update_accept_list_sync(struct hci_dev *hdev)
 {
 	struct conn_params *params;
-	struct bdaddr_list *b, *t;
 	u8 num_entries = 0;
 	bool pend_conn, pend_report;
 	u8 filter_policy;
@@ -3001,20 +3025,27 @@ static u8 hci_update_accept_list_sync(struct hci_dev *hdev)
 	 * report. If not present in either list, then remove it from
 	 * the controller.
 	 */
-	list_for_each_entry_safe(b, t, &hdev->le_accept_list, list) {
+	params = le_accept_list_copy(hdev, &n);
+	if (!params) {
+		err = -ENOMEM;
+		goto done;
+	}
+
+	for (i = 0; i < n; i++) {
 		rcu_read_lock();
 
-		if (hci_conn_hash_lookup_le(hdev, &b->bdaddr, b->bdaddr_type)) {
+		if (hci_conn_hash_lookup_le(hdev, &params[i].addr,
+					    params[i].addr_type)) {
 			rcu_read_unlock();
 			continue;
 		}
 
 		pend_conn = hci_pend_le_action_lookup(&hdev->pend_le_conns,
-						      &b->bdaddr,
-						      b->bdaddr_type);
-		pend_report = hci_pend_le_action_lookup(&hdev->pend_le_reports,
-							&b->bdaddr,
-							b->bdaddr_type);
+						      &params[i].addr,
+						      params[i].addr_type);
+		pend_report = hci_pend_le_action_lookup(
+			&hdev->pend_le_reports, &params[i].addr,
+			params[i].addr_type);
 
 		rcu_read_unlock();
 
@@ -3022,14 +3053,16 @@ static u8 hci_update_accept_list_sync(struct hci_dev *hdev)
 		 * remove it from the acceptlist.
 		 */
 		if (!pend_conn && !pend_report) {
-			hci_le_del_accept_list_sync(hdev, &b->bdaddr,
-						    b->bdaddr_type);
+			hci_le_del_accept_list_sync(hdev, &params[i].addr,
+						    params[i].addr_type);
 			continue;
 		}
 
 		num_entries++;
 	}
 
+	kvfree(params);
+
 	/* Since all no longer valid accept list entries have been
 	 * removed, walk through the list of pending connections
 	 * and ensure that any new device gets programmed into
Signature · 1 line
2.53.0
author maintainer
#183 lore raw

PATCH 182/990 Bluetooth: hci_sync: Protect resolving-list lookups

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit f05bd61a3213613de7848c8df2865492d5225023 ]

The host resolving list is updated under hdev->lock, and each bdaddr_list_with_irk entry must remain alive throughout a lookup. hci_le_del_resolve_list_sync() and hci_le_add_resolve_list_sync() traverse that list without taking the lock.

On an LE privacy-capable controller with a programmed entry, passive scan reconciliation can reach hci_le_del_resolve_list_sync() while a privileged HCI_RAW client sends LE Clear Resolving List. The raw command does not take req_lock, and its successful completion runs on the controller workqueue independently of request work:

Request work Raw HCI / event work
hci_le_del_resolve_list_sync()
lookup loads a list node
hci_sock_sendmsg()
queue LE Clear Resolving List
hci_cc_le_clear_resolv_list()
take hdev->lock unlink and free the node release hdev->lock
read the node's address/type

The clear can free the node after the lookup loads it and before its address/type read, causing a use-after-free. The report below shows this access with the delete helper on the faulting stack. The add helper uses the same unprotected lookup.

Take hdev->lock around each resolving-list membership lookup and retain only a boolean result. This serializes traversal with clear completion and keeps entry pointers inside the protected section. Release the lock before issuing a synchronous HCI command, whose completion also needs the lock.

KASAN report as below:

    ==================================================================
    BUG: KASAN: slab-use-after-free in
    hci_bdaddr_list_lookup_with_irk+0x106/0x120
    Read of size 1 at addr ffff88810b036e16 by task kworker/u17:0/495

    CPU: 2 UID: 0 PID: 495 Comm: kworker/u17:0 Not tainted
    7.2.0-rc6-pmb-bt-functional-v1+ #3 PREEMPT(lazy)
    Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix,
    1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
    Workqueue: hci0 hci_cmd_sync_work
    Call Trace:
     <TASK>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     ? hci_bdaddr_list_lookup_with_irk+0x106/0x120
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __virt_addr_valid+0x20d/0x410
     ? hci_bdaddr_list_lookup_with_irk+0x106/0x120
     kasan_report+0xe0/0x110
     ? hci_bdaddr_list_lookup_with_irk+0x106/0x120
     hci_bdaddr_list_lookup_with_irk+0x106/0x120
     hci_le_del_resolve_list_sync.isra.0+0xd6/0x3f0
     ? __pfx_hci_le_del_resolve_list_sync.isra.0+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     hci_le_del_accept_list_sync.isra.0+0x11c/0x290
     ? __pfx_hci_le_del_accept_list_sync.isra.0+0x10/0x10
     ? hci_passive_scan_sync+0x551/0x1e80
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_release+0xc8/0x280
     hci_passive_scan_sync+0x71c/0x1e80
     ? __pfx_hci_passive_scan_sync+0x10/0x10
     ? find_held_lock+0x2b/0x80
     ? hci_lookup_le_connect+0xe1/0x3c0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? find_held_lock+0x2b/0x80
     ? hci_update_passive_scan_sync+0x437/0x950
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_release+0xc8/0x280
     hci_update_passive_scan_sync+0x461/0x950
     hci_cmd_sync_work+0x1b3/0x450
     ? srso_alias_return_thunk+0x5/0xfbef5
     process_one_work+0x908/0x19c0
     ? __pfx_process_one_work+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_is_held_type+0x8f/0x100
     ? srso_alias_return_thunk+0x5/0xfbef5
     worker_thread+0x65c/0xe40
     ? __pfx_worker_thread+0x10/0x10
     kthread+0x34f/0x460
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_kthread+0x10/0x10
     ret_from_fork+0x659/0x940
     ? __pfx_ret_from_fork+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __switch_to+0x74f/0xf80
     ? __pfx_kthread+0x10/0x10
     ret_from_fork_asm+0x1a/0x30
     </TASK>

    Allocated by task 495:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_kmalloc+0xaa/0xb0
     __kmalloc_cache_noprof+0x251/0x610
     hci_bdaddr_list_add_with_irk+0x183/0x3e0
     hci_cc_le_add_to_resolv_list+0x18c/0x240
     hci_cmd_complete_evt+0x373/0xab0
     hci_event_packet+0x4e8/0xc70
     hci_rx_work+0x367/0xf00
     process_one_work+0x908/0x19c0
     worker_thread+0x65c/0xe40
     kthread+0x34f/0x460
     ret_from_fork+0x659/0x940
     ret_from_fork_asm+0x1a/0x30

    Freed by task 497:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     kasan_save_free_info+0x3b/0x60
     __kasan_slab_free+0x5f/0x80
     kfree+0x307/0x580
     hci_bdaddr_list_clear+0x134/0x230
     hci_cc_le_clear_resolv_list+0x13d/0x240
     hci_cmd_complete_evt+0x373/0xab0
     hci_event_packet+0x4e8/0xc70
     hci_rx_work+0x367/0xf00
     process_one_work+0x908/0x19c0
     worker_thread+0x65c/0xe40
     kthread+0x34f/0x460
     ret_from_fork+0x659/0x940
     ret_from_fork_asm+0x1a/0x30

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

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

    Memory state around the buggy address:
     ffff88810b036d00: 00 00 00 00 00 00 00 00 fc fc fc fc fc fc fc fc
     ffff88810b036d80: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
    >ffff88810b036e00: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
                             ^
     ffff88810b036e80: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
     ffff88810b036f00: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
    ==================================================================
    Disabling lock debugging due to kernel taint
Fixes e8907f76544f ("Bluetooth: hci_sync: Make use of hci_cmd_sync_queue set 3")
Assisted-by LLM
---
 net/bluetooth/hci_sync.c | 21 ++++++++++++---------
 1 file changed, 12 insertions(+), 9 deletions(-)
net/bluetooth/hci_sync.c +12 -9
index 7403fff7d7855..9ba61c1bcd129 100644
@@ -2469,15 +2469,17 @@ static int hci_le_del_resolve_list_sync(struct hci_dev *hdev,
 					bdaddr_t *bdaddr, u8 bdaddr_type)
 {
 	struct hci_cp_le_del_from_resolv_list cp;
-	struct bdaddr_list_with_irk *entry;
+	bool exists;
 
 	if (!ll_privacy_capable(hdev))
 		return 0;
 
 	/* Check if the IRK has been programmed */
-	entry = hci_bdaddr_list_lookup_with_irk(&hdev->le_resolv_list, bdaddr,
-						bdaddr_type);
-	if (!entry)
+	hci_dev_lock(hdev);
+	exists = hci_bdaddr_list_lookup_with_irk(&hdev->le_resolv_list,
+						 bdaddr, bdaddr_type);
+	hci_dev_unlock(hdev);
+	if (!exists)
 		return 0;
 
 	cp.bdaddr_type = bdaddr_type;
@@ -2533,8 +2535,8 @@ static int hci_le_add_resolve_list_sync(struct hci_dev *hdev,
 {
 	struct hci_cp_le_add_to_resolv_list cp;
 	struct smp_irk *irk;
-	struct bdaddr_list_with_irk *entry;
 	struct hci_conn_params *p;
+	bool exists;
 
 	if (!ll_privacy_capable(hdev))
 		return 0;
@@ -2557,10 +2559,11 @@ static int hci_le_add_resolve_list_sync(struct hci_dev *hdev,
 		return 0;
 
 	/* Check if the IK has _not_ been programmed yet. */
-	entry = hci_bdaddr_list_lookup_with_irk(&hdev->le_resolv_list,
-						&params->addr,
-						params->addr_type);
-	if (entry)
+	hci_dev_lock(hdev);
+	exists = hci_bdaddr_list_lookup_with_irk(
+		&hdev->le_resolv_list, &params->addr, params->addr_type);
+	hci_dev_unlock(hdev);
+	if (exists)
 		return 0;
 
 	cp.bdaddr_type = params->addr_type;
Signature · 1 line
2.53.0
author maintainer
#184 lore raw

PATCH 183/990 Bluetooth: mgmt: reply to cancelled mgmt commands instead of silently dropping

In reply to Greg Kroah-Hartman

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

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

From: Shuai Zhang <[email protected]>

[ Upstream commit c0bb764fc082672678d371c375597a6a9f614cf9 ]

The kernel sets HCI_AUTO_OFF when a controller is first registered and starts a 2-second timer. On slower boots bluetoothd and the HCI_AUTO_OFF timer can race: hci_power_off() is already queued while bluetoothd is still in the middle of its adapter setup sequence. hci_cmd_sync_clear() then cancels any pending mgmt commands with -ECANCELED, including the MGMT_OP_REMOVE_ADV_MONITOR sent by reset_adv_monitors() early in the setup sequence.

When auto_off=1, hci_dev_close_sync() skips __mgmt_power_off() entirely, so there is no fallback path to reply to the cancelled commands. mgmt_remove_adv_monitor_complete() silently returns on -ECANCELED, leaving the command with no reply. Since bluez's mgmt queue is strictly serialised, this stalls all subsequent commands indefinitely, leaving bluetoothd unable to register the adapter.

Fix by mapping -ECANCELED to MGMT_STATUS_CANCELLED in mgmt_errno_status() and replying to the cancelled command in mgmt_remove_adv_monitor_complete() instead of returning early.

Stable-dep-of: 7eac80614300 ("Bluetooth: MGMT: Return RFKILLED for Set Powered on a blocked controller")

---
 net/bluetooth/mgmt.c | 14 +++++++++++++-
 1 file changed, 13 insertions(+), 1 deletion(-)
net/bluetooth/mgmt.c +13 -1
index 5058fa2ed9a9b..6e49f77c363f8 100644
@@ -304,6 +304,8 @@ static u8 mgmt_errno_status(int err)
 		return MGMT_STATUS_ALREADY_CONNECTED;
 	case -ENOTCONN:
 		return MGMT_STATUS_DISCONNECTED;
+	case -ECANCELED:
+		return MGMT_STATUS_CANCELLED;
 	}
 
 	return MGMT_STATUS_FAILED;
@@ -5614,8 +5616,18 @@ static void mgmt_remove_adv_monitor_complete(struct hci_dev *hdev,
 	struct mgmt_pending_cmd *cmd = data;
 	struct mgmt_cp_remove_adv_monitor *cp;
 
-	if (status == -ECANCELED)
+	/* Reply to a cancelled command so bluetoothd's serialised mgmt queue
+	 * is not blocked.
+	 */
+	if (status == -ECANCELED) {
+		cp = cmd->param;
+		rp.monitor_handle = cp->monitor_handle;
+
+		mgmt_cmd_complete(cmd->sk, cmd->hdev->id, cmd->opcode,
+				  mgmt_status(status), &rp, sizeof(rp));
+		mgmt_pending_free(cmd);
 		return;
+	}
 
 	hci_dev_lock(hdev);
 
Signature · 1 line
2.53.0
author maintainer
#185 lore raw

PATCH 184/990 Bluetooth: MGMT: Return RFKILLED for Set Powered on a blocked controller

In reply to Greg Kroah-Hartman

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

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

From: Tobias Wilken <[email protected]>

[ Upstream commit 7eac80614300563470cffabf4df2b63616787ee7 ]

Since MGMT_OP_SET_POWERED runs through hci_cmd_sync, powering on a controller that is blocked by rfkill fails with -ERFKILL from hci_dev_open_sync(), and mgmt_set_powered_complete() reports it with mgmt_status(err). mgmt_errno_status() has no case for -ERFKILL, so userspace gets MGMT_STATUS_FAILED instead of MGMT_STATUS_RFKILLED.

Before that conversion, power on went through hci_power_on(), whose error path mgmt_set_powered_failed() still maps -ERFKILL to MGMT_STATUS_RFKILLED. bluetoothd relies on that status: for RFKILLED it sets the adapter PowerState to "off-blocked" and returns org.bluez.Error.Blocked for the Powered property, for any other status it returns org.bluez.Error.Failed.

With the controller soft blocked, "bluetoothctl power on" printed "Failed to set power on: org.bluez.Error.Failed" and btmon showed "Set Powered (0x0005) Status: Failed (0x03)". With this change it prints org.bluez.Error.Blocked and btmon shows "Status: RFKilled (0x12)".

Map -ERFKILL to MGMT_STATUS_RFKILLED in mgmt_errno_status().

Fixes cf75ad8b41d2 ("Bluetooth: hci_sync: Convert MGMT_SET_POWERED")
Assisted-by LLM
---
 net/bluetooth/mgmt.c | 2 ++
 1 file changed, 2 insertions(+)
net/bluetooth/mgmt.c +2 -0
index 6e49f77c363f8..484243146f10e 100644
@@ -306,6 +306,8 @@ static u8 mgmt_errno_status(int err)
 		return MGMT_STATUS_DISCONNECTED;
 	case -ECANCELED:
 		return MGMT_STATUS_CANCELLED;
+	case -ERFKILL:
+		return MGMT_STATUS_RFKILLED;
 	}
 
 	return MGMT_STATUS_FAILED;
Signature · 1 line
2.53.0
author maintainer
#186 lore raw

PATCH 185/990 Bluetooth: btmtk: fix error handling in btmtk_usb_isointf_init()

In reply to Greg Kroah-Hartman

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

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

From: Ismail Tarim <[email protected]>

[ Upstream commit 3b70dd827b27bfadd89e7b1a2d422b04da38797c ]

btmtk_usb_isointf_init() submits the ISO interrupt IN URB and then sends the vendor command 0xfd98. If that command fails, the function returns an error without killing the URB it has just submitted. The caller then leaves BTMTK_ISOPKT_RUNNING clear, so the driver treats the ISO path as inactive while its RX URB is still in flight, and btmtk_usb_suspend() skips killing it. Kill the anchored URBs on this path, as the URB submission failure path already does.

The return value of __set_mtk_intr_interface() is also ignored: a failure to select the ISO alternate setting or to find its endpoints is logged, but the function goes on to submit the URB. Return the error instead.

Fixes ceac1cb0259d ("Bluetooth: btusb: mediatek: add ISO data transmission functions")
---
 drivers/bluetooth/btmtk.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/bluetooth/btmtk.c +4 -1
index 5863b63f5d3f0..50e0ff30e8db2 100644
@@ -1358,7 +1358,9 @@ static int btmtk_usb_isointf_init(struct hci_dev *hdev)
 
 	spin_lock_init(&btmtk_data->isorxlock);
 
-	__set_mtk_intr_interface(hdev);
+	err = __set_mtk_intr_interface(hdev);
+	if (err < 0)
+		return err;
 
 	err = btmtk_submit_intr_urb(hdev, GFP_KERNEL);
 	if (err < 0) {
@@ -1370,6 +1372,7 @@ static int btmtk_usb_isointf_init(struct hci_dev *hdev)
 	skb = __hci_cmd_sync(hdev, 0xfd98, sizeof(iso_param), &iso_param,
 			     HCI_INIT_TIMEOUT);
 	if (IS_ERR(skb)) {
+		usb_kill_anchored_urbs(&btmtk_data->isopkt_anchor);
 		bt_dev_err(hdev, "Failed to apply iso setting (%ld)", PTR_ERR(skb));
 		return PTR_ERR(skb);
 	}
Signature · 1 line
2.53.0
author maintainer
#187 lore raw

PATCH 186/990 Bluetooth: hci_core: Keep link-key filtering inside RCU

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit 281ddc4e01ab54cab07995f2a1b72cf81bf90eb5 ]

hci_find_link_key() must keep the matching link key allocated while it checks the key against the blocked-key list. It currently leaves the key-list RCU read-side section before passing k->val to hci_is_blocked_key(). That helper's own RCU section protects the blocked-key list, but it cannot keep an unlinked link key from being reclaimed.

The SMP receive path calls the finder without hdev->lock: Secure Connections key distribution over BR/EDR reaches it through smp_distribute_keys() and sc_generate_ltk(). With a stored peer link key and a link-key entry in the blocked-key list, MGMT_OP_LOAD_LINK_KEYS can free the selected key before the comparison:

HCI RX worker (SMP) Management / RCU reclamation
hci_find_link_key()

    rcu_read_lock()
    select k
    rcu_read_unlock()
                                   load_link_keys()
                                     hci_dev_lock(hdev)
                                     hci_link_keys_clear(hdev)
                                       list_del_rcu(), kfree_rcu()
                                     hci_dev_unlock(hdev)
                                   grace period ends, k is freed
    hci_is_blocked_key(hdev, ..., k->val)
      memcmp() reads the freed key

Keep the RCU read-side section active through the blocked-key comparison and the warning that prints k->bdaddr, and release it before returning on both matched-key paths. hci_find_ltk() already handles its blocked-key check this way.

KASAN reported this on a test kernel whose scheduling hook paused the receive worker after the lookup until the key had been freed.

KASAN report as below:

    ==================================================================
    BUG: KASAN: slab-use-after-free in hci_is_blocked_key+0x2db/0x300
    Read of size 1 at addr ffff88810b5f89a7 by task kworker/u17:0/502

    CPU: 1 UID: 0 PID: 502 Comm: kworker/u17:0 Not tainted 7.2.0-rc6-pmb-bt-functional-v1+ #5 PREEMPT(lazy)
    Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
    Workqueue: hci1 hci_rx_work
    Call Trace:
     <TASK>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     ? hci_is_blocked_key+0x2db/0x300
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __virt_addr_valid+0x20d/0x410
     ? hci_is_blocked_key+0x2db/0x300
     kasan_report+0xe0/0x110
     ? hci_is_blocked_key+0x2db/0x300
     hci_is_blocked_key+0x2db/0x300
     hci_find_link_key+0x12e/0x400
     smp_distribute_keys+0x1830/0x2950
     ? trace_hardirqs_on+0x18/0x160
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? queue_delayed_work_on+0xb3/0xf0
     ? __pfx_smp_distribute_keys+0x10/0x10
     ? __pfx_smp_send_cmd.isra.0+0x10/0x10
     ? __cancel_work+0x1b0/0x290
     ? __entry_text_end+0x1020f7/0x1020f9
     ? lockdep_hardirqs_on_prepare+0xea/0x1a0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __asan_memset+0x23/0x50
     ? smp_recv_cb+0x12c7/0x8d80
     ? srso_alias_return_thunk+0x5/0xfbef5
     smp_recv_cb+0x12c7/0x8d80
     ? __pfx_smp_recv_cb+0x10/0x10
     ? __pfx___might_resched+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? stack_depot_save_flags+0x29/0x9a0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __mutex_lock+0x182c/0x2590
     ? kasan_save_stack+0x42/0x60
     ? l2cap_recv_frame+0x9ef/0x8830
     ? __kasan_slab_free+0x5f/0x80
     ? kmem_cache_free+0x242/0x580
     ? kfree_skbmem+0x15e/0x1d0
     ? sk_skb_reason_drop+0x12f/0x490
     ? hci_event_packet+0x556/0xc70
     ? hci_rx_work+0x367/0xf00
     ? process_one_work+0x908/0x19c0
     ? worker_thread+0x65c/0xe40
     ? __pfx___mutex_lock+0x10/0x10
     ? __lock_acquire+0x466/0x2260
     ? __pfx_l2cap_chan_hold_unless_zero+0x10/0x10
     ? l2cap_recv_frame+0x13cc/0x8830
     ? __pfx_smp_recv_cb+0x10/0x10
     l2cap_recv_frame+0x13cc/0x8830
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __mutex_lock+0x182c/0x2590
     ? __pfx_l2cap_recv_frame+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? find_held_lock+0x2b/0x80
     ? l2cap_recv_acldata+0x1eb/0x10e0
     ? __pfx___mutex_lock+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __mutex_unlock_slowpath+0x147/0x920
     ? __pfx_l2cap_conn_hold_unless_zero+0x10/0x10
     ? __pfx_hci_conn_enter_active_mode+0x10/0x10
     ? l2cap_recv_acldata+0x13d/0x10e0
     ? srso_alias_return_thunk+0x5/0xfbef5
     l2cap_recv_acldata+0xe9f/0x10e0
     ? srso_alias_return_thunk+0x5/0xfbef5
     hci_rx_work+0x5a6/0xf00
     ? srso_alias_return_thunk+0x5/0xfbef5
     process_one_work+0x908/0x19c0
     ? __pfx_process_one_work+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_is_held_type+0x8f/0x100
     ? srso_alias_return_thunk+0x5/0xfbef5
     worker_thread+0x65c/0xe40
     ? __pfx_worker_thread+0x10/0x10
     kthread+0x34f/0x460
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_kthread+0x10/0x10
     ret_from_fork+0x659/0x940
     ? __pfx_ret_from_fork+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __switch_to+0x74f/0xf80
     ? __pfx_kthread+0x10/0x10
     ret_from_fork_asm+0x1a/0x30
     </TASK>

    Allocated by task 504:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_kmalloc+0xaa/0xb0
     __kmalloc_cache_noprof+0x251/0x610
     hci_add_link_key+0x474/0x840
     hci_link_key_notify_evt+0x492/0xce0
     hci_event_packet+0x894/0xc70
     hci_rx_work+0x367/0xf00
     process_one_work+0x908/0x19c0
     worker_thread+0x65c/0xe40
     kthread+0x34f/0x460
     ret_from_fork+0x659/0x940
     ret_from_fork_asm+0x1a/0x30

    Freed by task 29:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     kasan_save_free_info+0x3b/0x60
     __kasan_slab_free+0x5f/0x80
     __rcu_free_sheaf_prepare+0x65/0x2a0
     rcu_free_sheaf_nobarn+0x1d/0x50
     rcu_core+0x661/0x1d10
     handle_softirqs+0x201/0x930
     run_ksoftirqd+0x33/0x60
     smpboot_thread_fn+0x3bd/0x9a0
     kthread+0x34f/0x460
     ret_from_fork+0x659/0x940
     ret_from_fork_asm+0x1a/0x30

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

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

    Memory state around the buggy address:
     ffff88810b5f8880: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
     ffff88810b5f8900: 00 00 00 00 00 00 00 fc fc fc fc fc fc fc fc fc
    >ffff88810b5f8980: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
                                   ^
     ffff88810b5f8a00: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
     ffff88810b5f8a80: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
    ==================================================================
Fixes 600a87490ff9 ("Bluetooth: Implementation of MGMT_OP_SET_BLOCKED_KEYS.")
Assisted-by LLM
---
 net/bluetooth/hci_core.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
net/bluetooth/hci_core.c +2 -3
index e4caf79c2d7c3..c9b8fa9a2e88a 100644
@@ -1111,17 +1111,16 @@ struct link_key *hci_find_link_key(struct hci_dev *hdev, bdaddr_t *bdaddr)
 	rcu_read_lock();
 	list_for_each_entry_rcu(k, &hdev->link_keys, list) {
 		if (bacmp(bdaddr, &k->bdaddr) == 0) {
-			rcu_read_unlock();
-
 			if (hci_is_blocked_key(hdev,
 					       HCI_BLOCKED_KEY_TYPE_LINKKEY,
 					       k->val)) {
 				bt_dev_warn_ratelimited(hdev,
 							"Link key blocked for %pMR",
 							&k->bdaddr);
-				return NULL;
+				k = NULL;
 			}
 
+			rcu_read_unlock();
 			return k;
 		}
 	}
Signature · 1 line
2.53.0
author maintainer
#188 lore raw

PATCH 187/990 Bluetooth: hci_sync: Copy the resolving-list IRK under RCU

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit 9ff737119177a6c1ce6083ef8c0fc06355f11869 ]

hci_le_add_resolve_list_sync() copies the peer IRK into the LE Add Device To Resolving List command after hci_find_irk_by_addr() has returned. The finder ends its RCU read-side section before returning the borrowed entry, and neither the request worker nor interleave_scan_work() holds hdev->lock here. The resolving-list membership check between the lookup and the copy takes hdev->lock and may sleep on it, which widens the window.

When LL privacy programs a peer with address resolution enabled, MGMT_OP_LOAD_IRKS can free its IRK before the copy:

Request worker Management / RCU reclamation
hci_le_add_resolve_list_sync()
irk = hci_find_irk_by_addr()
load_irks()
hci_dev_lock(hdev) hci_smp_irks_clear(hdev)
list_del_rcu(), kfree_rcu()
hci_dev_unlock(hdev)
grace period ends, irk is freed
resolving-list membership check
memcpy(cp.peer_irk, irk->val, 16)

Copy the IRK value in an RCU read-side section right after the lookup, as hci_le_set_privacy_mode_sync() does for the identity address. The section ends before hdev->lock is taken and before the synchronous HCI command is sent.

KASAN reported this on a test kernel with scheduling hooks, whose frames appear in the trace. The report predates the hdev->lock taken by the membership check.

KASAN report as below:

    ==================================================================
    BUG: KASAN: slab-use-after-free in hci_le_add_resolve_list_sync+0x8d9/0x910
    Read of size 16 at addr ffff88810d21452d by task kworker/u17:0/504

    CPU: 2 UID: 0 PID: 504 Comm: kworker/u17:0 Not tainted 7.2.0-rc6-pmb-bt-functional-v1+ #2 PREEMPT(lazy)
    Hardware name: QEMU Ubuntu 24.04 PC v2 (i440FX + PIIX, arch_caps fix, 1996), BIOS 1.16.3-debian-1.16.3-2 04/01/2014
    Workqueue: hci0 interleave_scan_work
    Call Trace:
     <TASK>
     dump_stack_lvl+0x93/0xd0
     print_report+0xce/0x630
     ? hci_le_add_resolve_list_sync+0x8d9/0x910
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __virt_addr_valid+0x20d/0x410
     ? hci_le_add_resolve_list_sync+0x8d9/0x910
     kasan_report+0xe0/0x110
     ? hci_le_add_resolve_list_sync+0x8d9/0x910
     hci_le_add_resolve_list_sync+0x8d9/0x910
     ? __pfx_hci_le_add_resolve_list_sync+0x10/0x10
     ? pmbd_probe_hit_cookie+0xe7/0x1c0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? pmbd_probe_hit_cookie+0xee/0x1c0
     ? __pfx_pmbd_probe_hit_cookie+0x10/0x10
     hci_le_add_accept_list_sync+0x18e/0x820
     ? conn_params_copy+0x36e/0x650
     ? __pfx_hci_le_add_accept_list_sync+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? conn_params_copy+0x3a0/0x650
     hci_passive_scan_sync+0x95f/0x1f10
     ? __pfx_hci_passive_scan_sync+0x10/0x10
     ? debug_object_deactivate+0x2f8/0x3c0
     ? pwq_dec_nr_in_flight+0x880/0xdf0
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_acquire+0x17b/0x2f0
     ? process_one_work+0x895/0x19c0
     interleave_scan_work+0x11b/0x470
     process_one_work+0x908/0x19c0
     ? __pfx_process_one_work+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? lock_is_held_type+0x8f/0x100
     ? srso_alias_return_thunk+0x5/0xfbef5
     worker_thread+0x65c/0xe40
     ? __pfx_worker_thread+0x10/0x10
     kthread+0x34f/0x460
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __pfx_kthread+0x10/0x10
     ret_from_fork+0x659/0x940
     ? __pfx_ret_from_fork+0x10/0x10
     ? srso_alias_return_thunk+0x5/0xfbef5
     ? __switch_to+0x74f/0xf80
     ? __pfx_kthread+0x10/0x10
     ret_from_fork_asm+0x1a/0x30
     </TASK>

    Allocated by task 535:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     __kasan_kmalloc+0xaa/0xb0
     __kmalloc_cache_noprof+0x251/0x610
     hci_add_irk+0xb6/0x220
     load_irks+0x5f9/0x840
     hci_sock_sendmsg+0x128b/0x22e0
     __sys_sendto+0x425/0x470
     __x64_sys_sendto+0xe5/0x1c0
     do_syscall_64+0x115/0x6a0
     entry_SYSCALL_64_after_hwframe+0x77/0x7f

    Freed by task 0:
     kasan_save_stack+0x33/0x60
     kasan_save_track+0x14/0x30
     kasan_save_free_info+0x3b/0x60
     __kasan_slab_free+0x5f/0x80
     __rcu_free_sheaf_prepare+0x65/0x2a0
     rcu_free_sheaf+0x1f/0xe0
     rcu_core+0x661/0x1d10
     handle_softirqs+0x201/0x930
     __irq_exit_rcu+0x110/0x1e0
     irq_exit_rcu+0xe/0x20
     sysvec_apic_timer_interrupt+0x6c/0x80
     asm_sysvec_apic_timer_interrupt+0x1a/0x20

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

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

    Memory state around the buggy address:
     ffff88810d214400: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
     ffff88810d214480: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
    >ffff88810d214500: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
                                      ^
     ffff88810d214580: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
     ffff88810d214600: fa fb fb fb fb fb fb fb fc fc fc fc fc fc fc fc
    ==================================================================
Fixes e8907f76544f ("Bluetooth: hci_sync: Make use of hci_cmd_sync_queue set 3")
Assisted-by LLM
---
 net/bluetooth/hci_sync.c | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
net/bluetooth/hci_sync.c +9 -2
index 9ba61c1bcd129..e5f29558f1468 100644
@@ -2554,9 +2554,17 @@ static int hci_le_add_resolve_list_sync(struct hci_dev *hdev,
 	} else if (!(params->flags & HCI_CONN_FLAG_ADDRESS_RESOLUTION))
 		return 0;
 
+	rcu_read_lock();
+
 	irk = hci_find_irk_by_addr(hdev, &params->addr, params->addr_type);
-	if (!irk)
+	if (!irk) {
+		rcu_read_unlock();
 		return 0;
+	}
+
+	memcpy(cp.peer_irk, irk->val, 16);
+
+	rcu_read_unlock();
 
 	/* Check if the IK has _not_ been programmed yet. */
 	hci_dev_lock(hdev);
@@ -2568,7 +2576,6 @@ static int hci_le_add_resolve_list_sync(struct hci_dev *hdev,
 
 	cp.bdaddr_type = params->addr_type;
 	bacpy(&cp.bdaddr, &params->addr);
-	memcpy(cp.peer_irk, irk->val, 16);
 
 	/* Default privacy mode is always Network */
 	params->privacy_mode = HCI_NETWORK_PRIVACY;
Signature · 1 line
2.53.0
author maintainer
#162 lore raw

PATCH 161/990 vduse: avoid infinite loop when no affinity CPU is online

In reply to Greg Kroah-Hartman

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

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

From: Jia Jia <[email protected]>

[ Upstream commit cf0a5805d43236e308f14188f9737ddcf83fb53a ]

If all CPUs in vq->irq_affinity are offline, cpumask_next() walks to the end of the mask, and the loop then resets the cursor to IRQ_UNBOUND and restarts the scan. When VDUSE_VQ_INJECT_IRQ is issued, the intersection of vq->irq_affinity and cpu_online_mask is empty, so the caller busy-loops in kernel context on its current CPU (e.g. CPU2).

Replace the while loop in vduse_vq_update_effective_cpu() with cpumask_next_and_wrap() to find the intersection of vq->irq_affinity and cpu_online_mask in a single wrapped scan. If the intersection is empty, set curr_cpu to IRQ_UNBOUND and let the existing unbound workqueue handle injection, avoiding repeated rescans when all CPUs in the affinity are offline. Use cpus_read_lock()/cpus_read_unlock() to keep the selected CPU online.

Fixes 28f6288eb63d ("vduse: Support set_vq_affinity callback")

Message-ID: <[email protected]>

---
 drivers/vdpa/vdpa_user/vduse_dev.c | 15 +++++++--------
 1 file changed, 7 insertions(+), 8 deletions(-)
drivers/vdpa/vdpa_user/vduse_dev.c +7 -8
index f9547ede71be7..d68858acc5d9c 100644
@@ -13,6 +13,7 @@
 #include <linux/module.h>
 #include <linux/cdev.h>
 #include <linux/device.h>
+#include <linux/cpu.h>
 #include <linux/eventfd.h>
 #include <linux/slab.h>
 #include <linux/wait.h>
@@ -1239,14 +1240,10 @@ static void vduse_vq_update_effective_cpu(struct vduse_virtqueue *vq)
 {
 	int curr_cpu = vq->irq_effective_cpu;
 
-	while (true) {
-		curr_cpu = cpumask_next(curr_cpu, &vq->irq_affinity);
-		if (cpu_online(curr_cpu))
-			break;
-
-		if (curr_cpu >= nr_cpu_ids)
-			curr_cpu = IRQ_UNBOUND;
-	}
+	curr_cpu = cpumask_next_and_wrap(curr_cpu, &vq->irq_affinity,
+					 cpu_online_mask);
+	if (curr_cpu >= nr_cpu_ids)
+		curr_cpu = IRQ_UNBOUND;
 
 	vq->irq_effective_cpu = curr_cpu;
 }
@@ -1427,10 +1424,12 @@ static long vduse_dev_ioctl(struct file *file, unsigned int cmd,
 		ret = 0;
 		index = array_index_nospec(index, dev->vq_num);
 		if (!vduse_vq_signal_irqfd(dev->vqs[index])) {
+			cpus_read_lock();
 			vduse_vq_update_effective_cpu(dev->vqs[index]);
 			ret = vduse_dev_queue_irq_work(dev,
 						&dev->vqs[index]->inject,
 						dev->vqs[index]->irq_effective_cpu);
+			cpus_read_unlock();
 		}
 		break;
 	}
Signature · 1 line
2.53.0
author maintainer
#189 lore raw

PATCH 188/990 Bluetooth: MGMT: Clear disabled connection parameters when loading none

In reply to Greg Kroah-Hartman

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

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

From: Kevin Dewald <[email protected]>

[ Upstream commit d90f24dc389b9a7524aaac109021d1530fa180f0 ]

Load Connection Parameters only clears the disabled connection parameters when it loads more than one entry, so that loading a single entry can update the parameters of one device without dropping the others. Loading no entries does not clear them either, though, which is what bluetoothd does when it starts without stored connection parameters.

Pair Device adds disabled connection parameters for the device it pairs with, so these now survive bluetoothd restarts, and new connections to the device keep using the parameters they were created with instead of the defaults set since, e.g. the connection interval from main.conf.

Clear the disabled connection parameters unless a single entry is loaded, as was done for any number of entries before.

Fixes 0ece498c27d8 ("Bluetooth: MGMT: Make MGMT_OP_LOAD_CONN_PARAM update existing connection")
Assisted-by Claude:claude-opus-5.5
---
 net/bluetooth/mgmt.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
net/bluetooth/mgmt.c +5 -1
index 484243146f10e..8d18e94fe8c05 100644
@@ -8165,7 +8165,11 @@ static int load_conn_param(struct sock *sk, struct hci_dev *hdev, void *data,
 
 	hci_dev_lock(hdev);
 
-	if (param_count > 1)
+	/* A single entry may be an update for one device, so keep the other
+	 * disabled parameters then, but clear them otherwise, including when
+	 * no entries are loaded.
+	 */
+	if (param_count != 1)
 		hci_conn_params_clear_disabled(hdev);
 
 	for (i = 0; i < param_count; i++) {
Signature · 1 line
2.53.0
author maintainer
#190 lore raw

PATCH 189/990 Bluetooth: hci_core: Initialize advertising RPA work only once

In reply to Greg Kroah-Hartman

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

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

From: Cen Zhang <[email protected]>

[ Upstream commit a7c5c18b7cc30dcd2a9ae5a0fb38378d3998417e ]

hci_add_adv_instance() also updates existing instances and calls INIT_DELAYED_WORK() on their rpa_expired_cb every time, even when the work is pending or running. cancel_delayed_work_sync() then no longer finds the work, so hci_remove_adv_instance() can free the instance under it:

hdev->workqueue MGMT_OP_ADD_EXT_ADV_PARAMS
adv_instance_rpa_expired()
hci_dev_lock(hdev) hci_add_adv_instance()
INIT_DELAYED_WORK()
mgmt_pending_new() fails hci_remove_adv_instance()
cancel_delayed_work_sync()
returns without waiting
kfree(adv)
hci_dev_unlock(hdev)
adv->rpa_expired = true

The work has been initialized on every update since it was added. Initialize it only when the instance is allocated.

KASAN report as below:

    BUG: KASAN: slab-use-after-free in adv_instance_rpa_expired+0x139/0x160
    Write of size 1 at addr ffff888108d84b2e by task kworker/u17:0/504

    Workqueue: hci0 adv_instance_rpa_expired
    Call Trace:
     adv_instance_rpa_expired+0x139/0x160

    Allocated by task 560:
     hci_add_adv_instance+0x68d/0x9d0
     add_ext_adv_params+0x4d4/0xb60
     hci_sock_sendmsg+0x128b/0x22e0

    Freed by task 594:
     kfree+0x307/0x580
     hci_remove_adv_instance+0x230/0x540
     add_ext_adv_params+0xa43/0xb60
     hci_sock_sendmsg+0x128b/0x22e0

    Last potentially related work creation:
     insert_work+0x37/0x210
     __queue_work+0xaba/0x1270
     call_timer_fn+0x171/0x500

    The buggy address belongs to the object at ffff888108d84800
     which belongs to the cache kmalloc-1k of size 1024
    The buggy address is located 814 bytes inside of
     freed 1024-byte region [ffff888108d84800, ffff888108d84c00)
Fixes a73c046a2869 ("Bluetooth: Implement Set ADV set random address")
---
 net/bluetooth/hci_core.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
net/bluetooth/hci_core.c +3 -2
index c9b8fa9a2e88a..c19a9fa19e7d3 100644
@@ -1736,6 +1736,9 @@ struct adv_info *hci_add_adv_instance(struct hci_dev *hdev, u8 instance,
 		if (!adv)
 			return ERR_PTR(-ENOMEM);
 
+		INIT_DELAYED_WORK(&adv->rpa_expired_cb,
+				  adv_instance_rpa_expired);
+
 		adv->pending = true;
 		adv->instance = instance;
 
@@ -1772,8 +1775,6 @@ struct adv_info *hci_add_adv_instance(struct hci_dev *hdev, u8 instance,
 	else
 		adv->duration = duration;
 
-	INIT_DELAYED_WORK(&adv->rpa_expired_cb, adv_instance_rpa_expired);
-
 	BT_DBG("%s for %dMR", hdev->name, instance);
 
 	return adv;
Signature · 1 line
2.53.0
author maintainer
#191 lore raw

PATCH 190/990 Bluetooth: validate retained LE Create CIS command length

In reply to Greg Kroah-Hartman

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

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

From: Yifan Zhang <[email protected]>

[ Upstream commit 1eb52f35fc8fb06ab7f2973fff29cba81f96b947 ]

hci_cs_le_create_cis() retrieves the parameters of the previously sent command without their length. It then trusts num_cis and walks the flexible cis[] array when a controller reports a failed command.

A five-byte HCI command containing only num_cis can therefore make the handler read beyond the command skb. KASAN reports:

  BUG: KASAN: slab-out-of-bounds in hci_cs_le_create_cis
  Read of size 2
  hci_cs_le_create_cis
  hci_cmd_status_evt
  hci_event_packet

Add a length-returning saved-command helper and require the fixed header and complete CIS array before walking it.

The reproducer no longer triggers a KASAN report with this change.

Fixes 26afbd826ee3 ("Bluetooth: Add initial implementation of CIS connections")
---
 include/net/bluetooth/hci_core.h |  2 ++
 net/bluetooth/hci_core.c         | 18 ++++++++++++++----
 net/bluetooth/hci_event.c        |  7 ++++++-
 3 files changed, 22 insertions(+), 5 deletions(-)
include/net/bluetooth/hci_core.h +2 -0
index c416f7f2af6aa..37b3dc2b4c945 100644
@@ -2330,6 +2330,8 @@ void hci_send_sco(struct hci_conn *conn, struct sk_buff *skb);
 void hci_send_iso(struct hci_conn *conn, struct sk_buff *skb);
 
 void *hci_sent_cmd_data(struct hci_dev *hdev, __u16 opcode);
+void *hci_sent_cmd_data_len(struct hci_dev *hdev, __u16 opcode,
+			    size_t *len);
 void *hci_recv_event_data(struct hci_dev *hdev, __u8 event);
 
 u32 hci_conn_get_phy(struct hci_conn *conn);
net/bluetooth/hci_core.c +14 -4
index c19a9fa19e7d3..54a8942a022ec 100644
@@ -3175,7 +3175,8 @@ int __hci_cmd_send(struct hci_dev *hdev, u16 opcode, u32 plen,
 EXPORT_SYMBOL(__hci_cmd_send);
 
 /* Get data from the previously sent command */
-static void *hci_cmd_data(struct sk_buff *skb, __u16 opcode)
+static void *hci_cmd_data(struct sk_buff *skb, __u16 opcode,
+			  size_t *len)
 {
 	struct hci_command_hdr *hdr;
 
@@ -3187,23 +3188,32 @@ static void *hci_cmd_data(struct sk_buff *skb, __u16 opcode)
 	if (hdr->opcode != cpu_to_le16(opcode))
 		return NULL;
 
+	if (len)
+		*len = skb->len - HCI_COMMAND_HDR_SIZE;
+
 	return skb->data + HCI_COMMAND_HDR_SIZE;
 }
 
 /* Get data from the previously sent command */
-void *hci_sent_cmd_data(struct hci_dev *hdev, __u16 opcode)
+void *hci_sent_cmd_data_len(struct hci_dev *hdev, __u16 opcode, size_t *len)
 {
 	void *data;
 
 	/* Check if opcode matches last sent command */
-	data = hci_cmd_data(hdev->sent_cmd, opcode);
+	data = hci_cmd_data(hdev->sent_cmd, opcode, len);
 	if (!data)
 		/* Check if opcode matches last request */
-		data = hci_cmd_data(hdev->req_skb, opcode);
+		data = hci_cmd_data(hdev->req_skb, opcode, len);
 
 	return data;
 }
 
+/* Get data from the previously sent command */
+void *hci_sent_cmd_data(struct hci_dev *hdev, __u16 opcode)
+{
+	return hci_sent_cmd_data_len(hdev, opcode, NULL);
+}
+
 /* Get data from last received event */
 void *hci_recv_event_data(struct hci_dev *hdev, __u8 event)
 {
net/bluetooth/hci_event.c +6 -1
index 4be09dd9d9597..1897663dfbdb2 100644
@@ -4303,6 +4303,7 @@ static void hci_cs_le_create_cis(struct hci_dev *hdev, u8 status)
 {
 	struct hci_cp_le_create_cis *cp;
 	bool pending = false;
+	size_t len;
 	int i;
 
 	bt_dev_dbg(hdev, "status 0x%2.2x", status);
@@ -4310,10 +4311,14 @@ static void hci_cs_le_create_cis(struct hci_dev *hdev, u8 status)
 	if (!status)
 		return;
 
-	cp = hci_sent_cmd_data(hdev, HCI_OP_LE_CREATE_CIS);
+	cp = hci_sent_cmd_data_len(hdev, HCI_OP_LE_CREATE_CIS, &len);
 	if (!cp)
 		return;
 
+	if (len < sizeof(*cp) ||
+	    len < struct_size(cp, cis, cp->num_cis))
+		return;
+
 	hci_dev_lock(hdev);
 
 	/* Remove connection if command failed */
Signature · 1 line
2.53.0
author maintainer
#192 lore raw

PATCH 191/990 Bluetooth: validate retained LE Set CIG Parameters command length

In reply to Greg Kroah-Hartman

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

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

From: Yifan Zhang <[email protected]>

[ Upstream commit ed4d302af778b9e2ead28134a2196c09a4ad248a ]

hci_cc_le_set_cig_params() validates the controller response but not the parameters of the previously sent command. A short command can claim a large num_cis without containing the corresponding cis[] array. A complete successful response then makes the handler read beyond the command skb while looking up each CIS ID.

KASAN reports:

  BUG: KASAN: slab-out-of-bounds in hci_cc_le_set_cig_params
  Read of size 1
  hci_cc_le_set_cig_params
  hci_cmd_complete_evt
  hci_event_packet

Obtain the retained parameter length and require both the fixed header and the complete CIS array before using the command data.

The reproducer no longer triggers a KASAN report with this change.

Fixes 71e9588435c3 ("Bluetooth: ISO: use correct CIS order in Set CIG Parameters event")
---
 net/bluetooth/hci_event.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)
net/bluetooth/hci_event.c +5 -2
index 1897663dfbdb2..af7f1de7d657d 100644
@@ -3853,13 +3853,16 @@ static u8 hci_cc_le_set_cig_params(struct hci_dev *hdev, void *data,
 	struct hci_conn *conn;
 	u8 status = rp->status;
 	bool pending = false;
+	size_t len;
 	int i;
 
 	bt_dev_dbg(hdev, "status 0x%2.2x", rp->status);
 
-	cp = hci_sent_cmd_data(hdev, HCI_OP_LE_SET_CIG_PARAMS);
+	cp = hci_sent_cmd_data_len(hdev, HCI_OP_LE_SET_CIG_PARAMS, &len);
 	if (!rp->status &&
-	    (!cp || rp->num_handles != cp->num_cis ||
+	    (!cp || len < sizeof(*cp) ||
+	     len < struct_size(cp, cis, cp->num_cis) ||
+	     rp->num_handles != cp->num_cis ||
 	     rp->cig_id != cp->cig_id ||
 	     skb->len < array_size(rp->num_handles, sizeof(*rp->handle)))) {
 		bt_dev_err(hdev, "unexpected Set CIG Parameters response data");
Signature · 1 line
2.53.0
author maintainer
#193 lore raw

PATCH 192/990 Bluetooth: MGMT: Fix discovery stuck after a failed Stop Discovery

In reply to Greg Kroah-Hartman

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

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

From: Kevin Dewald <[email protected]>

[ Upstream commit 60b10121db602a43ada3dbc39792bbf93d25991b ]

Stop Discovery moves the discovery to DISCOVERY_STOPPING, and stop_discovery_complete() only moves it on to DISCOVERY_STOPPED when stopping succeeded. When it fails, for example because LE Set Scan Enable times out, nothing moves the discovery out of
DISCOVERY_STOPPING: Stop Discovery is rejected, as the discovery is not active anymore, and the LE scan timeout was cancelled before the scan was disabled. Until the controller is powered off, every Start Discovery then fails with Busy, and hci_update_passive_scan_sync() skips background scanning, so devices set to auto-connect are not connected anymore.

Move the discovery back to DISCOVERY_FINDING when stopping it failed while its inquiry or active LE scan is still running, so that it can be stopped again. Only change the state while the discovery is still stopping, as Inquiry Cancel may already have stopped it, for example when only the passive scan could not be disabled, and a new Start Discovery may have followed. Do this under hci_dev_lock(), like the command completions that change these flags, and before replying, so that a client acting on the reply sees the new state. Only cancel the LE scan timeout once the scan is disabled, so that the discovery still ends on its own, except when suspending, where it is still cancelled first.

A timed out LE Set Scan Enable can still complete afterwards, which cancels the timeout as well, so also stop the discovery when its scan is disabled while the timeout is pending, or while the timeout work waits for the lock.

Fixes 0e05bba6f6f8 ("Bluetooth: Update stop_discovery to use HCI request")
Assisted-by Claude:claude-opus-5.5
---
 net/bluetooth/hci_event.c | 12 +++++++++++-
 net/bluetooth/hci_sync.c  | 26 +++++++++++++++++++++++---
 net/bluetooth/mgmt.c      | 23 ++++++++++++++++++++---
 3 files changed, 54 insertions(+), 7 deletions(-)
net/bluetooth/hci_event.c +11 -1
index af7f1de7d657d..8b9b27f2d8916 100644
@@ -1770,6 +1770,8 @@ static void store_pending_adv_report(struct hci_dev *hdev, bdaddr_t *bdaddr,
 
 static void le_set_scan_enable_complete(struct hci_dev *hdev, u8 enable)
 {
+	bool timeout_pending;
+
 	hci_dev_lock(hdev);
 
 	switch (enable) {
@@ -1799,10 +1801,18 @@ static void le_set_scan_enable_complete(struct hci_dev *hdev, u8 enable)
 		/* Cancel this timer so that we don't try to disable scanning
 		 * when it's already disabled.
 		 */
-		cancel_delayed_work(&hdev->le_scan_disable);
+		timeout_pending = cancel_delayed_work(&hdev->le_scan_disable);
 
 		hci_dev_clear_flag(hdev, HCI_LE_SCAN);
 
+		/* The scan of a discovery was disabled before its timeout,
+		 * for example by a Stop Discovery that timed out and still
+		 * completed, so nothing else would end the discovery.
+		 */
+		if (timeout_pending &&
+		    hdev->discovery.state == DISCOVERY_FINDING)
+			hci_discovery_set_state(hdev, DISCOVERY_STOPPED);
+
 		if (hdev->discovery.type == DISCOV_TYPE_INTERLEAVED &&
 		    hci_test_quirk(hdev, HCI_QUIRK_SIMULTANEOUS_DISCOVERY) &&
 		    !test_bit(HCI_INQUIRY, &hdev->flags) &&
net/bluetooth/hci_sync.c +23 -3
index e5f29558f1468..ba5add3292e33 100644
@@ -376,8 +376,18 @@ static void le_scan_disable(struct work_struct *work)
 	bt_dev_dbg(hdev, "");
 	hci_dev_lock(hdev);
 
-	if (!hci_dev_test_flag(hdev, HCI_LE_SCAN))
+	if (!hci_dev_test_flag(hdev, HCI_LE_SCAN)) {
+		/* The scan of a discovery can be disabled while this work
+		 * waits for the lock, for example by a Stop Discovery that
+		 * timed out and still completed, so end the discovery as
+		 * le_set_scan_enable_complete() does when it cancels this
+		 * work.
+		 */
+		if (hdev->discovery.state == DISCOVERY_FINDING)
+			goto discov_stopped;
+
 		goto _return;
+	}
 
 	status = hci_cmd_sync_queue(hdev, scan_disable_sync, NULL, NULL);
 	if (status) {
@@ -5762,11 +5772,15 @@ int hci_stop_discovery_sync(struct hci_dev *hdev)
 		}
 
 		if (hci_dev_test_flag(hdev, HCI_LE_SCAN)) {
-			cancel_delayed_work(&hdev->le_scan_disable);
-
 			err = hci_scan_disable_sync(hdev);
 			if (err)
 				return err;
+
+			/* Only cancel the LE scan timeout once the scan is
+			 * disabled, so that the discovery still ends if
+			 * stopping it failed.
+			 */
+			cancel_delayed_work(&hdev->le_scan_disable);
 		}
 
 	} else {
@@ -6401,6 +6415,12 @@ static int hci_pause_discovery_sync(struct hci_dev *hdev)
 		return 0;
 
 	hci_discovery_set_state(hdev, DISCOVERY_STOPPING);
+
+	/* Cancel the LE scan timeout first, so that it does not run while
+	 * suspended if the scan cannot be disabled.
+	 */
+	cancel_delayed_work(&hdev->le_scan_disable);
+
 	err = hci_stop_discovery_sync(hdev);
 	if (err)
 		return err;
net/bluetooth/mgmt.c +20 -3
index 8d18e94fe8c05..b16b70a3cab61 100644
@@ -6242,12 +6242,29 @@ static void stop_discovery_complete(struct hci_dev *hdev, void *data, int err)
 
 	bt_dev_dbg(hdev, "err %d", err);
 
+	hci_dev_lock(hdev);
+
+	/* Change the state before replying, so that a client acting on the
+	 * reply sees it, and only while the discovery is still stopping, as
+	 * Inquiry Cancel may already have stopped it and a new Start Discovery
+	 * may have followed. Go back to DISCOVERY_FINDING when stopping failed
+	 * while the inquiry or the active LE scan of the discovery is still
+	 * running, so that it can be stopped again.
+	 */
+	if (hdev->discovery.state == DISCOVERY_STOPPING) {
+		if (err && (test_bit(HCI_INQUIRY, &hdev->flags) ||
+			    (hci_dev_test_flag(hdev, HCI_LE_SCAN) &&
+			     hdev->le_scan_type == LE_SCAN_ACTIVE)))
+			hci_discovery_set_state(hdev, DISCOVERY_FINDING);
+		else
+			hci_discovery_set_state(hdev, DISCOVERY_STOPPED);
+	}
+
+	hci_dev_unlock(hdev);
+
 	mgmt_cmd_complete(cmd->sk, cmd->hdev->id, cmd->opcode, mgmt_status(err),
 			  cmd->param, 1);
 	mgmt_pending_free(cmd);
-
-	if (!err)
-		hci_discovery_set_state(hdev, DISCOVERY_STOPPED);
 }
 
 static int stop_discovery_sync(struct hci_dev *hdev, void *data)
Signature · 1 line
2.53.0
author maintainer
#194 lore raw

PATCH 193/990 selftests/mm: merge: keep the far mremap() targets in the carveout

In reply to Greg Kroah-Hartman

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

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

From: Danish Khateeb <[email protected]>

[ Upstream commit 332c1bd17422c1aa59e18513042e56ea5aac4051 ]

The merge tests map their areas at fixed addresses within a 30-page PROT_NONE carveout. Several mremap() tests move an area 1000 or 2000 pages away to separate it from the others, but those targets are outside the carveout, and MREMAP_FIXED unmaps whatever is mapped there.

Under virtme-ng, the shared libraries are packed right above the carveout and the dynamic linker starts about 4 MiB above it. The moves then replace part of its text with an anonymous mapping, and the test crashes in its next lazily bound call:

merge[6980]: segfault at 7f7ebb3c1e60 ip 00007f7ebb3c1e60 sp 00007ffd35fbaec8 error 14

Two to four of the mremap() tests then fail with "Test terminated unexpectedly by signal 11", depending on the exact layout. On a host where libc is mapped at a 2 MiB aligned address, the targets happen to land above the dynamic linker and the tests pass.

Since the areas are all within the first 30 pages, moving one by 30 pages is enough to keep it apart from the others. Add FAR_PAGES for that distance, move areas by FAR_PAGES or 2 * FAR_PAGES pages, and make the carveout 3 * FAR_PAGES pages so that it covers every target.

Fixes 4e25f85b9f85 ("tools/testing/selftests: add mremap() unfaulted/faulted test cases")
Cc Liam R. Howlett <[email protected]>
Cc Vlastimil Babka <[email protected]>
Cc Jann Horn <[email protected]>
Cc Pedro Falcato <[email protected]>
Cc David Hildenbrand <[email protected]>
Cc Mike Rapoport <[email protected]>
Cc Suren Baghdasaryan <[email protected]>
Cc Michal Hocko <[email protected]>
Cc Shuah Khan <[email protected]>
---
 tools/testing/selftests/mm/merge.c | 33 ++++++++++++++++--------------
 1 file changed, 18 insertions(+), 15 deletions(-)
tools/testing/selftests/mm/merge.c +18 -15
index 10b686102b79d..65c30632795ec 100644
@@ -22,9 +22,12 @@ FIXTURE(merge)
 	struct procmap_fd procmap;
 };
 
+#define FAR_PAGES	30
+#define CARVEOUT_PAGES	(3 * FAR_PAGES)
+
 static char *map_carveout(unsigned int page_size)
 {
-	return mmap(NULL, 30 * page_size, PROT_NONE,
+	return mmap(NULL, CARVEOUT_PAGES * page_size, PROT_NONE,
 		    MAP_ANON | MAP_PRIVATE, -1, 0);
 }
 
@@ -60,7 +63,7 @@ FIXTURE_SETUP(merge)
 
 FIXTURE_TEARDOWN(merge)
 {
-	ASSERT_EQ(munmap(self->carveout, 30 * self->page_size), 0);
+	ASSERT_EQ(munmap(self->carveout, CARVEOUT_PAGES * self->page_size), 0);
 	/* May fail for parent of forked process. */
 	close_procmap(&self->procmap);
 	/*
@@ -102,7 +105,7 @@ FIXTURE_SETUP(merge_with_fork)
 
 FIXTURE_TEARDOWN(merge_with_fork)
 {
-	ASSERT_EQ(munmap(self->carveout, 30 * self->page_size), 0);
+	ASSERT_EQ(munmap(self->carveout, CARVEOUT_PAGES * self->page_size), 0);
 	ASSERT_EQ(close_procmap(&self->procmap), 0);
 	/* See above. */
 	prctl(PR_SET_MEMORY_MERGE, 0, 0, 0, 0);
@@ -647,7 +650,7 @@ TEST_F(merge, mremap_unfaulted_to_faulted)
 
 	/* Offset ptr2 further away. */
 	ptr2 = sys_mremap(ptr2, 5 * page_size, 5 * page_size,
-			  MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + page_size * 1000);
+			  MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + FAR_PAGES * page_size);
 	ASSERT_NE(ptr2, MAP_FAILED);
 
 	/*
@@ -708,7 +711,7 @@ TEST_F(merge, mremap_unfaulted_behind_faulted)
 
 	/* Offset ptr2 further away. */
 	ptr2 = sys_mremap(ptr2, 5 * page_size, 5 * page_size,
-			  MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + page_size * 1000);
+			  MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + FAR_PAGES * page_size);
 	ASSERT_NE(ptr2, MAP_FAILED);
 
 	/*
@@ -772,12 +775,12 @@ TEST_F(merge, mremap_unfaulted_between_faulted)
 
 	/* Offset ptr3 further away. */
 	ptr3 = sys_mremap(ptr3, 5 * page_size, 5 * page_size,
-			  MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + page_size * 2000);
+			  MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + 2 * FAR_PAGES * page_size);
 	ASSERT_NE(ptr3, MAP_FAILED);
 
 	/* Offset ptr2 further away. */
 	ptr2 = sys_mremap(ptr2, 5 * page_size, 5 * page_size,
-			  MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + page_size * 1000);
+			  MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + FAR_PAGES * page_size);
 	ASSERT_NE(ptr2, MAP_FAILED);
 
 	/*
@@ -857,13 +860,13 @@ TEST_F(merge, mremap_unfaulted_between_faulted_unfaulted)
 
 	/* Offset ptr3 further away. */
 	ptr3 = sys_mremap(ptr3, 5 * page_size, 5 * page_size,
-			  MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + page_size * 2000);
+			  MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + 2 * FAR_PAGES * page_size);
 	ASSERT_NE(ptr3, MAP_FAILED);
 
 
 	/* Offset ptr2 further away. */
 	ptr2 = sys_mremap(ptr2, 5 * page_size, 5 * page_size,
-			  MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + page_size * 1000);
+			  MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + FAR_PAGES * page_size);
 	ASSERT_NE(ptr2, MAP_FAILED);
 
 	/*
@@ -1022,11 +1025,11 @@ TEST_F(merge, mremap_correct_placed_faulted)
 	 */
 	ptr3 = &ptr[10 * page_size];
 	ptr3 = sys_mremap(ptr3, 5 * page_size, 5 * page_size,
-			  MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + page_size * 2000);
+			  MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + 2 * FAR_PAGES * page_size);
 	ASSERT_NE(ptr3, MAP_FAILED);
 	ptr2 = &ptr[5 * page_size];
 	ptr2 = sys_mremap(ptr2, 5 * page_size, 5 * page_size,
-			  MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + page_size * 1000);
+			  MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + FAR_PAGES * page_size);
 	ASSERT_NE(ptr2, MAP_FAILED);
 
 	/*
@@ -1062,7 +1065,7 @@ TEST_F(merge, mremap_correct_placed_faulted)
 	 *                  ptr2      \       ptr       \       ptr3
 	 */
 	ptr = sys_mremap(ptr, 5 * page_size, 5 * page_size,
-			 MREMAP_MAYMOVE | MREMAP_FIXED, ptr + page_size * 1000);
+			 MREMAP_MAYMOVE | MREMAP_FIXED, ptr + FAR_PAGES * page_size);
 	ASSERT_NE(ptr, MAP_FAILED);
 
 	/*
@@ -1097,7 +1100,7 @@ TEST_F(merge, mremap_correct_placed_faulted)
 	 *                  ptr2      \       ptr       \       ptr3
 	 */
 	ptr = sys_mremap(ptr, 5 * page_size, 5 * page_size,
-			 MREMAP_MAYMOVE | MREMAP_FIXED, ptr + page_size * 1000);
+			 MREMAP_MAYMOVE | MREMAP_FIXED, ptr + FAR_PAGES * page_size);
 	ASSERT_NE(ptr, MAP_FAILED);
 
 	/*
@@ -1155,7 +1158,7 @@ TEST_F(merge, mremap_correct_placed_faulted)
 	 *      ptr                     ptr3      \       ptr2
 	 */
 	ptr2 = sys_mremap(ptr2, 5 * page_size, 5 * page_size,
-			  MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + page_size * 1000);
+			  MREMAP_MAYMOVE | MREMAP_FIXED, ptr2 + FAR_PAGES * page_size);
 	ASSERT_NE(ptr2, MAP_FAILED);
 
 	/*
@@ -1190,7 +1193,7 @@ TEST_F(merge, mremap_correct_placed_faulted)
 	 *            ptr                         \       ptr3
 	 */
 	ptr3 = sys_mremap(ptr3, 5 * page_size, 5 * page_size,
-			  MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + page_size * 1000);
+			  MREMAP_MAYMOVE | MREMAP_FIXED, ptr3 + FAR_PAGES * page_size);
 	ASSERT_NE(ptr3, MAP_FAILED);
 
 	/*
Signature · 1 line
2.53.0
author maintainer
#195 lore raw

PATCH 194/990 mctp i3c: Fix locking in an error path

In reply to Greg Kroah-Hartman

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

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

From: Bart Van Assche <[email protected]>

[ Upstream commit 750eb5ab457e62e221a9c8521e2274f14c85b387 ]

If netdev_alloc_skb() fails, mctp_i3c_read() jumps to a label that unlocks mi->lock although that mutex has not been locked yet. Fix this by returning -ENOMEM directly. This bug has been detected by the Clang thread-safety analyzer.

---
 drivers/net/mctp/mctp-i3c.c | 3 +--
 1 file changed, 1 insertion(+), 2 deletions(-)
drivers/net/mctp/mctp-i3c.c +1 -2
index 1d9d0c1418ebd..22376ea460f12 100644
@@ -111,8 +111,7 @@ static int mctp_i3c_read(struct mctp_i3c_device *mi)
 			       mi->mrl + sizeof(struct mctp_i3c_internal_hdr));
 	if (!skb) {
 		stats->rx_dropped++;
-		rc = -ENOMEM;
-		goto err;
+		return -ENOMEM;
 	}
 
 	skb->protocol = htons(ETH_P_MCTP);
Signature · 1 line
2.53.0
author maintainer
#196 lore raw

PATCH 195/990 ksmbd: implement error handling for STATUS_INFO_LENGTH_MISMATCH in smb server

In reply to Greg Kroah-Hartman

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

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

From: Aaditya Kansal <[email protected]>

[ Upstream commit e4442b2e95baf0901830c924d0a197b100aca970 ]

Add STATUS_INFO_LENGTH_MISMATCH mapping to EMSGSIZE. Currently, STATUS_INFO_LENGTH_MISMATCH has no mapping to any error code, making it difficult to distinguish between invalid parameters and length mismatch.

Map STATUS_INFO_LENGTH_MISMATCH to EMSGSIZE while keeping the EINVAL for invalid parameters. Although the buf_len check only checks for buf_size being less than required, there was no error code for lower buf_size. Hence, EMSGSIZE is used.

Stable-dep-of: e49296d51ccb ("ksmbd: require NUL-terminated EA names")

---
 fs/smb/server/smb2pdu.c | 21 +++++++++++----------
 1 file changed, 11 insertions(+), 10 deletions(-)
fs/smb/server/smb2pdu.c +11 -10
index 94a18e0ee9c20..56dc2134d8bac 100644
@@ -6769,7 +6769,6 @@ static int set_file_mode_info(struct ksmbd_file *fp,
  * @share:	ksmbd_share_config pointer
  *
  * Return:	0 on success, otherwise error
- * TODO: need to implement an error handling for STATUS_INFO_LENGTH_MISMATCH
  */
 static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
 			      struct smb2_set_info_req *req,
@@ -6782,14 +6781,14 @@ static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
 	case FILE_BASIC_INFORMATION:
 	{
 		if (buf_len < sizeof(struct smb2_file_basic_info))
-			return -EINVAL;
+			return -EMSGSIZE;
 
 		return set_file_basic_info(fp, (struct smb2_file_basic_info *)buffer, share);
 	}
 	case FILE_ALLOCATION_INFORMATION:
 	{
 		if (buf_len < sizeof(struct smb2_file_alloc_info))
-			return -EINVAL;
+			return -EMSGSIZE;
 
 		return set_file_allocation_info(work, fp,
 						(struct smb2_file_alloc_info *)buffer);
@@ -6797,7 +6796,7 @@ static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
 	case FILE_END_OF_FILE_INFORMATION:
 	{
 		if (buf_len < sizeof(struct smb2_file_eof_info))
-			return -EINVAL;
+			return -EMSGSIZE;
 
 		return set_end_of_file_info(work, fp,
 					    (struct smb2_file_eof_info *)buffer);
@@ -6805,7 +6804,7 @@ static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
 	case FILE_RENAME_INFORMATION:
 	{
 		if (buf_len < sizeof(struct smb2_file_rename_info))
-			return -EINVAL;
+			return -EMSGSIZE;
 
 		return set_rename_info(work, fp,
 				       (struct smb2_file_rename_info *)buffer,
@@ -6816,7 +6815,7 @@ static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
 		struct smb2_file_link_info *file_info;
 
 		if (buf_len < sizeof(struct smb2_file_link_info))
-			return -EINVAL;
+			return -EMSGSIZE;
 
 		file_info = (struct smb2_file_link_info *)buffer;
 		if (file_info->ReplaceIfExists && !(fp->daccess & FILE_DELETE_LE)) {
@@ -6831,7 +6830,7 @@ static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
 	case FILE_DISPOSITION_INFORMATION:
 	{
 		if (buf_len < sizeof(struct smb2_file_disposition_info))
-			return -EINVAL;
+			return -EMSGSIZE;
 
 		return set_file_disposition_info(work, fp,
 						 (struct smb2_file_disposition_info *)buffer);
@@ -6845,7 +6844,7 @@ static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
 		}
 
 		if (buf_len < sizeof(struct smb2_ea_info))
-			return -EINVAL;
+			return -EMSGSIZE;
 
 		return smb2_set_ea((struct smb2_ea_info *)buffer,
 				   buf_len, &fp->filp->f_path, true);
@@ -6853,14 +6852,14 @@ static int smb2_set_info_file(struct ksmbd_work *work, struct ksmbd_file *fp,
 	case FILE_POSITION_INFORMATION:
 	{
 		if (buf_len < sizeof(struct smb2_file_pos_info))
-			return -EINVAL;
+			return -EMSGSIZE;
 
 		return set_file_position_info(fp, (struct smb2_file_pos_info *)buffer);
 	}
 	case FILE_MODE_INFORMATION:
 	{
 		if (buf_len < sizeof(struct smb2_file_mode_info))
-			return -EINVAL;
+			return -EMSGSIZE;
 
 		return set_file_mode_info(fp, (struct smb2_file_mode_info *)buffer);
 	}
@@ -6968,6 +6967,8 @@ int smb2_set_info(struct ksmbd_work *work)
 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
 	else if (rc == -EINVAL)
 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
+	else if (rc == -EMSGSIZE)
+		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
 	else if (rc == -ESHARE)
 		rsp->hdr.Status = STATUS_SHARING_VIOLATION;
 	else if (rc == -ENOENT)
Signature · 1 line
2.53.0
author maintainer
#197 lore raw

PATCH 196/990 ksmbd: require NUL-terminated EA names

In reply to Greg Kroah-Hartman

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

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

From: Yifan Zhang <[email protected]>

[ Upstream commit e49296d51ccbf2ad0ed0484db1382f1d7217bd6e ]

smb2_set_ea() verifies that the byte reserved for the declared EA-name terminator lies inside the request, but it does not verify that the byte is zero. With SMB debug logging enabled, the name is passed to %s and the diagnostic reads beyond the request allocation.

KASAN reports:

  BUG: KASAN: slab-out-of-bounds in string
  Read of size 1
  string
  vsnprintf
  _printk
  smb2_set_ea
  smb2_set_info

Reject an EA entry whose declared terminator byte is nonzero. Return -EBADMSG for the malformed buffer, and map that error to STATUS_EA_LIST_INCONSISTENT for both SET_INFO and CREATE.

Fixes e2f34481b24d ("cifsd: add server-side procedures for SMB3")
---
 fs/smb/server/smb2pdu.c | 9 +++++++++
 1 file changed, 9 insertions(+)
fs/smb/server/smb2pdu.c +9 -0
index 56dc2134d8bac..53094243d456b 100644
@@ -2453,6 +2453,11 @@ static int smb2_set_ea(struct smb2_ea_info *eabuf, unsigned int buf_len,
 		if (!eabuf->EaNameLength)
 			goto next;
 
+		if (eabuf->name[eabuf->EaNameLength]) {
+			rc = -EBADMSG;
+			break;
+		}
+
 		ksmbd_debug(SMB,
 			    "name : <%s>, name_len : %u, value_len : %u, next : %u\n",
 			    eabuf->name, eabuf->EaNameLength,
@@ -3935,6 +3940,8 @@ int smb2_open(struct ksmbd_work *work)
 	if (rc) {
 		if (rc == -EINVAL)
 			rsp->hdr.Status = STATUS_INVALID_PARAMETER;
+		else if (rc == -EBADMSG)
+			rsp->hdr.Status = STATUS_EA_LIST_INCONSISTENT;
 		else if (rc == -EOPNOTSUPP)
 			rsp->hdr.Status = STATUS_NOT_SUPPORTED;
 		else if (rc == -EACCES || rc == -ESTALE || rc == -EXDEV) {
@@ -6967,6 +6974,8 @@ int smb2_set_info(struct ksmbd_work *work)
 		rsp->hdr.Status = STATUS_ACCESS_DENIED;
 	else if (rc == -EINVAL)
 		rsp->hdr.Status = STATUS_INVALID_PARAMETER;
+	else if (rc == -EBADMSG)
+		rsp->hdr.Status = STATUS_EA_LIST_INCONSISTENT;
 	else if (rc == -EMSGSIZE)
 		rsp->hdr.Status = STATUS_INFO_LENGTH_MISMATCH;
 	else if (rc == -ESHARE)
Signature · 1 line
2.53.0
author maintainer
#198 lore raw

PATCH 197/990 soreuseport: annotate data-races around reuse->socks[] and num_socks

In reply to Greg Kroah-Hartman

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

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

From: Eric Dumazet <[email protected]>

[ Upstream commit 213d491308b99d026514c93980cf8dd572226b1b ]

reuseport_select_sock() and reuseport_migrate_sock() read reuse->num_socks and reuse->socks[] locklessly under RCU, while writers holding reuseport_lock can change them.

Readers snapshot num_socks once, then index socks[] with it. Meanwhile, writers can perform several operations, storing into slots below the reader's stale count:

- __reuseport_detach_sock() moves the last socket into slot i.
- __reuseport_add_sock() then writes the new socket at the (now smaller) num_socks index.
- reuseport_stop_listen_sock() calls __reuseport_detach_sock() then __reuseport_add_closed_sock(), which writes slot max_socks - num_closed_socks - 1. This can be the slot a reader still considers part of the listener region when the array is full.
- __reuseport_detach_closed_sock() can then rewrite that slot.

All pointers stored in socks[] remain valid for the RCU grace period, but without annotations the compiler is allowed to tear or reload these accesses. For instance, reuseport_select_sock_by_hash() could reload reuse->socks[i] between the sk_state/sk_incoming_cpu checks and the return, returning a socket that did not pass them.

Use WRITE_ONCE() for all socks[] stores done while the array is visible to readers, and for num_socks updates (readers already use READ_ONCE()). Use READ_ONCE() in the two lockless readers.

---
 net/core/sock_reuseport.c | 17 +++++++++--------
 1 file changed, 9 insertions(+), 8 deletions(-)
net/core/sock_reuseport.c +9 -8
index 4211710393a8a..d4b7caf86eee3 100644
@@ -124,10 +124,10 @@ static int reuseport_sock_index(struct sock *sk,
 static void __reuseport_add_sock(struct sock *sk,
 				 struct sock_reuseport *reuse)
 {
-	reuse->socks[reuse->num_socks] = sk;
+	WRITE_ONCE(reuse->socks[reuse->num_socks], sk);
 	/* paired with smp_rmb() in reuseport_(select|migrate)_sock() */
 	smp_wmb();
-	reuse->num_socks++;
+	WRITE_ONCE(reuse->num_socks, reuse->num_socks + 1);
 	reuseport_get_incoming_cpu(sk, reuse);
 }
 
@@ -139,8 +139,8 @@ static bool __reuseport_detach_sock(struct sock *sk,
 	if (i == -1)
 		return false;
 
-	reuse->socks[i] = reuse->socks[reuse->num_socks - 1];
-	reuse->num_socks--;
+	WRITE_ONCE(reuse->socks[i], reuse->socks[reuse->num_socks - 1]);
+	WRITE_ONCE(reuse->num_socks, reuse->num_socks - 1);
 	reuseport_put_incoming_cpu(sk, reuse);
 
 	return true;
@@ -149,7 +149,7 @@ static bool __reuseport_detach_sock(struct sock *sk,
 static void __reuseport_add_closed_sock(struct sock *sk,
 					struct sock_reuseport *reuse)
 {
-	reuse->socks[reuse->max_socks - reuse->num_closed_socks - 1] = sk;
+	WRITE_ONCE(reuse->socks[reuse->max_socks - reuse->num_closed_socks - 1], sk);
 	/* paired with READ_ONCE() in inet_csk_bind_conflict() */
 	WRITE_ONCE(reuse->num_closed_socks, reuse->num_closed_socks + 1);
 	reuseport_get_incoming_cpu(sk, reuse);
@@ -163,7 +163,8 @@ static bool __reuseport_detach_closed_sock(struct sock *sk,
 	if (i == -1)
 		return false;
 
-	reuse->socks[i] = reuse->socks[reuse->max_socks - reuse->num_closed_socks];
+	WRITE_ONCE(reuse->socks[i],
+		   reuse->socks[reuse->max_socks - reuse->num_closed_socks]);
 	/* paired with READ_ONCE() in inet_csk_bind_conflict() */
 	WRITE_ONCE(reuse->num_closed_socks, reuse->num_closed_socks - 1);
 	reuseport_put_incoming_cpu(sk, reuse);
@@ -521,7 +522,7 @@ static struct sock *run_bpf_filter(struct sock_reuseport *reuse, u16 socks,
 	if (index >= socks)
 		return NULL;
 
-	return reuse->socks[index];
+	return READ_ONCE(reuse->socks[index]);
 }
 
 static struct sock *reuseport_select_sock_by_hash(struct sock_reuseport *reuse,
@@ -532,7 +533,7 @@ static struct sock *reuseport_select_sock_by_hash(struct sock_reuseport *reuse,
 
 	i = j = reciprocal_scale(hash, num_socks);
 	do {
-		struct sock *sk = reuse->socks[i];
+		struct sock *sk = READ_ONCE(reuse->socks[i]);
 
 		if (sk->sk_state != TCP_ESTABLISHED) {
 			/* Paired with WRITE_ONCE() in __reuseport_(get|put)_incoming_cpu(). */
Signature · 1 line
2.53.0
author maintainer
#163 lore raw

PATCH 162/990 virtio_blk: Reset device on probe error paths after DRIVER_OK

In reply to Greg Kroah-Hartman

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

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

From: Yuho Choi <[email protected]>

[ Upstream commit f4f6e9a9cb349003d333f0776de94f12ac95b8d2 ]

virtblk_probe() marks the device ready before revalidating zones and adding the disk, and either of those can fail. The out_cleanup_disk path they take goes on to delete the virtqueues, but nothing tells the device to stop first, so it is still live when the rings are freed.

Reset the device at out_cleanup_disk, which is only reachable after virtio_device_ready(). virtblk_remove() and virtblk_freeze_priv() both reset before deleting the virtqueues for the same reason.

Fixes dbb301f91fc8 ("virtio_blk: add error handling support for add_disk()")

Message-ID: <[email protected]>

---
 drivers/block/virtio_blk.c | 1 +
 1 file changed, 1 insertion(+)
drivers/block/virtio_blk.c +1 -0
index 6cfad73bf47df..29317945a7c00 100644
@@ -1583,6 +1583,7 @@ static int virtblk_probe(struct virtio_device *vdev)
 	return 0;
 
 out_cleanup_disk:
+	virtio_reset_device(vdev);
 	put_disk(vblk->disk);
 out_free_tags:
 	blk_mq_free_tag_set(&vblk->tag_set);
Signature · 1 line
2.53.0
author maintainer
#199 lore raw

PATCH 198/990 vhost-scsi: do not count PI bytes in the data length

In reply to Greg Kroah-Hartman

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

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

From: Jia Jia <[email protected]>

[ Upstream commit 1f5bc40e33d8b3e5e3b89047956099b0c19f1d3d ]

vhost_scsi_handle_vq() moves pi_bytesout or pi_bytesin into the protection sgl and subtracts those bytes from exp_data_len. The length passed to TCM is still exp_data_len + prot_bytes.

prot_bytes comes from virtio_scsi_cmd_req_pi. With VIRTIO_SCSI_F_T10_PI negotiated, vhost reads that header and does not check that the CDB is a READ or WRITE. sbc_check_prot() replaces data_length from the CDB only when the protect field is non-zero. target_cmd_size_check() leaves a write's data_length unchanged when the CDB size is smaller, so a command that does not get that replacement keeps a data_length larger than the data sgl.

The KASAN report is a MODE SELECT whose header had pi_bytesout set. The data sgl held only the parameter list. spc_emulate_modeselect() walked data_length and read the next physical page.

Pass the data sgl length. Protected READ and WRITE still take their length from the CDB in sbc_check_prot().

KASAN reports:

  BUG: KASAN: use-after-free in spc_emulate_modeselect+0x145/0x380 [target_core_mod]
  Read of size 1

spc_emulate_modeselect
__target_execute_cmd
target_execute_cmd
vhost_scsi_write_pending
transport_generic_new_cmd
__target_submit
target_queued_submit_work
process_one_work
worker_thread
kthread
ret_from_fork
ret_from_fork_asm

Fixes 9f977ef7b671 ("vhost-scsi: Include prot_bytes into expected data transfer length")

Message-ID: <[email protected]>

---
 drivers/vhost/scsi.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
drivers/vhost/scsi.c +10 -2
index d39dc7d215c09..4c2964dcb78c8 100644
@@ -1516,9 +1516,17 @@ vhost_scsi_handle_vq(struct vhost_scsi *vs, struct vhost_virtqueue *vq)
 		 * vhost_scsi_queue_data_in() and vhost_scsi_queue_status()
 		 */
 		cmd->tvc_vq_desc = vc.head;
+		/*
+		 * vhost_scsi_mapal() maps the PI bytes into cmd->prot_table.
+		 * It maps the remaining exp_data_len bytes into cmd->table,
+		 * which is the data SGL passed to the target core.  Its
+		 * expected length must therefore exclude prot_bytes.
+		 *
+		 * sbc_check_prot() derives the data length for protected READ
+		 * and WRITE commands from the CDB.
+		 */
 		vhost_scsi_target_queue_cmd(nexus, cmd, cdb, lun, task_attr,
-					    data_direction,
-					    exp_data_len + prot_bytes);
+					    data_direction, exp_data_len);
 		ret = 0;
 err:
 		/*
Signature · 1 line
2.53.0