Linux bluetooth development
 help / color / mirror / Atom feed
* [PATCH AUTOSEL 6.18-6.1] Bluetooth: hci_event: fix out-of-bounds read in LE PA report reassembly
       [not found] <20261019135441.1420968-1-sashal@kernel.org>
@ 2026-10-19 13:45 ` Sasha Levin
  2026-10-19 13:45 ` [PATCH AUTOSEL 6.18-5.10] Bluetooth: btrsi: Move set_bt_context after successful HCI registration Sasha Levin
                   ` (8 subsequent siblings)
  9 siblings, 0 replies; 10+ messages in thread
From: Sasha Levin @ 2026-10-19 13:45 UTC (permalink / raw)
  To: patches, stable
  Cc: Laxman Acharya, Luiz Augusto von Dentz, Sasha Levin, marcel,
	luiz.dentz, linux-bluetooth, linux-kernel

From: Laxman Acharya <acharyalaxman8848@gmail.com>

[ Upstream commit e3643fbddb257c928c075cab05bbd929106b56ee ]

hci_le_per_adv_report_evt() is dispatched with a minimum length of
sizeof(struct hci_ev_le_per_adv_report), which only covers the fixed
part of the event and not the trailing data[] array:

	struct hci_ev_le_per_adv_report {
		__le16   sync_handle;
		__u8     tx_power;
		__u8     rssi;
		__u8     cte_type;
		__u8     data_status;
		__u8     length;
		__u8     data[];
	} __packed;

The handler notifies the ISO layer via hci_proto_connect_ind(), which
reaches iso_connect_ind(). That function retrieves the stored event with
hci_recv_event_data() and, while reassembling the periodic advertising
data, does:

	memcpy(hcon->le_per_adv_data + hcon->le_per_adv_data_offset,
	       ev->data, ev->length);

ev->length is taken directly from the event and is never validated
against the amount of data the event actually carries.  A controller
that reports a length larger than the received event therefore causes
the memcpy() to read past the end of the event buffer.  The leaked bytes
are stored in hcon->le_per_adv_data and can subsequently be read back
from user space via getsockopt(BT_ISO_BASE).

Validate that the event contains ev->length data bytes before it is
consumed, mirroring the check already performed by
hci_le_ext_adv_report_evt() and hci_le_adv_report_evt().

Signed-off-by: Laxman Acharya <acharyalaxman8848@gmail.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
Signed-off-by: Sasha Levin <sashal@kernel.org>
---

LLM Generated explanations, may be completely bogus:

This is a 6.12.111 tree (`pending-6.12`). The PA-report handler is
present and still copies `ev->length` without checking the event buffer,
so the OOB read and `BT_ISO_BASE` leak exist here.

---

## PHASE 1: COMMIT MESSAGE FORENSICS

**Step 1.1: PARSE THE SUBJECT LINE**
Record: `[Bluetooth/hci_event] [fix] [out-of-bounds read while
reassembling LE periodic advertising reports]`

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**
Record:
- `Signed-off-by: Laxman Acharya <acharyalaxman8848@gmail.com>` (author)
- `Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>`
  (Bluetooth maintainer applied it)
- No `Fixes:` tag (expected for this review)
- No `Cc: stable@vger.kernel.org` (expected)
- No `Reported-by:` / `Tested-by:` / `Reviewed-by:` / `Link:`
- Ignore any pipeline `Signed-off-by: Sasha Levin` / `[Upstream commit
  ...]` markers

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**
Record:
- Bug: `hci_le_per_adv_report_evt()` is dispatched with `min_len ==
  sizeof(struct hci_ev_le_per_adv_report)` (fixed header only).
  `iso_connect_ind()` later does `memcpy(..., ev->data, ev->length)`
  using the controller-supplied length with no check against remaining
  event bytes.
- Symptom: slab/skb out-of-bounds read; copied bytes land in
  `hcon->le_per_adv_data` and can be read from userspace via
  `getsockopt(BT_ISO_BASE)`.
- Failure mode: kernel info leak (and KASAN OOB read / possible oops).
- Root cause: HCI LE Periodic Advertising Report `length` is trusted;
  sibling handlers (`hci_le_adv_report_evt`,
  `hci_le_ext_adv_report_evt`) already validate trailing data with
  `hci_le_ev_skb_pull()`.
- Version info: none in the message. Local history puts the memcpy in
  v6.9-rc1 (`168d9bf9c7f01`), present in this 6.12 tree.

**Step 1.4: DETECT HIDDEN BUG FIXES**
Record: Not a disguised cleanup. Subject and body describe a real OOB
read plus userspace-visible leak. Explicit `fix`.

---

## PHASE 2: DIFF ANALYSIS

**Step 2.1: INVENTORY THE CHANGES**
Record:
- File: `net/bluetooth/hci_event.c` — about +7 / -0 (comment + 2
  executable lines)
- Function: `hci_le_per_adv_report_evt()`
- Scope: single-file surgical fix

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**
Record: Before: after the debug print, the handler takes `hci_dev_lock`
and calls `hci_proto_connect_ind()` → `iso_connect_ind()`, which copies
`ev->length` bytes from the stored event. After:
`hci_le_ev_skb_pull(hdev, skb, HCI_EV_LE_PER_ADV_REPORT, ev->length)`
must succeed first; on failure the event is dropped and logged as a
malformed LE event. Normal well-formed reports are unchanged.

**Step 2.3: IDENTIFY THE BUG MECHANISM**
Record:
- Category: memory safety — buffer overflow / out-of-bounds **read**,
  with kernel heap contents later exposed to userspace.
- Mechanism: `ev->length` (`u8`) is not compared to remaining skb bytes.
  Destination is capped at `HCI_MAX_PER_AD_TOT_LEN` (1650) in `iso.c`,
  so this is a **source** OOB, not a dest write overflow. The pull is
  the same pattern as LE adv / ext-adv report handlers.

**Step 2.4: ASSESS THE FIX QUALITY**
Record: Obviously correct. `skb_pull_data()` returns NULL when `skb->len
< len`. The check runs before the lock and before
`hci_proto_connect_ind()`, so a short event never reaches the memcpy.
Regression risk is very low: only malformed events are dropped. No
API/data-structure change. `hci_le_ev_skb_pull` is used only for
validation here; `iso_connect_ind()` still reads `hdev->recv_event` (a
clone taken before parsing pulls).

---

## PHASE 3: GIT HISTORY INVESTIGATION

**Step 3.1: BLAME THE CHANGED LINES**
Record:
- Handler added in `9c0826310bfb7` (“Bluetooth: ISO: Add support for
  periodic adv reports processing”, 2023-08-24) — contained in v6.6-rc1,
  ancestor of HEAD.
- Unsafe memcpy added in `168d9bf9c7f01` (“Bluetooth: ISO: Reassemble PA
  data for bcast sink”, 2024-03-06) — contained in **v6.9-rc1**,
  ancestor of this 6.12 tree.
- Call already uses `PA_LINK` (`a8444cca514ed` is in this tree).

**Step 3.2: FOLLOW THE FIXES: TAG**
Record: No `Fixes:` tag. The memcpy that needs the check is
`168d9bf9c7f01`, present here (`git merge-base --is-ancestor`
succeeded).

**Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES**
Record: Same file already has length pulls for adv/ext-adv, BIG complete
(`22559ad7654f6`), etc. This is a standalone one-hunk fix, not patch
X/Y. No later local commit implements this check (`git grep
hci_le_ev_skb_pull.*PER_ADV` empty).

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**
Record: Laxman Acharya is a regular Bluetooth bounds-checking
contributor, not the maintainer. Same-tree examples: `a34df5c4a439c`
(CIG params response length) and `930be1f6ae581` (vendor codec count).
Maintainer Luiz applied this patch.

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS**
Record: Needs `hci_le_ev_skb_pull`, `HCI_EV_LE_PER_ADV_REPORT`,
`hci_le_per_adv_report_evt`, `iso_connect_ind` memcpy, and `PA_LINK`.
All exist in this checkout. Standalone.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**
Record:
- Message-ID: `20260805173701.6649-1-acharyalaxman8848@gmail.com`
- `b4 dig -c` not usable: candidate SHA is not in this checkout.
- `b4 mbox` on that msgid: 3-message thread, **v1 only**.
- Recipients: Luiz von Dentz, Marcel Holtmann, linux-bluetooth, linux-
  kernel.
- Applied to bluetooth-next as `96995a7d94f3` by Luiz (2026-08-07).
  Listed in Luiz’s netdev pull `for-net-next-2026-08-07`.
- No NAK, no reviewer risk comments, no extra revisions.
- BlueZ CI: CheckPatch/build/sparse PASS; **iso-tester PASS**; GitLint
  FAIL only for tabs in the quoted struct; mgmt/mesh failures are
  unrelated timeouts.

**Step 4.2: CHECK WHO REVIEWED THE PATCH**
Record: Sent To Bluetooth maintainers; Luiz applied it (Ack-by-apply).
No extra Reviewed-by.

**Step 4.3: SEARCH FOR THE BUG REPORT**
Record: No syzbot/bugzilla `Reported-by`. Description matches the code
in this tree (`iso.c:2250-2251` memcpy; `iso_sock_getsockopt`
`BT_ISO_BASE`).

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**
Record: Standalone `[PATCH]`, not a series. Same author also sent CIG
validation (already in this tree). No extra companion hunk required.

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**
Record: lore.kernel.org/stable returned 403. gnuweeb linux-bluetooth
index shows this patch (2 messages) with no stable-specific NAK. No
evidence it was rejected for stable.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

semcode MCP tools were not available; used `git grep` and file reads.

**Step 5.1: KEY FUNCTIONS**
Record: `hci_le_per_adv_report_evt` (modified); uses
`hci_le_ev_skb_pull`; downstream `hci_proto_connect_ind` →
`iso_connect_ind`.

**Step 5.2: TRACE CALLERS**
Record: Only the LE subevent table (`HCI_EV_LE_PER_ADV_REPORT` /
`HCI_LE_EV_VL`). Path: `hci_event_packet` → `hci_event_func` →
`hci_le_meta_evt` (pulls `min_len` = 7-byte header) → handler. HCI
events come from the controller (USB/UART/virtio) or a user-channel HCI
socket (`CAP_NET_ADMIN` / `CAP_NET_RAW` in `hci_sock.c`).

**Step 5.3: TRACE CALLEES**
Record: `hci_le_ev_skb_pull` → `skb_pull_data` (NULL if short). Then
lock, `hci_proto_connect_ind` → `iso_connect_ind` →
`hci_recv_event_data` (clone at `hci_event_packet`) → memcpy of
`ev3->data`.

**Step 5.4: FOLLOW THE CALL CHAIN**
Record: Reachable on CONFIG_BT + CONFIG_BT_LE (iso.o, default y) when a
broadcast-sink ISO socket matches `sync_handle`. `iso_sock_create()` has
no extra cap check. The memcpy runs only if `iso_get_sock` finds that
listener. Userspace can then read `le_per_adv_data` via
`getsockopt(BT_ISO_BASE)` when connected with `dst == BDADDR_ANY`.

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**
Record: Trailing-data pulls already in `hci_le_adv_report_evt`,
`hci_le_ext_adv_report_evt`, `hci_le_create_big_complete_evt`. This
handler was the missing analog for PA reports.

---

## PHASE 6: CROSS-REFERENCING AGAINST THE LOCAL TREE

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?**
Record: Yes. `net/bluetooth/hci_event.c:6460-6497` has the handler
**without** the pull. `iso.c:2246-2251` has dest-size check only, then
memcpy of `ev3->length`. Struct FAM is in `include/net/bluetooth/hci.h`.
Introduced v6.9, present in 6.12.111.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**
Record: `git apply --check` of the candidate hunk **succeeded**.
Insertion site matches (after `bt_dev_dbg`, before `hci_dev_lock`).
Expected difficulty: **clean apply**.

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**
Record: No. `git log --grep="out-of-bounds read in LE PA"` empty; no
`hci_le_ev_skb_pull(..., HCI_EV_LE_PER_ADV_REPORT, ev->length)`.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

**Step 7.1: SUBSYSTEM AND CRITICALITY**
Record: `net/bluetooth` HCI event parsing + ISO (LE Audio / periodic
advertising / broadcast sink). **IMPORTANT** — not mm/core, but default-
on `CONFIG_BT_LE` on phones, laptops, IoT.

**Step 7.2: SUBSYSTEM ACTIVITY**
Record: Active; many recent HCI/ISO memory-safety fixes in this tree.
Pattern of trusting HCI length fields is a known class.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

**Step 8.1: WHO IS AFFECTED**
Record: Bluetooth LE users with ISO broadcast sink / PA sync (LE Audio /
Auracast-style). Config: `CONFIG_BT` + `CONFIG_BT_LE`. Driver- and
config-specific, not universal.

**Step 8.2: TRIGGER CONDITIONS**
Record: Malformed `HCI_EV_LE_PER_ADV_REPORT` (`length` larger than
remaining bytes) while a matching ISO listener exists. Sources:
buggy/malicious controller (including USB dongle), or privileged HCI
injection. Not every boot; realistic for HCI parsers. Unprivileged user
can hold the ISO socket; injecting the event usually needs
controller/firmware or `CAP_NET_ADMIN`/`CAP_NET_RAW`.

**Step 8.3: FAILURE MODE SEVERITY**
Record: Kernel OOB read of skb/slab tail; bytes stored and returned by
`getsockopt(BT_ISO_BASE)` → **info leak**. KASAN/hardened kernels can
oops. Severity: **HIGH** (memory safety + userspace-visible leak). Not a
guaranteed panic on every box, but not cosmetic.

**Step 8.4: RISK-BENEFIT RATIO**
Record:
- Benefit: high for BT LE Audio/ISO users — stops OOB read and leak.
- Risk: very low — 2 code lines, established helper, drops only invalid
  events.
- Ratio: strongly favors backport.

---

## PHASE 9: FINAL SYNTHESIS

**Step 9.1: COMPILE THE EVIDENCE**

FOR:
- Real OOB read of HCI event buffer; leak via `BT_ISO_BASE`.
- Buggy memcpy present in this 6.12 tree since v6.9.
- Small, obviously correct; same pull used by sibling handlers.
- Applies cleanly; all helpers/types present.
- Maintainer applied v1; iso-tester passed.
- No new feature/API.

AGAINST:
- Needs ISO broadcast-sink + PA report (not every Bluetooth device).
- No syzbot/`Fixes:`/`Cc: stable` (absence is expected).
- CI GitLint/mgmt/mesh noise is unrelated/cosmetic.

UNRESOLVED (do not drive the verdict):
- lore.kernel.org and git.kernel.org fetches blocked (403 / Anubis).
- `b4 dig -c` unused (SHA not in this repo); thread recovered via msgid.
- Mainline SHA after net-next merge not confirmed locally (bluetooth-
  next `96995a7d94f3` and the 2026-08-07 pull are enough).
- No stable@ thread found (search blocked).

**Step 9.2: STABLE RULES CHECKLIST**
1. Obviously correct and tested? **PASS** — pull-before-consume;
   maintainer applied; iso-tester PASS.
2. Real bug affecting users? **PASS** — OOB read + `getsockopt` leak on
   ISO PA reassembly.
3. Important (crash/security/corruption/deadlock)? **PASS** — HIGH
   memory-safety / info leak.
4. Small and contained? **PASS** — ~7 lines, one function.
5. No new features or APIs? **PASS**.
6. Can apply to this tree? **PASS** — `git apply --check` clean; bug
   present.

**Step 9.3: EXCEPTION CATEGORIES**
Record: Not a device-ID/quirk/DT/build/docs exception. Ordinary
security/correctness fix.

**Step 9.4: DECISION**
Backport. The bug is in this tree, the fix is surgical, and the user-
visible effect is a kernel info leak from a trusted-length HCI field.

---

### What this solves for 6.12 users

On 6.12.111, `hci_le_per_adv_report_evt()` still accepts a 7-byte header
and `iso_connect_ind()` copies `ev->length` bytes from the stored event.
A short HCI packet with a large `length` reads past the skb into
`hcon->le_per_adv_data`, which `getsockopt(BT_ISO_BASE)` can return. The
patch drops that event unless the skb actually contains `ev->length`
data bytes.

### Stable rules / risk vs benefit

Meets all six criteria. Benefit is preventing an OOB read and leak on
Bluetooth ISO PA reassembly; risk is dropping already-invalid events. No
missing prerequisites in this checkout.

### Concerns

None that block backport. Path is ISO/PA-specific, not every HCI user;
still a real memory-safety bug in default `CONFIG_BT_LE` code. No series
dependency.

---

Verification:
- [Phase 1] Parsed tags: author + Luiz SOB only; no
  Fixes/Cc:stable/Reported-by
- [Phase 2] Diff: +7 lines in `hci_le_per_adv_report_evt`;
  `hci_le_ev_skb_pull(..., ev->length)` before consume
- [Phase 2] Confirmed dest check in `iso.c:2246-2248` vs missing source
  check at `iso.c:2250-2251`
- [Phase 2] `skb_pull_data` returns NULL if `skb->len < len`
  (`net/core/skbuff.c:2667-2676`)
- [Phase 3] `git describe HEAD` / Makefile: **6.12.111**, branch
  `pending-6.12`
- [Phase 3] blame: handler `9c0826310bfb7` (v6.6-rc1); memcpy
  `168d9bf9c7f01` (v6.9-rc1); both ancestors of HEAD
- [Phase 3] `git merge-base --is-ancestor 168d9bf9c7f01 HEAD` → yes
- [Phase 3] `git log --grep="out-of-bounds read in LE PA" --
  net/bluetooth/` → empty (fix not in tree)
- [Phase 3] `hci_le_ev_skb_pull` present at `hci_event.c:71-81`
- [Phase 4] `b4 mbox` msgid
  `20260805173701.6649-1-acharyalaxman8848@gmail.com`: v1, 3 msgs, no
  NAK; applied bluetooth-next `96995a7d94f3`
- [Phase 4] BlueZ CI: iso-tester PASS; GitLint tabs in commit-message
  sample; unrelated mgmt/mesh timeouts
- [Phase 4] netdev pull 2026-08-07 lists this commit under Laxman
  Acharya
- [Phase 4] UNVERIFIED: lore.kernel.org 403; git.kernel.org Anubis; `b4
  dig -c` skipped (SHA not local)
- [Phase 5] Call chain: event table → `hci_le_meta_evt` min_len pull →
  handler → `hci_proto_connect_ind` (`PA_LINK`) → `iso_connect_ind`
- [Phase 5] `hci_recv_event_data` uses `skb_clone` taken before pulls
  (`hci_event.c:7575-7576`)
- [Phase 5] `BT_ISO_BASE` getsockopt copies `le_per_adv_data`
  (`iso.c:1834-1848`)
- [Phase 5] `iso.o` built with `CONFIG_BT_LE`; `iso_sock_create` has no
  extra cap
- [Phase 6] Local handler at `hci_event.c:6460` lacks the pull; `git
  apply --check` of candidate hunk exit 0
- [Phase 8] Failure mode: OOB read + userspace info leak; severity HIGH
- UNVERIFIED: whether mgmt/mesh CI fails are pre-existing flakes (iso-
  tester passed; those tests are unrelated)

**YES**

 net/bluetooth/hci_event.c | 7 +++++++
 1 file changed, 7 insertions(+)

diff --git a/net/bluetooth/hci_event.c b/net/bluetooth/hci_event.c
index 23fe327a0fcd6..fd823baf64415 100644
--- a/net/bluetooth/hci_event.c
+++ b/net/bluetooth/hci_event.c
@@ -6580,6 +6580,13 @@ static void hci_le_per_adv_report_evt(struct hci_dev *hdev, void *data,
 
 	bt_dev_dbg(hdev, "sync_handle 0x%4.4x", le16_to_cpu(ev->sync_handle));
 
+	/* The reassembly in iso_connect_ind() copies ev->length bytes from the
+	 * stored event, so make sure the event actually carries that many data
+	 * bytes before it is consumed.
+	 */
+	if (!hci_le_ev_skb_pull(hdev, skb, HCI_EV_LE_PER_ADV_REPORT, ev->length))
+		return;
+
 	hci_dev_lock(hdev);
 
 	mask |= hci_proto_connect_ind(hdev, BDADDR_ANY, PA_LINK, &flags);
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH AUTOSEL 6.18-5.10] Bluetooth: btrsi: Move set_bt_context after successful HCI registration
       [not found] <20261019135441.1420968-1-sashal@kernel.org>
  2026-10-19 13:45 ` [PATCH AUTOSEL 6.18-6.1] Bluetooth: hci_event: fix out-of-bounds read in LE PA report reassembly Sasha Levin
@ 2026-10-19 13:45 ` Sasha Levin
  2026-10-19 13:47 ` [PATCH AUTOSEL 6.18] Bluetooth: bfusb: validate received block boundaries Sasha Levin
                   ` (7 subsequent siblings)
  9 siblings, 0 replies; 10+ messages in thread
From: Sasha Levin @ 2026-10-19 13:45 UTC (permalink / raw)
  To: patches, stable
  Cc: Chen Changcheng, Luiz Augusto von Dentz, Sasha Levin, marcel,
	luiz.dentz, linux-bluetooth, linux-kernel

From: Chen Changcheng <chenchangcheng@kylinos.cn>

[ Upstream commit 290a3644609526f7ac12529cd1618042fa5a32db ]

In rsi_hci_attach(), ops->set_bt_context() stores the newly allocated
h_adapter into common->bt_adapter before hci_alloc_dev() and
hci_register_dev() are called. If either of these fails, h_adapter
is freed but common->bt_adapter remains a non-NULL dangling pointer.

This causes a deterministically reachable use-after-free when the
device operates in a BT+WiFi coexistence mode and CONFIG_RSI_COEX
is enabled. The following software-only trigger paths exist:

  1. SDIO driver .remove  (rsi_disconnect)
  2. USB  driver .disconnect (rsi_disconnect)
  3. SDIO driver .shutdown (rsi_shutdown)
  4. Hibernation .freeze  (rsi_freeze)

All four paths check:
    if (IS_ENABLED(CONFIG_RSI_COEX) && coex_mode > 1 && bt_adapter)
        rsi_bt_ops.detach(bt_adapter);  // use-after-free

coex_mode is set during rsi_91x_init(), before rsi_hci_attach() is
called, and is not cleared on attach failure. Since set_bt_context()
already wrote bt_adapter before the failure, the deinit paths see a
non-NULL dangling pointer and proceed to detach it.

Fix this by moving set_bt_context() after hci_register_dev() succeeds.
On failure paths bt_adapter stays NULL, and the deinit callers correctly
skip the detach call.

Signed-off-by: Chen Changcheng <chenchangcheng@kylinos.cn>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
Signed-off-by: Sasha Levin <sashal@kernel.org>
---

LLM Generated explanations, may be completely bogus:

The local tree is **6.12.111** (`pending-6.12`). The buggy
`set_bt_context()` placement is present in `drivers/bluetooth/btrsi.c`,
and the 3-line UAF fix applies here.

===============================================================
PHASE 1: COMMIT MESSAGE FORENSICS
===============================================================

**Step 1.1: PARSE THE SUBJECT LINE**
Record: [Bluetooth/btrsi] [Move] [Call `set_bt_context()` only after
`hci_register_dev()` succeeds so a failed HCI attach does not leave a
dangling `bt_adapter`.]

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**
Record:
- Signed-off-by: Chen Changcheng \<chenchangcheng@kylinos.cn\> (author)
- Signed-off-by: Luiz Augusto von Dentz \<luiz.von.dentz@intel.com\>
  (Bluetooth maintainer; applied to bluetooth-next)
- No Fixes:, Reported-by:, Tested-by:, Reviewed-by:, Acked-by:, Link:,
  or Cc: stable (absence is expected for this review pipeline)
- Upstream object (verified in this repo’s object store, not an ancestor
  of HEAD): `17abcfc57c8a0071e60a56256fbc4428957d22bb`

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**
Record:
- Bug: `rsi_hci_attach()` stores `h_adapter` into `common->bt_adapter`
  via `ops->set_bt_context()` *before* `hci_alloc_dev()` /
  `hci_register_dev()`. On failure it `kfree`s `h_adapter` but leaves
  `bt_adapter` non-NULL.
- Symptom: use-after-free in later detach callers that test `bt_adapter`
  and call `rsi_bt_ops.detach()`.
- Named triggers: SDIO `.remove` (`rsi_disconnect`), USB `.disconnect`
  (`rsi_disconnect`), SDIO `.shutdown` (`rsi_shutdown`), hibernation
  `.freeze` (`rsi_freeze`).
- Root cause: `coex_mode` is set in `rsi_91x_init()` and is not cleared
  on attach failure, so deinit still takes the BT detach path.
- Version info: none in the message. The buggy placement dates to the
  original driver (`38aa4da504837`, v4.17-rc1).

**Step 1.4: DETECT HIDDEN BUG FIXES**
Record: Not hidden. This is an explicit UAF fix described as such. The
verb “Move” is the mechanism, not a cleanup.

===============================================================
PHASE 2: DIFF ANALYSIS - LINE BY LINE
===============================================================

**Step 2.1: INVENTORY THE CHANGES**
Record:
- File: `drivers/bluetooth/btrsi.c` only (+2 / −1 in the actual commit
  `17abcfc57c8a`; the candidate dump showed extra surrounding context
  including `kzalloc_obj`, which is **not** part of the functional
  change).
- Function: `rsi_hci_attach()`.
- Scope: single-file surgical fix.

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**
Record:
- Before: after `kzalloc`, immediately `ops->set_bt_context(priv,
  h_adapter)` (writes `common->bt_adapter`). Then `hci_alloc_dev()` /
  `hci_register_dev()`. Either failure does `goto err` →
  `kfree(h_adapter)` while `bt_adapter` still points at it.
- After: `set_bt_context()` runs only after `hci_register_dev()` returns
  success. Failure paths leave `bt_adapter` NULL (it was never written),
  so deinit skips detach.
- Path affected: HCI attach error path; success path still publishes the
  adapter, just later.

**Step 2.3: IDENTIFY THE BUG MECHANISM**
Record: [USE-AFTER-FREE / dangling pointer] Mechanism: publish-then-free
on error. Fix: publish only after successful registration. Category (d)
memory safety + (g) error-path ordering.

**Step 2.4: ASSESS THE FIX QUALITY**
Record:
- Obviously correct: `rsi_set_bt_context()` is a straight store of
  `common->bt_adapter`; delaying that store until the object is fully
  live is the right lifetime rule.
- Minimal: one call moved, no API/data-structure change.
- Regression risk: low. During `hci_register_dev()`, `bt_adapter` stays
  NULL so `recv_pkt` is skipped (`if (common->bt_adapter)`). HCI
  callbacks use `hci_set_drvdata()`, which is set before register.
  Attach is synchronous in the RX path, so by the next BT packet
  `bt_adapter` is either valid or still NULL.
- Red flags: none.

===============================================================
PHASE 3: GIT HISTORY INVESTIGATION
===============================================================

**Step 3.1: BLAME THE CHANGED LINES**
Record: Buggy `ops->set_bt_context(priv, h_adapter)` at line 120 is from
`38aa4da504837` (“Bluetooth: btrsi: add new rsi bluetooth driver”,
Prameela Rani Garnepudi, 2018-02-27). Contained in v4.17-rc1. Present in
this 6.12 tree (`git merge-base --is-ancestor 38aa4da504837 HEAD`
succeeded).

**Step 3.2: FOLLOW THE FIXES: TAG**
Record: No Fixes: tag. The introducing commit is the original driver
add, confirmed by blame.

**Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES**
Record: Recent `btrsi.c` history in this tree is unrelated (unaligned.h
move, HCI_AMP removal, header/comment cleanups, tx timeout). No prior
UAF/`set_bt_context` fix. Standalone; not patch X/Y.

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**
Record: Chen Changcheng has no other commits in this tree under
`drivers/bluetooth/`. Luiz von Dentz (who applied it) is the Bluetooth
subsystem maintainer and is active here. Author is not the RSI driver
maintainer; the patch was still taken by the Bluetooth maintainer.

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS**
Record: No prerequisites. `set_bt_context` / `rsi_hci_attach` /
`rsi_bt_ops.detach` all exist in this tree. `git apply --check` of
`17abcfc57c8a` succeeded (hunks at offset +10). Standalone.

===============================================================
PHASE 4: MAILING LIST AND EXTERNAL RESEARCH
===============================================================

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**
Record:
- `b4 dig -c 17abcfc57c8a`: https://patch.msgid.link/20260722083136.1756
  50-1-chenchangcheng@kylinos.cn
- `b4 dig -a`: single v1 series (2026-07-22); no v2/v3.
- Thread: original patch, BlueZ CI bot, patchwork-bot “applied by Luiz”.
  No NAKs. No reviewer-requested respin. No explicit “Cc: stable” in the
  thread.
- Applied to bluetooth-next as `17abcfc57c8a` by Luiz Augusto von Dentz
  (2026-07-23).

**Step 4.2: CHECK WHO REVIEWED THE PATCH**
Record (`b4 dig -w`): To Marcel Holtmann, Luiz von Dentz; Cc linux-
bluetooth, linux-kernel. Appropriate Bluetooth maintainers. Luiz applied
it (maintainer SOB). No additional human Reviewed-by in the mbox.

**Step 4.3: SEARCH FOR THE BUG REPORT**
Record: No Reported-by, syzbot, or bugzilla. Bug is explained from code
analysis. BlueZ CI: CheckPatch/BuildKernel/CheckSparse/IncrementalBuild
PASS.

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**
Record: Standalone 1-patch series. No sibling patches required.

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**
Record: No useful stable-list discussion of this fix was found
(lore.kernel.org search 403; web search for site:lore.kernel.org/stable
returned unrelated btrfs hits). UNVERIFIED that nobody previously
rejected it for stable.

===============================================================
PHASE 5: CODE SEMANTIC ANALYSIS
===============================================================

**Step 5.1: IDENTIFY KEY FUNCTIONS IN THE DIFF**
Record: `rsi_hci_attach()` only. Related callees/callers used to confirm
the UAF: `rsi_set_bt_context()`, `rsi_hci_detach()`, `rsi_attach_bt()`.

**Step 5.2: TRACE CALLERS**
Record:
- `rsi_hci_attach` is `rsi_bt_ops.attach`.
- `rsi_attach_bt()` in `drivers/net/wireless/rsi/rsi_91x_main.c` calls
  `rsi_bt_ops.attach()` and **only logs** on failure.
- Callers of `rsi_attach_bt()`: RX handler on `BT_CARD_READY_IND`
  (`rsi_91x_main.c`), and deferred attach from mgmt FSM
  (`rsi_91x_mgmt.c`).
- Detach UAF sites (all present here):
  - `rsi_91x_sdio.c` remove (~1226), freeze (~1407), shutdown (~1460)
  - `rsi_91x_usb.c` disconnect (~882)
  - `rsi_91x_main.c` `rsi_91x_deinit()` (~411) — same pattern, not
    listed in the commit message
- Context: probe/firmware-ready path and later remove/shutdown/PM. Not
  IRQ-critical; reachable from device lifecycle.

**Step 5.3: TRACE CALLEES**
Record:
`kzalloc`/`hci_alloc_dev`/`hci_register_dev`/`hci_free_dev`/`kfree`;
`ops->set_bt_context` → `rsi_set_bt_context()` which assigns
`common->bt_adapter = bt_context`. `rsi_hci_detach()` does
`hci_unregister_dev`/`hci_free_dev`/`kfree` on that pointer.

**Step 5.4: FOLLOW THE CALL CHAIN**
Record: Plug RSI SDIO/USB device with BT+WiFi firmware
(`CONFIG_RSI_COEX`, `coex_mode > 1`) → firmware `BT_CARD_READY_IND` →
`rsi_attach_bt()` → `rsi_hci_attach()`. If `hci_alloc_dev()` or
`hci_register_dev()` fails, `h_adapter` is freed but `bt_adapter`
remains set. Subsequent BT RX packets hit `if (common->bt_adapter)
rsi_bt_ops.recv_pkt(...)` (UAF without waiting for unplug).
Unplug/shutdown/hibernate also UAF in detach. Userspace can trigger the
lifecycle (unplug, reboot, hibernate); the attach failure itself is an
error path (OOM or HCI register failure).

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**
Record: All `rsi_bt_ops.detach(bt_adapter)` sites share the same
`bt_adapter` NULL-check. No other `set_bt_context` call sites. Same bug
class is concentrated in this one publish point.

===============================================================
PHASE 6: CROSS-REFERENCING AGAINST THE LOCAL TREE
===============================================================

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?**
Record: Yes. `drivers/bluetooth/btrsi.c` lines 119–153:

```119:153:drivers/bluetooth/btrsi.c
        h_adapter->priv = priv;
        ops->set_bt_context(priv, h_adapter);
        h_adapter->proto_ops = ops;
        // ...
        err = hci_register_dev(hdev);
        if (err < 0) {
                BT_ERR("HCI registration failed with errcode %d", err);
                hci_free_dev(hdev);
                goto err;
        }
        return 0;
err:
        h_adapter->hdev = NULL;
        kfree(h_adapter);
```

`rsi_set_bt_context()` assigns `common->bt_adapter`. `coex_mode` is set
in `rsi_91x_init()` (lines 347–366) and is not cleared on attach
failure. Introduced in v4.17; present in 6.12.111.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**
Record: Clean apply. `git show 17abcfc57c8a -- drivers/bluetooth/btrsi.c
| git apply --check` succeeded (offset 10). This tree still uses
`kzalloc(sizeof(*h_adapter), GFP_KERNEL)` rather than mainline
`kzalloc_obj`; that line is outside the committed hunks. No conflicting
local changes.

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**
Record: `git log --grep="set_bt_context"` on these files is empty.
`17abcfc57c8a` is **not** an ancestor of HEAD. No alternate fix present.

===============================================================
PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT
===============================================================

**Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY**
Record: [Bluetooth HCI driver + RSI 91x WiFi coexistence] [IMPORTANT for
RSI users, PERIPHERAL vs core kernel]. `CONFIG_RSI_COEX` is `default y`
when `RSI_91X && BT`. `BT_HCIRSI` is selected by that. Affects
Redpine/Silicon Labs RS9113-class BT+WiFi modules, not all machines.

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**
Record: RSI wireless still receives real fixes in this tree (heap OOB,
beacon length, kthread lifetime, memory corruption). Bluetooth stack is
actively maintained. The UAF itself is old (2018), not a new-code issue.

===============================================================
PHASE 8: IMPACT AND RISK ASSESSMENT
===============================================================

**Step 8.1: DETERMINE WHO IS AFFECTED**
Record: Driver-specific + config-specific: RSI 91x with
`CONFIG_RSI_COEX` (default y) in BT coexistence `oper_mode` (`coex_mode
> 1`).

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**
Record: Requires HCI attach failure (`hci_alloc_dev` OOM or
`hci_register_dev` error) after `coex_mode` is already > 1, then either
continued BT RX or remove/shutdown/freeze. Not every boot; once attach
fails, UAF is deterministic. Unprivileged users can unplug USB or
trigger shutdown; they cannot typically force `hci_register_dev` failure
except under memory pressure.

**Step 8.3: DETERMINE THE FAILURE MODE SEVERITY**
Record: [Use-after-free of `rsi_hci_adapter`, then
`hci_unregister_dev`/`kfree` on freed memory] [HIGH]. Crash/oops; UAF is
also a memory-safety issue. Not a guaranteed panic on every RSI boot.

**Step 8.4: CALCULATE RISK-BENEFIT RATIO**
Record: Benefit HIGH for affected hardware (prevents UAF/crash on a
reachable error path). Risk VERY LOW (3-line reorder, no locking/API
change, applies cleanly). Ratio strongly favors backport.

===============================================================
PHASE 9: FINAL SYNTHESIS
===============================================================

**Step 9.1: COMPILE THE EVIDENCE**

FOR:
- Real UAF: `bt_adapter` published, object freed, later detach/recv uses
  it.
- Confirmed in *this* 6.12.111 tree; introducing commit is an ancestor.
- Multiple concrete deinit paths match the message; `rsi_91x_deinit()`
  is another.
- Attach failure is ignored (`rsi_attach_bt` only logs), so the device
  stays up with a dangling pointer.
- 3-line, obviously correct, Bluetooth maintainer applied it, BlueZ CI
  passed.
- Applies cleanly here; no prerequisites.
- UAF is a standard stable-worthy class.

AGAINST:
- Niche driver (Redpine RSI), not core mm/net.
- Primary trigger is an HCI alloc/register *failure*, not the happy
  path.
- No syzbot/user crash report; found by code inspection.
- No Fixes:/Cc: stable (expected; not a negative).
- No extra human Reviewed-by beyond maintainer application.

UNRESOLVED:
- No stable-list history found (lore.kernel.org 403; search noise).
- Could not walk descendants of `17abcfc57c8a` without forbidden
  `--all`; no evidence of a follow-up is needed for this standalone
  reorder.

**Step 9.2: APPLY THE STABLE RULES CHECKLIST**
1. Obviously correct and tested? **PASS** — lifetime reorder; applied by
   Luiz; CI PASS.
2. Fixes a real bug that affects users? **PASS** — UAF on RSI BT+WiFi
   coexistence after failed HCI attach, then unplug/shutdown/hibernate
   or further BT RX.
3. Important issue? **PASS** — UAF / crash (HIGH). Not a style change.
4. Small and contained? **PASS** — 3 lines, one function, one file.
5. No new features or APIs? **PASS**.
6. Can apply to the local tree? **PASS** — `git apply --check`
   succeeded.

**Step 9.3: CHECK FOR EXCEPTION CATEGORIES**
Record: Not a device-ID/quirk/DT/build/docs exception. It qualifies as a
normal UAF bug fix.

**Step 9.4: MAKE YOUR DECISION**
This is a small, correct UAF fix for code that has been in tree since
v4.17 and is still buggy in 6.12.111. Benefit outweighs risk.

------------------------------------------------
What the commit solves for stable users
------------------------------------------------
On RSI 91x BT+WiFi coexistence, a failed HCI attach currently leaves
`common->bt_adapter` pointing at freed memory. Later disconnect,
shutdown, freeze, deinit, or even the next BT packet will use that
pointer. Moving `set_bt_context()` until after successful
`hci_register_dev()` keeps `bt_adapter` NULL on failure so those paths
skip detach/recv.

It meets stable rules: real UAF, small, no new API, applies cleanly, low
regression risk.

------------------------------------------------
Verification
------------------------------------------------
- [Phase 1] `git describe HEAD` / `make kernelversion`:
  `p-6.12-3-g710455e2077bb`, **6.12.111**, branch `pending-6.12`.
- [Phase 1] Parsed tags: author + Luiz SOBs only; no Fixes/Reported-
  by/Cc: stable.
- [Phase 2] Actual upstream commit `17abcfc57c8a`: +2/−1 in
  `rsi_hci_attach()`; candidate dump’s `kzalloc_obj` is surrounding
  mainline context, not the fix.
- [Phase 3] `git blame drivers/bluetooth/btrsi.c` lines 109–154:
  `38aa4da504837` (v4.17-rc1).
- [Phase 3] `git merge-base --is-ancestor 38aa4da504837 HEAD`: yes. `git
  merge-base --is-ancestor 17abcfc57c8a HEAD`: no (fix not in this
  tree).
- [Phase 3] No related `set_bt_context` history in this tree.
- [Phase 4] `b4 dig -c 17abcfc57c8a`: lore msgid
  `20260722083136.175650-1-chenchangcheng@kylinos.cn`; v1 only; To
  Luiz/Marcel.
- [Phase 4] Saved mbox: CI PASS; patchwork-bot applied by Luiz; no NAK.
- [Phase 4] lore.kernel.org WebFetch 403; spinics 500 — used b4 mbox
  instead.
- [Phase 5] Callers verified in `rsi_91x_main.c`, `rsi_91x_mgmt.c`,
  `rsi_91x_sdio.c`, `rsi_91x_usb.c`; `rsi_set_bt_context()` writes
  `common->bt_adapter`.
- [Phase 6] Buggy `set_bt_context` still at line 120 of this tree’s
  `btrsi.c`.
- [Phase 6] `git apply --check` of `17abcfc57c8a`: succeeded (offset
  10).
- [Phase 7] `CONFIG_RSI_COEX` default y in
  `drivers/net/wireless/rsi/Kconfig`.
- [Phase 8] Failure mode: UAF → oops / memory safety, severity HIGH;
  trigger is attach-failure then deinit/RX.
- UNVERIFIED: later mainline follow-ups after `17abcfc57c8a` (no
  `--all`); no stable-list discussion.

**YES**

 drivers/bluetooth/btrsi.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/drivers/bluetooth/btrsi.c b/drivers/bluetooth/btrsi.c
index 6c1f584c8a337..0e2894e93e82e 100644
--- a/drivers/bluetooth/btrsi.c
+++ b/drivers/bluetooth/btrsi.c
@@ -117,7 +117,6 @@ static int rsi_hci_attach(void *priv, struct rsi_proto_ops *ops)
 		return -ENOMEM;
 
 	h_adapter->priv = priv;
-	ops->set_bt_context(priv, h_adapter);
 	h_adapter->proto_ops = ops;
 
 	hdev = hci_alloc_dev();
@@ -146,6 +145,8 @@ static int rsi_hci_attach(void *priv, struct rsi_proto_ops *ops)
 		goto err;
 	}
 
+	ops->set_bt_context(priv, h_adapter);
+
 	return 0;
 err:
 	h_adapter->hdev = NULL;
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH AUTOSEL 6.18] Bluetooth: bfusb: validate received block boundaries
       [not found] <20261019135441.1420968-1-sashal@kernel.org>
  2026-10-19 13:45 ` [PATCH AUTOSEL 6.18-6.1] Bluetooth: hci_event: fix out-of-bounds read in LE PA report reassembly Sasha Levin
  2026-10-19 13:45 ` [PATCH AUTOSEL 6.18-5.10] Bluetooth: btrsi: Move set_bt_context after successful HCI registration Sasha Levin
@ 2026-10-19 13:47 ` Sasha Levin
  2026-10-19 13:48 ` [PATCH AUTOSEL 6.18-5.15] Bluetooth: btusb: Add support for 1357:c123 Realtek 8852BE device Sasha Levin
                   ` (6 subsequent siblings)
  9 siblings, 0 replies; 10+ messages in thread
From: Sasha Levin @ 2026-10-19 13:47 UTC (permalink / raw)
  To: patches, stable
  Cc: Li Qiang, Luiz Augusto von Dentz, Sasha Levin, marcel, luiz.dentz,
	linux-bluetooth, linux-kernel

From: Li Qiang <liqiang01@kylinos.cn>

[ Upstream commit 6afadcff79b157a4770c4e987a6005bff40a670b ]

The USB receive path trusts the block header to contain the required
number of bytes and passes it to the reassembly routine. The routine
also trusts a malformed HCI packet type and can append more data than
the skb allocated from the advertised packet length. A malformed USB
transfer can therefore cause out-of-bounds reads or an skb tail
overwrite.

Validate block header availability, declared block size, packet type,
and reassembly tailroom. Drop the partial frame on an invalid block.

Signed-off-by: Li Qiang <liqiang01@kylinos.cn>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
Signed-off-by: Sasha Levin <sashal@kernel.org>
---

LLM Generated explanations, may be completely bogus:

The local tree is **6.18.53** (`pending-6.18`). The buggy `bfusb`
receive path is present here; the fix is not. This is a real USB OOB /
`skb_over_panic` bug, and the patch applies cleanly.

---

## PHASE 1: COMMIT MESSAGE FORENSICS

**Step 1.1: PARSE THE SUBJECT LINE**

Record: **[Bluetooth/bfusb] [validate] [check USB block headers and
reassembly bounds before trusting them]**

- Subsystem prefix: `Bluetooth: bfusb:`
- Action verb: **validate** (safety check / missing bounds handling)
- Claimed intent: stop treating untrusted USB block headers as valid
  lengths

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**

Record (from the candidate message and from `git show b94bab6f1dd9`):

- `Signed-off-by: Li Qiang <liqiang01@kylinos.cn>` — author
- `Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>` —
  Bluetooth maintainer; applied to bluetooth-next
- No `Fixes:` tag (expected)
- No `Cc: stable@vger.kernel.org` (expected)
- No `Reported-by:` / `Tested-by:` / `Reviewed-by:` / `Acked-by:` /
  `Link:`
- Ignore any pipeline `Signed-off-by: Sasha Levin` / `[Upstream commit
  ...]` markers

Notable pattern: maintainer SOB only; no syzbot/user report. The same
driver already had a `Cc: stable` USB-descriptor panic fix
(`b5e6fa7a12572`, division by zero on malicious `wMaxPacketSize`).

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**

Record:

- **Bug:** USB RX trusts the 2/3-byte block header and HCI packet type.
  Reassembly then copies `len` bytes into an skb sized from the
  advertised HCI length, with no tailroom check.
- **Symptom:** out-of-bounds URB reads and skb tail overwrite
  (`skb_put()` → `skb_over_panic()` → `BUG()`).
- **Version info:** none in the message. Blame shows the logic dates to
  `1da177e4c3f41` (Linux-2.6.12-rc2).
- **Root cause (author):** malformed USB transfer; missing validation of
  header availability, declared size, packet type, and reassembly
  tailroom. Invalid blocks should drop the partial frame.

**Step 1.4: DETECT HIDDEN BUG FIXES**

Record: **Not a hidden/cleanup-only change.** The subject is “validate”,
but the body names OOB reads and skb overwrite. The diff adds bounds
checks, a `default:` reject, and `break` on short/oversize blocks. This
is an explicit memory-safety fix.

---

## PHASE 2: DIFF ANALYSIS

**Step 2.1: INVENTORY THE CHANGES**

Record:

- File: `drivers/bluetooth/bfusb.c` only
- Scope: **+34 / −3**, single-file surgical fix
- Functions: `bfusb_recv_block()`, `bfusb_rx_complete()`

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**

Record (before → after), verified against current `bfusb.c` in this
tree:

1. **Unknown HCI packet type (start block):** `switch` has EVENT/ACL/SCO
   only, no `default`. `pkt_len` stays **0**. Code allocates
   `bt_skb_alloc(0)`, then `skb_put_data(..., len)` with the remaining
   block. → **`default:` returns `-EILSEQ`** before alloc.
2. **Reassembly copy:** any continuation (or start payload) is copied
   with `skb_put_data` with no tailroom check. → **if `len >
   skb_tailroom(reassembly)`, free skb, return `-EILSEQ`**.
3. **Block header parse loop:** `while (count)` always does `hdr =
   buf[0] | (buf[1] << 8)` and, unless bit `0x4000`, `buf[2]`. No `count
   >= 2` / `count >= 3` checks. → **short-header checks; drop reassembly
   and `break`**.
4. **`count < len`:** only logs `"block extends over URB buffer
   ranges"`, then still calls `bfusb_recv_block` and does `count -=
   len`. → **free reassembly and `break`**.
5. **Error accounting:** `bfusb_recv_block` return was ignored. → **on
   `< 0`, `data->hdev->stat.err_rx++`**.

**Step 2.3: IDENTIFY THE BUG MECHANISM**

Record: **[Memory safety: OOB read + skb overflow panic] [plus infinite
loop in URB complete]**

Verified mechanism in this tree:

```355:376:drivers/bluetooth/bfusb.c
        while (count) {
                hdr = buf[0] | (buf[1] << 8);
                ...
                        len = (buf[2] == 0) ? 256 : buf[2];
                ...
                if (count < len)
                        bt_dev_err(data->hdev, "block extends over URB
buffer ranges");

                if ((hdr & 0xe1) == 0xc1)
                        bfusb_recv_block(data, hdr, buf, len);

                count -= len;
                buf   += len;
        }
```

- `count` is `int urb->actual_length`. If `count < len`, `count -= len`
  goes **negative**. `while (count)` is then true forever → **hard
  lockup in USB completion**.
- `skb_put_data()` calls `skb_put()`, which panics if `skb->tail >
  skb->end`:

```2574:2592:net/core/skbuff.c
 - This function extends the used data area of the buffer. If this would
 - exceed the total buffer size the kernel will panic.
...
        if (unlikely(skb->tail > skb->end))
                skb_over_panic(skb, len, __builtin_return_address(0));
```

`skb_over_panic()` → `skb_panic()` → `BUG()`.

Unknown packet type: `pkt_len` initialized to 0, no `default`, then
`bt_skb_alloc(0)` and `skb_put_data` of the rest of the block → same
panic.

**Step 2.4: ASSESS THE FIX QUALITY**

Record:

- **Quality:** obviously correct. Same pattern as existing
  `skb_tailroom` checks in `btusb.c` / `hci_h4.c`.
- **Minimal:** only RX validation and error accounting; no API/structure
  changes.
- **Regression risk: low.** `default:` cannot reject ISO
  (`HCI_ISODATA_PKT` 0x05) on this 2003-era AVM dongle (VID `0x057c`,
  PID `0x2200`); previously unknown types already panicked. Short-header
  `break` only stops already-corrupt URBs. `kfree_skb(NULL)` is safe if
  `reassembly` is already NULL.
- **Red flags:** labeled `[PATCH 1/5]`, but the other four patches touch
  **different files** (`btmrvl`, `hci_bcsp`, `hci_ldisc`, `hci_qca`).
  This one is standalone.

---

## PHASE 3: GIT HISTORY INVESTIGATION

**Step 3.1: BLAME THE CHANGED LINES**

Record:

- Core RX loop / `bfusb_recv_block`: `1da177e4c3f41` (Linus, 2005-04-16,
  Linux-2.6.12-rc2)
- Function split/cleanup: `9c724357f432df` (Marcel Holtmann, 2006)
- `skb_put_data`: `59ae1d127ac0ae` (2017) — same overflow semantics as
  old `skb_put`+`memcpy`
- `bt_dev_err` conversion: `2a4f3909d0fbda` (2020)
- Brace removal on the `count < len` log: `461159ece0586` (2025) — style
  only; did **not** add a `break`

Buggy pattern has been in the tree for ~20 years.

**Step 3.2: FOLLOW THE FIXES: TAG**

Record: **No `Fixes:` tag.** Introducer is `1da177e4c3f41`, which **is**
an ancestor of this tree (`git merge-base --is-ancestor 1da177e4c3f41
HEAD` succeeded).

Related unmerged attempt: Seungjin Bae, Oct 2025, “Fix buffer over-read
in rx processing loop” — only the `count < 3` / `buf[2]` case. Not in
this tree. This commit is a superset.

**Step 3.3: CHECK FILE HISTORY**

Record (recent `git log --oneline -20 -- drivers/bluetooth/bfusb.c`):

- `b5e6fa7a12572` — `bfusb: fix division by zero in send path` (`Cc:
  stable`, malicious USB descriptors)
- `461159ece0586` — brace style on the exact `count < len` line
- No existing bounds-check fix for this RX loop

Standalone: yes. Series mates are other drivers.

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**

Record: Li Qiang has **no** other `drivers/bluetooth/` commits on this
branch. Luiz von Dentz is a Bluetooth maintainer (`MAINTAINERS`:
BLUETOOTH DRIVERS / SUBSYSTEM) and applied the patch to bluetooth-next
(commit date Mon Jul 20 2026).

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS**

Record: **None required.** Uses existing `skb_tailroom`, `bt_skb_alloc`,
`bt_dev_err`, `kfree_skb`. `git show b94bab6f1dd9 --
drivers/bluetooth/bfusb.c | git apply --check` → **clean apply**.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**

Record:

- `b4 dig -c b94bab6f1dd9`: https://patch.msgid.link/1f79f2f12306c15d6f6
  86348bb79d8e6839968d2.1784191283.git.liqiang01@kylinos.cn
- Cover: `[PATCH 0/5] Bluetooth: harden packet and transport parsing`
  (2026-07-16)
- `b4 dig -a`: **v1 only**; applied as submitted
- Applied to bluetooth-next as `b94bab6f1dd9` by Luiz (patchwork-bot,
  2026-07-20)
- Networking pull for **7.3** (Jakub Kicinski, 2026-08-18) — **not** in
  6.18
- No NAK on this patch. Samsung review (`0eec0c0d-636b-...`) is about
  **patch 2/5 `btmrvl`**, not bfusb.

**Step 4.2: CHECK WHO REVIEWED THE PATCH**

Record (`b4 dig -w`): `linux-bluetooth@vger.kernel.org`, Marcel
Holtmann, Luiz von Dentz, LKML. Maintainer applied it. No extra
Reviewed-by on this hunk.

**Step 4.3: SEARCH FOR THE BUG REPORT**

Record: no syzbot/bugzilla/`Reported-by`. Independent earlier report:
Seungjin Bae described the `buf[2]` over-read / panic (Oct 2025).
Trigger is a malformed USB bulk IN, not a syscall fuzzer.

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**

Record: 5 independent driver hardenings. Patch 1/5 is self-contained.
Patch 5/5 (`hci_qca`) was **not** applied. No bfusb follow-up found.

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**

Record: lore.kernel.org/stable search for this subject did not turn up a
prior stable discussion or a reason to skip it. UNVERIFIED in the sense
that lore.kernel.org itself returned 403; used mirrors + web search
instead.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

**Step 5.1: KEY FUNCTIONS**

Record: `bfusb_recv_block()`, `bfusb_rx_complete()`.

**Step 5.2: TRACE CALLERS**

Record:

- `bfusb_recv_block` — only from `bfusb_rx_complete`
- `bfusb_rx_complete` — URB complete from `bfusb_rx_submit()`
  (`usb_fill_bulk_urb(..., bfusb_rx_complete, skb)`)
- `bfusb_rx_submit` — `bfusb_open()` (HCI start) and resubmit in
  `bfusb_rx_complete`

Context: USB completion (atomic/BH). An infinite `while (count)` here is
a **hard lockup**, not a sleepable hang.

**Step 5.3: TRACE CALLEES**

Record: `bt_skb_alloc`, `skb_put_data`/`skb_put`, `hci_recv_frame`,
`kfree_skb`, `usb_submit_urb`. No new callees in the fix (`skb_tailroom`
is an existing inline).

**Step 5.4: FOLLOW THE CALL CHAIN**

Record:

USB plug of `0x057c:0x2200` → `bfusb_probe` → BlueZ opens HCI →
`bfusb_open` → bulk IN URBs → `bfusb_rx_complete`.

Reachable from: a matching (or spoofed) USB device plus HCI running. Not
a random syscall; **local USB attack surface**, same class as the prior
`Cc: stable` bfusb descriptor fix.

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**

Record: `btusb.c`, `hci_h4.c`, `btmtk.c` already check `skb_tailroom`
before appending. `err_rx++` on parse failure is standard (`btusb`,
`btsdio`, `bpa10x`, …). bfusb was missing both.

---

## PHASE 6: CROSS-REFERENCING AGAINST THE LOCAL TREE

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?**

Record: **Yes.** `drivers/bluetooth/bfusb.c` still has the unvalidated
loop and no `default:` / tailroom check (lines 245–376). `git describe
HEAD` = `p-6.18-1-g03b85e06ca9bf`; `make kernelversion` = **6.18.53**.
`git merge-base --is-ancestor b94bab6f1dd9 HEAD` → **not in this tree**.
Introduced in 2.6.12-rc2; present for the entire 6.18 lifetime.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**

Record: **Clean apply.** `git apply --check` on the exact commit diff
succeeded. Surrounding code matches the hunks (including
post-`461159ece0586` braceless `if (count < len)`).

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**

Record: Seungjin Bae over-read patch is **not** here. No other RX-bounds
fix in this file. The send-path div-by-zero fix **is** here; it does not
cover this RX bug.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

**Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY**

Record: **Bluetooth USB driver (`drivers/bluetooth/bfusb.c`)**.
Criticality: **PERIPHERAL** hardware (AVM BlueFRITZ! USB only), but the
failure is a **kernel panic / lockup** on untrusted USB data. Kconfig:
`BT_HCIBFUSB`, depends on USB. Enabled as `=m` in several defconfigs
(e.g. `omap2plus`, `exynos`, `loongson3`, `pmac32`).

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**

Record: Bluetooth core is active; **bfusb itself is mature/mostly
idle**. Recent file commits are isolated fixes/style. Long-lived bug,
not churn from a new feature.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

**Step 8.1: WHO IS AFFECTED**

Record: **driver-specific** — AVM BlueFRITZ! USB (`USB_DEVICE(0x057c,
0x2200)`), plus any system with the module that binds a spoofed VID/PID.
Not universal.

**Step 8.2: TRIGGER CONDITIONS**

Record:

- Requires this driver bound and HCI running (`HCI_RUNNING`).
- Trigger: truncated/malformed bulk IN (device bug, USB fuzzing,
  malicious dongle).
- Not a normal healthy-traffic path.
- Unprivileged userspace cannot hit it without the device; a **USB
  attacker** can.

**Step 8.3: FAILURE MODE SEVERITY**

Record:

- `skb_put` overflow → `skb_over_panic` → **`BUG()` / panic** —
  **CRITICAL**
- `while (count)` with negative `count` → **infinite loop in URB
  complete** — **CRITICAL**
- Short-header `buf[0]/buf[1]/buf[2]` — **OOB read** — **HIGH**

**Step 8.4: RISK-BENEFIT RATIO**

Record:

- **Benefit: high for affected systems** (panic/lockup prevention).
  Population is small, but the same driver already got stable treatment
  for malicious USB descriptors.
- **Risk: very low** — 37-line, single-file, validated by maintainer,
  applies cleanly, error-path only.
- **Ratio: favor backport.**

---

## PHASE 9: FINAL SYNTHESIS

**Step 9.1: COMPILE THE EVIDENCE**

**FOR:**

- Real OOB read + `skb` overflow `BUG()` + possible hard lockup,
  verified in this tree’s code
- Bug present since 2.6.12; definitely in 6.18.53
- Small, obviously correct, no new APIs
- Applies cleanly; no prerequisites
- Bluetooth maintainer applied it
- Same driver already had a stable USB-malice panic fix
- Independent of the rest of the 5-patch series

**AGAINST:**

- Niche 2000s dongle; few users
- No syzbot / production `Reported-by`
- Series framed as “harden”
- Patch 2/5 (`btmrvl`) later needed a fix — **does not apply to this
  file**

**UNRESOLVED:**

- Could not fetch lore.kernel.org directly (403); used `b4 dig` +
  mirrors
- No scan of every post-`b94bab6f1dd9` bluetooth-next follow-up (object
  is not on HEAD); no evidence of a bfusb revert/fixup

**Step 9.2: STABLE RULES CHECKLIST**

1. Obviously correct and tested? **PASS** — maintainer-applied; logic
   matches existing Bluetooth RX checks
2. Fixes a real bug that affects users? **PASS** — malformed USB RX
   panics/lockups this driver
3. Important issue? **PASS** — kernel `BUG()` / hard lockup / OOB
   (CRITICAL), even though the driver is niche
4. Small and contained? **PASS** — +34/−3, one file
5. No new features or APIs? **PASS**
6. Can apply to the local tree? **PASS** — `git apply --check`
   succeeded; buggy code present; fix not present

**Step 9.3: EXCEPTION CATEGORIES**

Record: none (not a device ID / quirk / DT / build / doc exception).
Qualifies as a **normal memory-safety bug fix**.

**Step 9.4: DECISION**

Backport to **this** 6.18.53 tree. The receive path here still trusts
USB block lengths; that can panic or lock up the USB completion path.
The fix is surgical and already matches this file.

### What the commit solves for stable users

On AVM BlueFRITZ! USB (or a spoofed `057c:2200`), a short or lying block
header can over-read the URB buffer, `skb_put()` past the reassembled
HCI skb (`BUG()`), or drive `count` negative and spin forever in
`bfusb_rx_complete`. This tree still has that code. The patch only adds
header/size/type/tailroom checks and drops the partial frame.

### Risk vs benefit

Benefit is preventing panic/lockup on untrusted USB RX. Risk is low:
error-path validation, no locking/API change, clean apply. Niche
hardware lowers breadth of impact but does not make a USB-triggered
`BUG()` unsuitable for stable.

---

## Verification

- **[Phase 1]** Parsed subject/body/tags from the candidate text and
  `git show b94bab6f1dd9`; no Fixes/Cc:stable/Reported-by; Luiz SOB
  confirmed
- **[Phase 2]** Read `bfusb_recv_block` / `bfusb_rx_complete` in this
  tree; confirmed missing `default`, no tailroom check, log-only `count
  < len`, signed `count` loop
- **[Phase 2]** Read `skb_put` / `skb_put_data` / `skb_panic`: overflow
  → `BUG()`
- **[Phase 3]** `git blame` on both functions: core logic
  `1da177e4c3f41` (2.6.12-rc2)
- **[Phase 3]** `git merge-base --is-ancestor 1da177e4c3f41 HEAD` —
  introducer in this tree
- **[Phase 3]** `git merge-base --is-ancestor b94bab6f1dd9 HEAD` — fix
  **not** in this tree (exit 1)
- **[Phase 3]** `git log --oneline -20 -- drivers/bluetooth/bfusb.c` —
  no prior RX-bounds fix; `b5e6fa7a12572` is a different (send-path) USB
  panic
- **[Phase 4]** `b4 dig -c b94bab6f1dd9` — lore msgid
  `1f79f2f12306c15d6f686348bb79d8e6839968d2.1784191283`
- **[Phase 4]** `b4 dig -a` — v1 only
- **[Phase 4]** `b4 dig -w` — linux-bluetooth, Holtmann, von Dentz
- **[Phase 4]** Cover letter / patchwork-bot: applied to bluetooth-next
  2026-07-20; networking pull for 7.3
- **[Phase 4]** Samsung mail is about `btmrvl` 2/5, not this patch
- **[Phase 5]** Callers: only URB complete ← `bfusb_rx_submit` ←
  `bfusb_open` / resubmit
- **[Phase 5]** `git grep skb_tailroom` in `drivers/bluetooth` — sibling
  drivers already check
- **[Phase 6]** `git describe HEAD` / `make kernelversion`: 6.18.53;
  `grep` found no “block exceeds packet length” in this tree
- **[Phase 6]** `git apply --check` of `b94bab6f1dd9` — success
- **[Phase 7]** Kconfig `BT_HCIBFUSB`; MAINTAINERS lists Luiz;
  defconfigs enable it as a module
- **[Phase 8]** Failure mode verified: panic (`BUG`) and infinite URB-
  complete loop
- **UNVERIFIED:** direct lore.kernel.org HTTP (403); exhaustive post-
  merge bfusb follow-ups on branches not in HEAD

**YES**

 drivers/bluetooth/bfusb.c | 37 ++++++++++++++++++++++++++++++++++---
 1 file changed, 34 insertions(+), 3 deletions(-)

diff --git a/drivers/bluetooth/bfusb.c b/drivers/bluetooth/bfusb.c
index 8df310983bf6b..d31d797639b51 100644
--- a/drivers/bluetooth/bfusb.c
+++ b/drivers/bluetooth/bfusb.c
@@ -301,6 +301,11 @@ static inline int bfusb_recv_block(struct bfusb_data *data, int hdr, unsigned ch
 				return -EILSEQ;
 			}
 			break;
+
+		default:
+			bt_dev_err(data->hdev, "unknown packet type 0x%02x",
+				   pkt_type);
+			return -EILSEQ;
 		}
 
 		skb = bt_skb_alloc(pkt_len, GFP_ATOMIC);
@@ -319,6 +324,13 @@ static inline int bfusb_recv_block(struct bfusb_data *data, int hdr, unsigned ch
 		}
 	}
 
+	if (len > skb_tailroom(data->reassembly)) {
+		bt_dev_err(data->hdev, "block exceeds packet length");
+		kfree_skb(data->reassembly);
+		data->reassembly = NULL;
+		return -EILSEQ;
+	}
+
 	if (len > 0)
 		skb_put_data(data->reassembly, buf, len);
 
@@ -353,6 +365,13 @@ static void bfusb_rx_complete(struct urb *urb)
 	skb_put(skb, count);
 
 	while (count) {
+		if (count < 2) {
+			bt_dev_err(data->hdev, "short block header");
+			kfree_skb(data->reassembly);
+			data->reassembly = NULL;
+			break;
+		}
+
 		hdr = buf[0] | (buf[1] << 8);
 
 		if (hdr & 0x4000) {
@@ -360,16 +379,28 @@ static void bfusb_rx_complete(struct urb *urb)
 			count -= 2;
 			buf   += 2;
 		} else {
+			if (count < 3) {
+				bt_dev_err(data->hdev, "short block header");
+				kfree_skb(data->reassembly);
+				data->reassembly = NULL;
+				break;
+			}
+
 			len = (buf[2] == 0) ? 256 : buf[2];
 			count -= 3;
 			buf   += 3;
 		}
 
-		if (count < len)
+		if (count < len) {
 			bt_dev_err(data->hdev, "block extends over URB buffer ranges");
+			kfree_skb(data->reassembly);
+			data->reassembly = NULL;
+			break;
+		}
 
-		if ((hdr & 0xe1) == 0xc1)
-			bfusb_recv_block(data, hdr, buf, len);
+		if ((hdr & 0xe1) == 0xc1 &&
+		    bfusb_recv_block(data, hdr, buf, len) < 0)
+			data->hdev->stat.err_rx++;
 
 		count -= len;
 		buf   += len;
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH AUTOSEL 6.18-5.15] Bluetooth: btusb: Add support for 1357:c123 Realtek 8852BE device
       [not found] <20261019135441.1420968-1-sashal@kernel.org>
                   ` (2 preceding siblings ...)
  2026-10-19 13:47 ` [PATCH AUTOSEL 6.18] Bluetooth: bfusb: validate received block boundaries Sasha Levin
@ 2026-10-19 13:48 ` Sasha Levin
  2026-10-19 13:48 ` [PATCH AUTOSEL 6.18-5.10] Bluetooth: hci_bcsp: validate received packet lengths Sasha Levin
                   ` (5 subsequent siblings)
  9 siblings, 0 replies; 10+ messages in thread
From: Sasha Levin @ 2026-10-19 13:48 UTC (permalink / raw)
  To: patches, stable
  Cc: Pavel Zverev, Luiz Augusto von Dentz, Sasha Levin, marcel,
	luiz.dentz, linux-bluetooth, linux-kernel

From: Pavel Zverev <playximik29@gmail.com>

[ Upstream commit 335d7bd554a20f33acf762655cafe1089f7f5822 ]

Wiko Hi MateBook 14 Ryzen 200 laptops (DMI system-product-name
"MNCA-XX", board "M1060") are equipped with an RTL8852BE Wi-Fi/BT
combo chip (rtw89_8852be), whose Bluetooth radio enumerates as
1357:c123 instead of one of the already-supported 1358:c123 / 0bda:c123
identifiers, presumably due to OEM rebranding. Without a matching
entry it only matches the generic USB Bluetooth class fallback, so the
Realtek firmware/config (rtl8852btu_fw.bin / rtl8852btu_config.bin) is
never loaded and the adapter cannot discover or connect to any device,
even though hciconfig reports it as powered and scanning.

Device descriptor:
  idVendor           0x1357
  idProduct          0xc123
  bcdDevice            0.00
  iManufacturer           1 Realtek
  iProduct                2 Bluetooth Radio
  bDeviceClass          224 Wireless
  bDeviceSubClass         1 Radio Frequency
  bDeviceProtocol         1 Bluetooth

Adding the same BTUSB_REALTEK | BTUSB_WIDEBAND_SPEECH quirk already
used for 1358:c123 and 0bda:c123 fixes firmware loading and normal
operation.

Signed-off-by: Pavel Zverev <playximik29@gmail.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
Signed-off-by: Sasha Levin <sashal@kernel.org>
---

LLM Generated explanations, may be completely bogus:

This is a two-line USB ID addition for an existing Realtek path in
`btusb`. The 6.18.53 tree already has that path and the sibling IDs;
this OEM VID is missing, so Bluetooth never loads firmware on the
affected laptop.

## Phase 1: Commit message forensics

**Step 1.1 — Subject**
Record: `[Bluetooth/btusb] [Add] USB ID 1357:c123 for Realtek 8852BE
(OEM rebrand of known c123 devices)`

**Step 1.2 — Tags**
Record:
- Signed-off-by: Pavel Zverev \<playximik29@gmail.com\> (author)
- Signed-off-by: Luiz Augusto von Dentz \<luiz.von.dentz@intel.com\>
  (Bluetooth maintainer; applied the patch)
- No Fixes:, Reported-by:, Tested-by:, Reviewed-by:, Acked-by:, Link:,
  or Cc: stable (absence of Fixes/Cc:stable is expected for this review
  queue)

**Step 1.3 — Body**
Record:
- Bug: Wiko Hi MateBook 14 Ryzen 200 (DMI `"MNCA-XX"` / board `"M1060"`)
  has RTL8852BE (Wi-Fi `rtw89_8852be`). BT enumerates as **1357:c123**
  instead of already-supported **1358:c123** / **0bda:c123**.
- Symptom: generic USB Bluetooth class match only; `rtl8852btu_fw.bin` /
  `rtl8852btu_config.bin` never load; adapter appears powered/scanning
  but cannot discover or connect.
- Root cause: missing `quirks_table` entry so `BTUSB_REALTEK` is never
  applied.
- Descriptor: vendor 0x1357, product 0xc123, class 224/1/1, manufacturer
  “Realtek”.
- Fix: same `BTUSB_REALTEK | BTUSB_WIDEBAND_SPEECH` flags as the sibling
  IDs.

**Step 1.4 — Hidden bug fix?**
Record: Not hidden. It is an explicit hardware-enablement / device-ID
quirk. Bluetooth is non-functional without it.

## Phase 2: Diff analysis

**Step 2.1 — Inventory**
Record: `drivers/bluetooth/btusb.c` only; **+2 / -0** lines; table
`quirks_table[]`; single-file surgical change.

**Step 2.2 — Flow**
Record: After `{ USB_DEVICE(0x0bda, 0xc123), ... }` insert `{
USB_DEVICE(0x1357, 0xc123), .driver_info = BTUSB_REALTEK |
BTUSB_WIDEBAND_SPEECH }`. Probe path only; no error-path or locking
change.

**Step 2.3 — Bug mechanism**
Record: **Hardware workaround / device ID** (stable exception). Without
the ID:
1. Device matches generic `{ USB_DEVICE_INFO(0xe0, 0x01, 0x01) }` in
   `btusb_table` with `driver_info == 0`.
2. `btusb_probe()` then calls `usb_match_id(intf, quirks_table)`.
3. No match → no `BTUSB_REALTEK` → `hdev->setup` is not
   `btusb_setup_realtek` → no `btrtl_download_firmware()`.

Firmware is chosen later by chip identity (`btrtl_match_ic()` on LMP/HCI
rev), not by USB PID, so this ID only gates the Realtek setup path.

**Step 2.4 — Fix quality**
Record: Obviously correct copy of sibling entries. Scope is this VID:PID
only. Regression risk is negligible (wrong non-Realtek device with
1357:c123 is not plausible given the descriptor). No API/structure
change.

## Phase 3: Git history

**Step 3.1 — Blame**
Record: Neighbor IDs:
- `1358:c123` — `f496297e76a69` (Julian Pidancet, 2020) “Add support for
  1358:c123 Realtek 8822CE” (Huawei Matebook); contained in v5.11-rc1.
- `0bda:c123` — `24d6a6d24f01f` (Cadel Watson, 2020) “Support 0bda:c123
  Realtek 8822CE”; also v5.11-rc1.
The missing ID is new OEM VID 0x1357 with the same PID. Buggy “no
Realtek quirk” behavior has existed for this VID:PID for as long as the
device has existed; the table itself has been there since ~5.11.

**Step 3.2 — Fixes: tag**
Record: None. Not a regression from a specific commit; it is a missing
ID.

**Step 3.3 — File history**
Record: Recent `btusb.c` history in this tree includes many of the same
pattern (`Add Realtek RTL8922AE VID/PID 0bda/d923`, Mercusys/ASUS/TP-
Link IDs, several RTL8852BE IDs). Standalone; not “patch X/Y”.

**Step 3.4 — Author**
Record: Pavel Zverev has no other `drivers/bluetooth/` commits in this
tree. Applied by Luiz Augusto von Dentz (Bluetooth USB maintainer). Same
class of ID adds is routinely accepted.

**Step 3.5 — Dependencies**
Record: Needs existing `BTUSB_REALTEK` / `quirks_table` /
`btrtl_setup_realtek()` / RTL8852 firmware table. All are in this tree
(`1fb9943146968` RTL8852BT/8852BE-VT firmware matching is an ancestor of
HEAD). Standalone +2 lines.

## Phase 4: Mailing list

**Step 4.1 — Original discussion**
Record:
- SHA: `335d7bd554a20f33acf762655cafe1089f7f5822`
- `b4 dig -c`:
  https://patch.msgid.link/20260707221549.27269-1-playximik29@gmail.com
- `b4 dig -a`: **v1 only**, 2026-07-08, no later revision
- Thread: submission, BlueZ CI pass, patchwork-bot “applied to
  bluetooth-next”
- No NAK, no reviewer risk flags, no request for changes
- Applied to bluetooth-next as `1386e748cfc0`; later on master as
  `335d7bd554a20`

**Step 4.2 — Recipients (`b4 dig -w`)**
Record: To Marcel Holtmann, Luiz Dentz; Cc linux-bluetooth@. Correct
lists/maintainers. Luiz applied it.

**Step 4.3 — Bug report**
Record: No bugzilla/syzbot link. Author reports a specific laptop (DMI +
USB descriptor) and that adding the ID restored discovery/connect.
Direct user impact, one platform.

**Step 4.4 — Series**
Record: Single standalone patch. CI: CheckPatch, build, sparse all PASS
(Patchwork series 1123385).

**Step 4.5 — Stable list**
Record: lore.kernel.org HTTP 403 from WebFetch; WebSearch for stable
discussion failed. No local `git log --grep=1357:c123` hits. UNVERIFIED:
no evidence this was already discussed on stable@; that is not a
negative.

## Phase 5: Code semantics

**Step 5.1 — Functions**
Record: No function body change. Data: `quirks_table[]`. Consumers:
`btusb_probe()` via `usb_match_id()`.

**Step 5.2 — Callers**
Record: USB probe when a matching interface is enumerated. `btusb_table`
generic class entry binds first; then quirks_table supplies
`driver_info`. Not irq/syscall hot path; once per device bind.

**Step 5.3 — Callees**
Record: With the new flags, probe sets `hdev->setup =
btusb_setup_realtek` → `btrtl_setup_realtek()` → `btrtl_initialize()` /
`btrtl_download_firmware()`. Also `HCI_QUIRK_WIDEBAND_SPEECH_SUPPORTED`.
`CONFIG_BT_HCIBTUSB_RTL` defaults to y.

**Step 5.4 — Reachability**
Record: Yes, from plugging in / internal USB BT of that laptop.
Unprivileged users then use BlueZ; the bug is “adapter never works,” not
a crash.

**Step 5.5 — Similar patterns**
Record: Dozens of `BTUSB_REALTEK | BTUSB_WIDEBAND_SPEECH` IDs, including
other 8852BE VIDs (`0bda:4853`, `13d3:3618`, `0489:e123`, …). Sibling
`c123` IDs already present. Same fix applied many times.

## Phase 6: This tree (6.18.53)

**Step 6.1 — Does the buggy code exist?**
Record: Yes.
- Tree: `pending-6.18`, `git describe HEAD` = `p-6.18-1-g03b85e06ca9bf`,
  `make kernelversion` = **6.18.53**, merge-base with master = `Linux
  6.18` (2025-11-30).
- `git merge-base --is-ancestor 335d7bd554a20 HEAD` → **not in HEAD**.
- `1358:c123` and `0bda:c123` are at lines 877–880 of
  `drivers/bluetooth/btusb.c`; **1357:c123 is absent**.
- Realtek setup and `rtl8852btu_*` firmware names exist in `btrtl.c`.

The ID was added in mainline in Aug 2026, after 6.18; the **gap**
(missing ID) is in this tree. That is the usual device-ID backport case,
not “code not present.”

**Step 6.2 — Backport difficulty**
Record: `git show 335d7bd554a20 | git apply --check` succeeded (hunk at
line 878, offset -16). Clean apply, trivial offset.

**Step 6.3 — Related fixes already here?**
Record: No 1357:c123 entry. Other 8852BE IDs and firmware support are
already here; this does not duplicate them.

## Phase 7: Subsystem context

**Step 7.1**
Record: `drivers/bluetooth/btusb.c` — USB Bluetooth. **IMPORTANT** (very
common laptop combo chips), not core mm/vfs, not staging.

**Step 7.2**
Record: Actively maintained; this tree already backported many
`Bluetooth: btusb: Add ...` ID patches (e.g. `b85ef6483d5b3` RTL8922AE
0bda/d923). Mature table, ongoing OEM IDs.

## Phase 8: Impact and risk

**Step 8.1 — Who is affected**
Record: Driver + VID/PID specific. Users of 1357:c123, documented as
Wiko Hi MateBook 14 Ryzen 200. No effect on other devices.

**Step 8.2 — Trigger**
Record: Every boot / BT bring-up on that hardware. Not a race.
Unprivileged use of BT is broken until firmware loads.

**Step 8.3 — Failure mode**
Record: Adapter enumerates and looks “up” but cannot discover or
connect. Severity **HIGH** for that hardware (Bluetooth unusable), not a
panic. Device-ID exception still applies.

**Step 8.4 — Risk vs benefit**
Record:
- Benefit: high for affected laptops; zero for everyone else.
- Risk: very low (+2 lines, VID/PID gated, same flags as existing c123
  entries).
- Ratio: strongly in favor of backport.

## Phase 9: Synthesis

**Evidence FOR**
- Explicit stable exception: **new USB ID on an existing driver**.
- Real user-visible bug: BT cannot pair/connect without Realtek
  firmware.
- +2 lines, identical to 1358:c123 / 0bda:c123 already in 6.18.53.
- Applies cleanly; Realtek/8852 firmware path already present.
- Maintainer-applied; CI passed; no NAKs.
- This 6.18.y tree already takes the same class of ID adds.

**Evidence AGAINST**
- Not a crash/UAF/security issue (not required for device IDs).
- One OEM laptop family (still a real product).
- Author is not a regular Bluetooth contributor (offset by Luiz applying
  it).
- Sibling IDs were labeled 8822CE in 2020; this commit says 8852BE.
  Firmware is matched by chip ID after `BTUSB_REALTEK`, so a mis-named
  chip in the subject would still load the correct image. Author cites
  `rtl8852btu_*` from the working setup.

**Unresolved**
- Could not fetch lore/stable@ via HTTP (403). Thread recovered via `b4
  dig -m`.
- Did not independently attach the laptop; relied on author’s descriptor
  and “works after this ID.”

**Stable rules**
1. Obviously correct and tested? **PASS** (same flags as siblings;
   author + CI + maintainer).
2. Real bug affecting users? **PASS** (BT unusable on that hardware).
3. Important? **PASS** under the device-ID exception (hardware does not
   work).
4. Small and contained? **PASS** (+2 lines, one table).
5. No new features/APIs? **PASS** (existing quirk flags only).
6. Applies to this tree? **PASS** (`git apply --check` clean).

**Exception category:** NEW DEVICE ID on existing `btusb` / Realtek
path.

This should be backported to this 6.18.53 tree. The driver, Realtek
firmware loader, and sibling `c123` quirks are already here; only
1357:c123 is missing, and that is enough to leave this laptop’s
Bluetooth non-functional.

Verification:
- [Phase 1] Parsed subject/tags from `git show 335d7bd554a20`; no
  Fixes/Cc:stable; Luiz SOB present
- [Phase 2] Diff is +2 lines in `quirks_table`; confirmed
  `btusb_probe()` uses generic class match then `usb_match_id(...,
  quirks_table)` when `driver_info == 0` (btusb.c ~4064–4069, 82–83,
  4309–4312)
- [Phase 2] Firmware selected by `btrtl_match_ic()` /
  `btrtl_setup_realtek()`, not USB PID (`btrtl.c` 342–345, 1359–1368)
- [Phase 3] Blame: 1358:c123 = f496297e76a69, 0bda:c123 = 24d6a6d24f01f,
  both v5.11-rc1 and in this tree
- [Phase 3] `git merge-base --is-ancestor 335d7bd554a20 HEAD` → not in
  this tree
- [Phase 3] `git merge-base --is-ancestor 1fb9943146968 HEAD` →
  8852BT/BE-VT firmware support is in this tree
- [Phase 4] `b4 dig -c/-a/-w/-m`: v1, linux-bluetooth, Luiz applied, CI
  PASS, no NAK
- [Phase 4] lore WebFetch 403; stable@ search failed — UNVERIFIED beyond
  b4 mbox
- [Phase 5] `CONFIG_BT_HCIBTUSB_RTL` default y (Kconfig);
  `BTUSB_WIDEBAND_SPEECH` → `HCI_QUIRK_WIDEBAND_SPEECH_SUPPORTED`
  (btusb.c:4344)
- [Phase 6] `git describe HEAD` p-6.18-1-g03b85e06ca9bf; kernel 6.18.53;
  grep shows 1358/0bda:c123, not 1357:c123
- [Phase 6] `git apply --check` succeeded with offset -16
- [Phase 7/8] Same ID-add pattern already in this tree (e.g.
  b85ef6483d5b3)
- UNVERIFIED: physical confirmation of 8852BE vs 8822CE; does not change
  the ID-add decision because firmware is chip-matched

**YES**

 drivers/bluetooth/btusb.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/drivers/bluetooth/btusb.c b/drivers/bluetooth/btusb.c
index 9257341b01399..3c9d5d0976936 100644
--- a/drivers/bluetooth/btusb.c
+++ b/drivers/bluetooth/btusb.c
@@ -882,6 +882,8 @@ static const struct usb_device_id quirks_table[] = {
 						     BTUSB_WIDEBAND_SPEECH },
 	{ USB_DEVICE(0x0bda, 0xc123), .driver_info = BTUSB_REALTEK |
 						     BTUSB_WIDEBAND_SPEECH },
+	{ USB_DEVICE(0x1357, 0xc123), .driver_info = BTUSB_REALTEK |
+						     BTUSB_WIDEBAND_SPEECH },
 	{ USB_DEVICE(0x0cb5, 0xc547), .driver_info = BTUSB_REALTEK |
 						     BTUSB_WIDEBAND_SPEECH },
 
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH AUTOSEL 6.18-5.10] Bluetooth: hci_bcsp: validate received packet lengths
       [not found] <20261019135441.1420968-1-sashal@kernel.org>
                   ` (3 preceding siblings ...)
  2026-10-19 13:48 ` [PATCH AUTOSEL 6.18-5.15] Bluetooth: btusb: Add support for 1357:c123 Realtek 8852BE device Sasha Levin
@ 2026-10-19 13:48 ` Sasha Levin
  2026-10-19 13:48 ` [PATCH AUTOSEL 6.18-5.10] Bluetooth: hci_nokia: validate firmware packet bounds Sasha Levin
                   ` (4 subsequent siblings)
  9 siblings, 0 replies; 10+ messages in thread
From: Sasha Levin @ 2026-10-19 13:48 UTC (permalink / raw)
  To: patches, stable
  Cc: Li Qiang, Luiz Augusto von Dentz, Sasha Levin, marcel, luiz.dentz,
	linux-bluetooth, linux-kernel

From: Li Qiang <liqiang01@kylinos.cn>

[ Upstream commit ceea75ad8925425ee6520ead964b55888fe871ec ]

The BCSP transmit path reads an HCI command header when an extension
packet has only been tested for a nonzero length. Its LE configuration
packet handler also indexes bytes through offset seven without a length
check.

Validate the complete command and LE configuration packet headers
before accessing their fields.

Signed-off-by: Li Qiang <liqiang01@kylinos.cn>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
Signed-off-by: Sasha Levin <sashal@kernel.org>
---

LLM Generated explanations, may be completely bogus:

The local tree is **6.12.111** (`p-6.12-3-g710455e2077bb`). The buggy
BCSP length handling is in this checkout; the candidate is not. The
verdict is for this tree only.

===============================================================
PHASE 1: COMMIT MESSAGE FORENSICS
===============================================================

**Step 1.1: PARSE THE SUBJECT LINE**
Record: `[Bluetooth / hci_bcsp] [validate] [check command and LE-config
packet lengths before field access]`

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**
Record:
- `Signed-off-by: Li Qiang <liqiang01@kylinos.cn>` (author)
- `Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>`
  (Bluetooth maintainer)
- No `Fixes:`, `Reported-by:`, `Tested-by:`, `Reviewed-by:`, `Acked-
  by:`, `Link:`, or `Cc: stable@vger.kernel.org`
- Ignore pipeline `Signed-off-by: Sasha Levin` / `[Upstream commit ...]`
  markers
- Absence of `Fixes:`/`Cc: stable` is expected for this review and is
  **not** a negative signal

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**
Record:
- **Bug:** BCSP TX reads an HCI command header without a full-header
  length check; LE config RX indexes through offset 7 without a length
  check.
- **Symptom:** Out-of-bounds read of skb/payload bytes on truncated
  packets (cover letter: “out-of-bounds accesses … when data is
  truncated”).
- **Version info:** none in the commit; code dates to git origin (2005).
- **Root cause (author):** fields are used before the complete header is
  known to be present.

**Step 1.4: DETECT HIDDEN BUG FIXES**
Record: Not a disguised cleanup. It is a bounds-check / OOB fix, even
though the series is titled “harden packet and transport parsing.”

===============================================================
PHASE 2: DIFF ANALYSIS - LINE BY LINE
===============================================================

**Step 2.1: INVENTORY THE CHANGES**
Record:
- File: `drivers/bluetooth/hci_bcsp.c` only (`+4 / -1`)
- Functions: `bcsp_prepare_pkt()`, `bcsp_handle_le_pkt()`
- Scope: single-file surgical fix

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**
Record:
- **Hunk 1 (`bcsp_prepare_pkt`):** before: if `hciextn && chan == 5`,
  always read `hci_command_hdr.opcode` and `data[HCI_COMMAND_HDR_SIZE]`.
  after: only if `len > HCI_COMMAND_HDR_SIZE` (3). Short commands skip
  vendor-extension rewrite and are slipped as-is.
- **Hunk 2 (`bcsp_handle_le_pkt`):** before: `data[1]`, `data[2]`,
  `memcmp(&data[4], …, 4)` with no `skb->len` check. after: return if
  `rx_skb->len < 8`.

**Step 2.3: IDENTIFY THE BUG MECHANISM**
Record: **Memory safety / out-of-bounds read (category d).**
- TX: `HCI_COMMAND_HDR_SIZE` is 3. Userspace HCI sockets accept `len >=
  4` (1 type byte + 3-byte command). After `skb_pull(1)`, `skb->len` can
  be **exactly 3**. For vendor OGF `0x3f`, the driver then does `*(data
  + 3)` — one byte past `skb->len`.
- If that byte has high nibble `0xc0`, `len -= 4` makes `len == -1`, and
  the BCSP header is built with a bogus length (`hdr[1]/hdr[2]` from a
  signed `-1`).
- RX: `memcmp` of bytes 4–7 with no `len` check. The receive state
  machine normally makes that path in-bounds when the header length
  field is 4; the extra check is defensive.

**Step 2.4: ASSESS THE FIX QUALITY**
Record: Obviously correct and minimal. Skipping extension parsing on
short packets is the safe default. Early-return on short LE frames does
not drop valid conf/sync packets (those are 4-byte hdr + 4-byte payload
= 8). Regression risk is very low. No API/data-structure change.

===============================================================
PHASE 3: GIT HISTORY INVESTIGATION
===============================================================

**Step 3.1: BLAME THE CHANGED LINES**
Record: Buggy TX/RX logic is from `1da177e4c3f41` (Linux-2.6.12-rc2,
2005), with later style/API churn only (`c5ec514016d1a6`,
`8083ad1cf910dc`, `59ae1d127ac0ae`). Present for the entire life of this
driver, including 6.12.

**Step 3.2: FOLLOW THE FIXES: TAG**
Record: No `Fixes:` tag. Not applicable.

**Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES**
Record: Recent 6.12 BCSP work includes `b420a4c7f915f` (syzbot NULL
deref in `bcsp_recv`), timer/kfree fixes. No prior length check. This
commit is **standalone** (series 3/5; other patches touch `bfusb.c`,
`btmrvl_main.c`, `hci_ldisc.c`, `hci_qca.c`).

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**
Record: Li Qiang has no other `drivers/bluetooth/` commits in this 6.12
tree. Luiz von Dentz is a listed Bluetooth driver maintainer and applied
the series to bluetooth-next (`a4c72c8c7cef`).

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS**
Record: None. Uses existing `HCI_COMMAND_HDR_SIZE` and `rx_skb->len`. A
surgical patch against this file applied cleanly (`git apply --check`
exit 0).

===============================================================
PHASE 4: MAILING LIST AND EXTERNAL RESEARCH
===============================================================

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**
Record:
- `b4 dig -c a4c72c8c7cef` → https://patch.msgid.link/6fb9de3e499424f798
  0a158798ea02b040b73b8f.1784191283.git.liqiang01@kylinos.cn
- Cover: `[PATCH 0/5] Bluetooth: harden packet and transport parsing`
  (2026-07-16)
- `b4 dig -a`: **v1 only** (no v2/v3)
- Applied 2026-07-20 by Luiz to bluetooth-next as `a4c72c8c7cef`
- No NAK on patch 3/5. BlueZ CI failed **patch 5/5** (`hci_qca.c`
  context), not this file.
- Patch 2/5 (`btmrvl`) later caused a Chromebook regression (Marek
  Szyprowski). That is a **different** patch; not this one.

**Step 4.2: CHECK WHO REVIEWED THE PATCH**
Record (`b4 dig -w`): To/Cc `linux-bluetooth@vger.kernel.org`, Marcel
Holtmann, Luiz von Dentz, LKML. Maintainer applied it. No extra
Reviewed-by on 3/5.

**Step 4.3: SEARCH FOR THE BUG REPORT**
Record: No syzbot/bugzilla report for this specific OOB. Cover letter
describes truncated-header OOB as the failure mode. Trigger
reconstructed from this tree’s `hci_sock_sendmsg` + `bcsp_prepare_pkt`.

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**
Record: Series of five independent driver/transport bounds checks. 3/5
does not depend on 1/2/4/5. Do not pull the others as prerequisites.

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**
Record: lore.kernel.org WebFetch returned 403. No stable-thread hit via
`b4`/openwall for this subject. UNVERIFIED whether anyone already asked
stable@ for this SHA.

===============================================================
PHASE 5: CODE SEMANTIC ANALYSIS
===============================================================

**Step 5.1: IDENTIFY KEY FUNCTIONS IN THE DIFF**
Record: `bcsp_prepare_pkt`, `bcsp_handle_le_pkt`

**Step 5.2: TRACE CALLERS**
Record:
- `bcsp_prepare_pkt`: `bcsp_dequeue()` (unrel, rel, and ACK). Dequeue is
  `hci_uart_proto.dequeue` → `hci_uart_tx_wakeup` / TTY write worker.
- `bcsp_handle_le_pkt`: `bcsp_complete_rx_pkt()` when BCSP channel 1,
  unreliable → `bcsp_recv()` → `hci_uart_tty_receive`. Syzbot has
  already reached `bcsp_recv` via TTY (`TIOCSTI`) in this tree.

**Step 5.3: TRACE CALLEES**
Record: TX reads `hci_opcode_ogf` / raw `data[]`, then `alloc_skb` +
SLIP. RX uses `memcmp`, `alloc_skb`, `skb_queue_head`,
`hci_uart_tx_wakeup`.

**Step 5.4: FOLLOW THE CALL CHAIN**
Record: TX is reachable from userspace `sendmsg` on an HCI RAW/USER
socket bound to a BCSP UART device. RAW vendor OGF 0x3f needs
`CAP_NET_RAW` (`ogf > HCI_SFLT_MAX_OGF`); USER channel bind needs
`CAP_NET_ADMIN`. Not unprivileged, but a real kernel OOB on a live HCI
UART. RX is reachable from the UART/TTY receive path (including
fuzzing).

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**
Record: Same series adds analogous header-length checks in
bfusb/btmrvl/qca. H5 (`hci_h5.c`) does not implement this vendor-
extension rewrite. No duplicate BCSP fix in this tree.

===============================================================
PHASE 6: CROSS-REFERENCING AGAINST THE LOCAL TREE
===============================================================

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?**
Record: Yes.
- `drivers/bluetooth/hci_bcsp.c:197` `if (hciextn && chan == 5)` with no
  length check
- `drivers/bluetooth/hci_bcsp.c:405-406` LE handler indexes `data[4]`
  without `len < 8`
- Bug introduced in 2.6.12-era origin; not post-6.12

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**
Record: **Clean apply** for the actual edits (`git apply --check`
succeeded). Nearby mainline context uses `timer_delete`; 6.12 still has
`del_timer` in `bcsp_pkt_cull`. That is unused context for a tight hunk.
No semantic rework needed.

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**
Record: `git log --grep='validate received'` on this file: empty. No
earlier equivalent check.

===============================================================
PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT
===============================================================

**Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY**
Record: Bluetooth HCI UART BCSP (`CONFIG_BT_HCIUART_BCSP`) — CSR
BlueCore UART. **IMPORTANT** for those devices, not core mm/VFS. Still a
production protocol path, and this file is actively fuzzed.

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**
Record: Bluetooth in this tree is active (many btusb/btintel/hci_bcsp
stable fixes). BCSP itself is mature; this is an old bug, not a new-
feature fallout.

===============================================================
PHASE 8: IMPACT AND RISK ASSESSMENT
===============================================================

**Step 8.1: DETERMINE WHO IS AFFECTED**
Record: Config-specific (`BT_HCIUART_BCSP`) + HCI UART BCSP hardware. TX
trigger also needs an HCI socket send of a short vendor command.

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**
Record:
- TX: HCI command packet, `hciextn` (default true), `len == 3` after
  type byte, OGF 0x3f. Constructible from userspace with
  `CAP_NET_RAW`/`CAP_NET_ADMIN`.
- RX: truncated LE frame; `memcmp` path is likely already in-bounds if
  the state machine honors the header length field.
- Not a hot every-packet path for well-formed kernel-generated commands
  (`hci_cmd_sync_alloc` always includes the 3-byte header).

**Step 8.3: DETERMINE THE FAILURE MODE SEVERITY**
Record: One-byte (or more, if `data` is short) read past `skb->len` on
TX; possible wrong BCSP channel/length if the spilled byte looks like an
HCI extension. May stay inside skb tailroom (not always a KASAN crash).
**Severity: HIGH** (memory safety / OOB), not a guaranteed panic.

**Step 8.4: CALCULATE RISK-BENEFIT RATIO**
Record: Benefit medium-high (closes a long-standing OOB in a fuzzed UART
protocol). Risk very low (4 lines, skip-on-short-packet). Ratio favors
backport.

===============================================================
PHASE 9: FINAL SYNTHESIS
===============================================================

**Step 9.1: COMPILE THE EVIDENCE**

FOR:
- Real OOB read in `bcsp_prepare_pkt` when a 3-byte vendor HCI command
  is sent on BCSP
- RX handler indexes through byte 7 with no length guard
- 4 insertions / 1 deletion, obviously correct
- Code present in this 6.12 tree since origin
- No prerequisites; applies here
- Bluetooth maintainer applied it to bluetooth-next
- Same class as other packet-length checks already landing in this tree

AGAINST:
- No syzbot/user crash report for this exact bug
- TX trigger is privileged
- RX `len < 8` check is likely redundant given the BCSP RX state machine
- Sister patch 2/5 in the same series had a regression (different
  driver)
- Framed as “hardening”

UNRESOLVED:
- lore.kernel.org WebFetch 403; no confirmed stable@ discussion
- Whether skb tailroom would make the 1-byte TX OOB a KASAN hit on this
  kernel’s allocator

**Step 9.2: APPLY THE STABLE RULES CHECKLIST**
1. Obviously correct and tested? **PASS** — maintainer-applied; logic is
   local and readable
2. Fixes a real bug that affects users? **PASS** — OOB on truncated
   vendor commands over BCSP UART
3. Important issue (crash, security, corruption, deadlock)? **PASS** —
   OOB / memory-safety (HIGH, not proven panic)
4. Small and contained? **PASS** — one file, five lines
5. No new features or APIs? **PASS**
6. Can apply to the local tree? **PASS** — buggy code present; surgical
   apply succeeded

**Step 9.3: CHECK FOR EXCEPTION CATEGORIES**
Record: Not a device-ID/quirk/DT/docs exception. Ordinary small memory-
safety fix.

**Step 9.4: MAKE YOUR DECISION**
This belongs on 6.12. The TX length check closes a real out-of-bounds
field access on a path that HCI sockets can hit; the RX check is cheap
and harmless. Scope, risk, and local applicability all fit stable rules.

===============================================================
Verification
===============================================================
- [Phase 1] Parsed subject/body/tags: author Li Qiang, SOB Luiz von
  Dentz; no Fixes/syzbot/Cc-stable
- [Phase 2] Diff: `hci_bcsp.c` +4/-1 in `bcsp_prepare_pkt` and
  `bcsp_handle_le_pkt`
- [Phase 2] `HCI_COMMAND_HDR_SIZE` is 3 in `include/net/bluetooth/hci.h`
- [Phase 2] `hciextn` defaults to true (`module_param`)
- [Phase 3] `git blame`: lines from `1da177e4c3f41` (2.6.12-rc2)
- [Phase 3] `git merge-base --is-ancestor a4c72c8c7cef HEAD` → not in
  this tree (exit 1); object exists as a commit
- [Phase 3] `git log --grep='validate received' --
  drivers/bluetooth/hci_bcsp.c` → empty
- [Phase 4] `b4 dig -c a4c72c8c7cef`: lore msgid 6fb9de3e…; v1-only
  series; applied to bluetooth-next
- [Phase 4] `b4 dig -w`: linux-bluetooth, Holtmann, von Dentz
- [Phase 4] mbox: no NAK on 3/5; CI fail was qca 5/5; btmrvl 2/5 later
  regressed Chromebooks
- [Phase 4] UNVERIFIED: stable@ mailing list (lore WebFetch 403)
- [Phase 5] Callers: `bcsp_dequeue` → UART TX; `bcsp_complete_rx_pkt` →
  `bcsp_recv`
- [Phase 5] `hci_sock_sendmsg`: `len < 4` rejected; after type pull,
  `skb->len` can be 3; OGF 0x3f on RAW needs `CAP_NET_RAW`
- [Phase 6] `git describe HEAD` / Makefile: 6.12.111; buggy `if (hciextn
  && chan == 5)` still present
- [Phase 6] `git apply --check` of the two hunks: success
- [Phase 8] Failure mode: OOB read past `skb->len` on TX vendor-
  extension parse; severity HIGH
- UNVERIFIED: whether this 1-byte read is always inside skb tailroom vs
  KASAN-poisoned

The TX path can read past a 3-byte HCI command; the fix is four lines
and applies to this 6.12 tree without extra commits.

**YES**

 drivers/bluetooth/hci_bcsp.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/drivers/bluetooth/hci_bcsp.c b/drivers/bluetooth/hci_bcsp.c
index 591abe6d63ddb..6461492cf653b 100644
--- a/drivers/bluetooth/hci_bcsp.c
+++ b/drivers/bluetooth/hci_bcsp.c
@@ -194,7 +194,7 @@ static struct sk_buff *bcsp_prepare_pkt(struct bcsp_struct *bcsp, u8 *data,
 		return NULL;
 	}
 
-	if (hciextn && chan == 5) {
+	if (hciextn && chan == 5 && len > HCI_COMMAND_HDR_SIZE) {
 		__le16 opcode = ((struct hci_command_hdr *)data)->opcode;
 
 		/* Vendor specific commands */
@@ -402,6 +402,9 @@ static void bcsp_handle_le_pkt(struct hci_uart *hu)
 	u8 sync_pkt[4]     = { 0xda, 0xdc, 0xed, 0xed };
 
 	/* spot "conf" pkts and reply with a "conf rsp" pkt */
+	if (bcsp->rx_skb->len < 8)
+		return;
+
 	if (bcsp->rx_skb->data[1] >> 4 == 4 && bcsp->rx_skb->data[2] == 0 &&
 	    !memcmp(&bcsp->rx_skb->data[4], conf_pkt, 4)) {
 		struct sk_buff *nskb = alloc_skb(4, GFP_ATOMIC);
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH AUTOSEL 6.18-5.10] Bluetooth: hci_nokia: validate firmware packet bounds
       [not found] <20261019135441.1420968-1-sashal@kernel.org>
                   ` (4 preceding siblings ...)
  2026-10-19 13:48 ` [PATCH AUTOSEL 6.18-5.10] Bluetooth: hci_bcsp: validate received packet lengths Sasha Levin
@ 2026-10-19 13:48 ` Sasha Levin
  2026-10-19 13:50 ` [PATCH AUTOSEL 6.18] Bluetooth: btusb: Add USB ID 13d3:3625 for MediaTek MT7922 Sasha Levin
                   ` (3 subsequent siblings)
  9 siblings, 0 replies; 10+ messages in thread
From: Sasha Levin @ 2026-10-19 13:48 UTC (permalink / raw)
  To: patches, stable
  Cc: Pengpeng Hou, Luiz Augusto von Dentz, Sasha Levin, marcel,
	luiz.dentz, linux-bluetooth, linux-kernel

From: Pengpeng Hou <pengpeng@iscas.ac.cn>

[ Upstream commit 45640627e3ddc5f4d3a0d08618a596a8c65d48a5 ]

nokia_setup_fw() walks a length-prefixed firmware stream and
decodes HCI command packets from each record.

Check that each record fits in the remaining firmware image, that command
records contain the HCI command header, and that the payload length is
covered before submitting the command.

Signed-off-by: Pengpeng Hou <pengpeng@iscas.ac.cn>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
Signed-off-by: Sasha Levin <sashal@kernel.org>
---

LLM Generated explanations, may be completely bogus:

The local tree is **6.18.53** (`pending-6.18`). The buggy firmware
parser is in this checkout and the bounds checks are not. This is a real
out-of-bounds firmware walk, not a feature or cleanup.

---

## PHASE 1: COMMIT MESSAGE FORENSICS

**Step 1.1: PARSE THE SUBJECT LINE**
Record: **[Bluetooth / hci_nokia] [validate] [bounds-check length-
prefixed firmware records before decoding HCI commands]**

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**
Record:
- **Signed-off-by:** Pengpeng Hou \<pengpeng@iscas.ac.cn\> (author)
- **Signed-off-by:** Luiz Augusto von Dentz \<luiz.von.dentz@intel.com\>
  (Bluetooth maintainer; applied the patch)
- **No Fixes:** tag (expected for this review)
- **No Cc: stable** (expected)
- **No Reported-by / Tested-by / Reviewed-by / Acked-by / Link**
- Ignore pipeline markers if present (none on the upstream commit)

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**
Record:
- **Bug:** `nokia_setup_fw()` walks a length-prefixed firmware blob and
  treats each record as an HCI command without checking that `pkt_size`,
  the command header, or `cmd->plen` fit in the remaining image.
- **Symptom / failure mode:** out-of-bounds read of firmware (`memcpy`
  of `cmd->plen` bytes; pointer walk past `fw->data`), and `size_t`
  underflow of `fw_size` if `pkt_size + 2 > fw_size`, which can turn the
  loop into an unbounded walk.
- **Version info in message:** none. Introducer is the original driver
  (v4.12-rc1).
- **Root cause (author):** missing bounds checks on a length-prefixed
  stream before `__hci_cmd_sync()`.

**Step 1.4: DETECT HIDDEN BUG FIXES**
Record: **Not disguised.** Subject and body are an explicit bounds-
validation fix. Same class as firmware OOB checks already in this tree
for `btrtl` and `hci_aml`.

---

## PHASE 2: DIFF ANALYSIS

**Step 2.1: INVENTORY THE CHANGES**
Record:
- **File:** `drivers/bluetooth/hci_nokia.c` — **+20 / −0**
- **Function:** `nokia_setup_fw()`
- **Scope:** single-file surgical fix

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**
Current loop in this tree:

```350:381:drivers/bluetooth/hci_nokia.c
        while (fw_size >= 4) {
                u16 pkt_size = get_unaligned_le16(fw_ptr);
                u8 pkt_type = fw_ptr[2];
                const struct hci_command_hdr *cmd;
                u16 opcode;
                struct sk_buff *skb;

                switch (pkt_type) {
                case HCI_COMMAND_PKT:
                        cmd = (struct hci_command_hdr *)(fw_ptr + 3);
                        opcode = le16_to_cpu(cmd->opcode);

                        skb = __hci_cmd_sync(hu->hdev, opcode,
cmd->plen,
                                             fw_ptr + 3 +
HCI_COMMAND_HDR_SIZE,
                                             HCI_INIT_TIMEOUT);
                        // ...
                }
                fw_ptr += pkt_size + 2;
                fw_size -= pkt_size + 2;
        }
```

Record, per hunk:
1. **Record size vs remaining image:** before, a huge `pkt_size` was
   trusted; after, `pkt_size > fw_size - 2` → `-EINVAL` / `goto done`.
2. **Command header present:** before, `fw_ptr + 3` was cast to
   `hci_command_hdr` with only `fw_size >= 4`; after, `pkt_size < 1 +
   HCI_COMMAND_HDR_SIZE` is rejected (`HCI_COMMAND_HDR_SIZE` is 3).
3. **Payload vs `cmd->plen`:** before, `__hci_cmd_sync()` copied
   `cmd->plen` bytes from `fw_ptr + 6` with no check; after, `cmd->plen
   > pkt_size - 1 - HCI_COMMAND_HDR_SIZE` is rejected.

Error path only for malformed images. Valid firmware is unchanged.

**Step 2.3: IDENTIFY THE BUG MECHANISM**
Record: **[Memory safety / OOB + size_t underflow]**
- `hci_cmd_sync_alloc()` does `skb_put_data(skb, param, plen)` →
  `memcpy` of `cmd->plen` (up to 255) from the firmware pointer with no
  source-size check.
- `fw_size` is `size_t`. `fw_size -= pkt_size + 2` underflows if the
  record is larger than the remaining blob, so the `while (fw_size >=
  4)` loop can continue with `fw_ptr` past the buffer.

**Step 2.4: ASSESS THE FIX QUALITY**
Record: **Obviously correct and minimal.** Arithmetic is sound: the loop
already requires `fw_size >= 4`, so `fw_size - 2` does not underflow;
the header check makes `pkt_size - 1 - HCI_COMMAND_HDR_SIZE` non-
negative. Regression risk is low: only malformed images that already
caused OOB are rejected. No API, locking, or data-structure changes.

---

## PHASE 3: GIT HISTORY INVESTIGATION

**Step 3.1: BLAME THE CHANGED LINES**
Record: Entire parser is **7bb318680e868c** (“Bluetooth: add nokia
driver”, Sebastian Reichel, 2017-04-13). **`git describe --contains` →
`v4.12-rc1~129^2~175^2~4`.** Unchanged since then in this area.

**Step 3.2: FOLLOW THE FIXES: TAG**
Record: **No Fixes: tag.** Introducer is the original driver commit
above. That commit is in this tree (the driver file exists and matches
the pre-image).

**Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES**
Record: Recent `hci_nokia.c` history in this tree is unrelated
(h4_recv_buf, quirk_flags, SPDX, unused struct). **Standalone, not patch
X/Y.** No later `hci_nokia.c` commits on `origin/master` after the fix.

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**
Record: Pengpeng Hou has other Bluetooth bounds-check commits in this
tree (`btusb` Realtek vendor event length, SCO altsetting clamp).
Maintainer SOB is Luiz von Dentz.

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS**
Record: **None.** Uses existing `HCI_COMMAND_HDR_SIZE`, `goto done`,
`request_firmware`. **`git apply --check` of 45640627e3ddc succeeded on
this tree.**

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**
Record:
- **b4 dig:**
  https://patch.msgid.link/20260706091701.77562-1-pengpeng@iscas.ac.cn
- **v1 only** (no v2/v3)
- Applied to bluetooth-next as **a392bd47c5e0** by Luiz on 2026-07-07;
  mainline **45640627e3ddc** (same patch-id
  `6d5cdd79755cd7e3d221355fefd1165392e0381a`)
- **No NAKs.** BlueZ CI: CheckPatch/BuildKernel/Sparse/32-bit all PASS
  (Patchwork series 1122167)
- No reviewer “Cc: stable” in the thread (CI + patchwork-bot only)

**Step 4.2: CHECK WHO REVIEWED THE PATCH**
Record (**b4 dig -w**): Marcel Holtmann, Luiz von Dentz, linux-
bluetooth, linux-kernel. Applied by the Bluetooth maintainer.

**Step 4.3: SEARCH FOR THE BUG REPORT**
Record: **No syzbot/bugzilla/user report.** Bug is from code inspection
of the parser.

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**
Record: Standalone. Same class of firmware-bounds fixes landed in
mainline around the same time:
- `Bluetooth: btrtl: validate firmware patch bounds`
- `Bluetooth: hci_aml: validate firmware segment lengths`
Both are **already in this 6.18 tree** (6744ab60dfac5, e1534d49a7b8b)
via stable (they had `Cc: stable`).

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**
Record: lore.kernel.org/stable WebFetch returned **403**. Keyword search
found **no** stable-list discussion of this subject. **UNVERIFIED**
beyond that.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

**Step 5.1: KEY FUNCTIONS**
Record: **`nokia_setup_fw()`** only.

**Step 5.2: TRACE CALLERS**
Record:
- `nokia_setup()` → `nokia_setup_fw()` (step “3. send firmware”)
- `nokia_proto.setup = nokia_setup`
- `hci_uart_setup()` in `hci_serdev.c` / `hci_ldisc.c` calls
  `hu->proto->setup(hu)`

**Step 5.3: TRACE CALLEES**
Record: `request_firmware()`, `get_unaligned_le16()`, `__hci_cmd_sync()`
→ `hci_cmd_sync_alloc()` → `skb_put_data()`/`memcpy()`,
`release_firmware()`.

**Step 5.4: FOLLOW THE CALL CHAIN**
Record: Triggered when the HCI UART Nokia device is set up (HCI bring-up
after serdev probe of `nokia,h4p-bluetooth`). **Reachable from userspace
HCI up**, not from arbitrary syscalls without the device. Firmware comes
from `nokia/bcmfw.bin` or `nokia/ti1273.bin` via the firmware loader
(including the userspace helper).

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**
Record: `btintel_legacy_rom_patching()` already validates `remain <
cmd->plen`. This tree already backported the same class for **btrtl**
and **hci_aml**. `hci_nokia` was the missing parser.

---

## PHASE 6: CROSS-REFERENCING AGAINST THE LOCAL TREE

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?**
Record: **Yes**, `drivers/bluetooth/hci_nokia.c` `nokia_setup_fw()`,
lines 350–381. Introduced **v4.12**.
Local tree: **`p-6.18-1-g03b85e06ca9bf`, kernelversion 6.18.53, branch
`pending-6.18`.**
`git merge-base --is-ancestor 45640627e3ddc HEAD` → **not an ancestor**
(fix not in this tree).
`git merge-base --is-ancestor 45640627e3ddc v6.18` → **not in v6.18**.
Mainline describe: **v7.2-rc6-1358-g45640627e3ddc**.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**
Record: **Clean apply** (`git apply --check` exit 0). Surrounding code
matches the pre-image.

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**
Record: **No** `Malformed firmware` / this subject in this tree. Sibling
firmware OOB fixes for other BT drivers **are** already here; they do
not cover `hci_nokia`.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

**Step 7.1: SUBSYSTEM AND CRITICALITY**
Record: **Bluetooth HCI UART Nokia H4+ driver**
(`CONFIG_BT_HCIUART_NOKIA`). **PERIPHERAL** (Nokia N9/N900/N950-class
UART Bluetooth), but the bug class is kernel memory safety during device
setup.

**Step 7.2: SUBSYSTEM ACTIVITY**
Record: Bluetooth core is active; `hci_nokia.c` itself is mature (parser
unchanged since 2017).

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

**Step 8.1: WHO IS AFFECTED**
Record: **Driver-specific / config-specific:** `CONFIG_BT_HCIUART_NOKIA`
and DT `nokia,h4p-bluetooth`, firmware `nokia/bcmfw.bin` or
`nokia/ti1273.bin`.

**Step 8.2: TRIGGER CONDITIONS**
Record: HCI setup with a firmware image whose length prefix, header, or
`plen` does not fit the blob. **Not every boot with good linux-
firmware.** Can be hit by truncated/corrupt firmware or a userspace
firmware loader. Unprivileged network clients cannot trigger it without
the device and a bad firmware file.

**Step 8.3: FAILURE MODE SEVERITY**
Record: **Kernel OOB read** (`memcpy` past `fw->data`) and possible
**unbounded buffer walk** after `fw_size` underflow. **Severity: HIGH**
(oops / KASAN / infoleak potential). Not a remote unauth exploit by
itself.

**Step 8.4: RISK-BENEFIT RATIO**
Record:
- **Benefit: HIGH for affected hardware** (prevents OOB/crash on bad
  firmware); **MEDIUM overall** (niche driver, but same bug class
  already taken for other BT firmware parsers in this tree).
- **Risk: VERY LOW** (20 lines, error-path only, clean apply).
- **Ratio: backport.**

---

## PHASE 9: FINAL SYNTHESIS

**Step 9.1: COMPILE THE EVIDENCE**

**FOR:**
- Real OOB: trusted `pkt_size`/`cmd->plen` without remaining-size
  checks; `__hci_cmd_sync` copies `plen` bytes; `fw_size` can underflow.
- Present in this 6.18.53 tree since v4.12; fix is not in HEAD.
- Small (+20), obviously correct, applies cleanly.
- No new APIs; valid firmware behavior unchanged.
- Applied by the Bluetooth maintainer; BlueZ CI passed.
- Same class already backported here for `btrtl` and `hci_aml`.

**AGAINST:**
- Niche Nokia UART hardware.
- No syzbot/user report; trigger needs malformed firmware.
- No `Fixes:` / `Cc: stable` (not a negative under these rules).

**UNRESOLVED:**
- Stable list 403; no evidence it was NAK’d for stable.
- No public crash report with a stack trace.

**Step 9.2: STABLE RULES CHECKLIST**
1. Obviously correct and tested? **PASS** (logic + maintainer apply +
   CI)
2. Fixes a real bug that affects users? **PASS** (OOB on malformed Nokia
   firmware at HCI setup)
3. Important (crash/security/corruption/deadlock)? **PASS** — HIGH
   memory-safety OOB
4. Small and contained? **PASS** — +20 lines, one function
5. No new features or APIs? **PASS**
6. Can apply to the local tree? **PASS** — `git apply --check` clean

**Step 9.3: EXCEPTION CATEGORIES**
Record: Not a device-ID/quirk/DT/build/docs exception. Ordinary
**memory-safety bug fix**.

**Step 9.4: DECISION**
This tree still has the unbounded firmware walk. The patch is a 20-line
guard that this 6.18 branch already accepted for sibling Bluetooth
firmware parsers. Backport it.

---

### What the commit solves for this tree

`nokia_setup_fw()` still trusts a LE16 length and `cmd->plen` from
`nokia/bcmfw.bin` / `nokia/ti1273.bin`. A truncated or hostile image can
make `__hci_cmd_sync()` `memcpy` past the firmware buffer and can wrap
`fw_size` so the loop walks off the end. The patch rejects those records
with `-EINVAL` before the copy/advance.

### Risk vs benefit

Benefit is preventing a kernel OOB during HCI setup on Nokia H4+ UART
Bluetooth. Risk is negligible: checks only fire on records that already
overflowed, and the hunk applies without context changes.

---

### Verification
- **[Phase 1]** Parsed tags on `45640627e3ddc` / `a392bd47c5e0`: author
  + Luiz SOB only; no Fixes/Cc/Reported-by
- **[Phase 2]** Diff: +20 in `nokia_setup_fw()`; three `-EINVAL` checks;
  `__hci_cmd_sync` / `skb_put_data` confirmed as `memcpy(param, plen)`
- **[Phase 2]** `HCI_COMMAND_HDR_SIZE` is 3; `struct hci_command_hdr {
  __le16 opcode; __u8 plen; }`
- **[Phase 3]** `git blame` 350–381: all `7bb318680e868c` (v4.12-rc1)
- **[Phase 3]** No Fixes tag; introducer is original driver
- **[Phase 3]** `git apply --check` of 45640627e3ddc: **exit 0**
- **[Phase 4]** `b4 dig -c a392bd47c5e0` / `-a` / `-w`: v1 only; lore
  msgid 20260706091701.77562-1; CC Holtmann + von Dentz + linux-
  bluetooth
- **[Phase 4]** mbox: BlueZ CI PASS; patchwork-bot applied to bluetooth-
  next `a392bd47c5e0`; no NAK
- **[Phase 4]** lore.kernel.org WebFetch 403; stable-list discussion
  **UNVERIFIED** (search did not show a hit)
- **[Phase 5]** Callers: `nokia_setup` ← `hci_uart_setup` in
  `hci_serdev.c`/`hci_ldisc.c`
- **[Phase 6]** `git describe HEAD` → `p-6.18-1-g03b85e06ca9bf`; `make
  kernelversion` → **6.18.53**
- **[Phase 6]** Buggy loop present; `merge-base --is-ancestor
  45640627e3ddc HEAD` failed; not in v6.18; mainline is v7.2-rc6-1358
- **[Phase 6]** Sibling firmware OOB fixes **are** in this tree:
  6744ab60dfac5 (btrtl), e1534d49a7b8b (hci_aml)
- **[Phase 8]** Failure mode: OOB read / possible unbounded walk → HIGH
- **UNVERIFIED:** whether a specific production `nokia/*.bin` is
  malformed (not required; the parser is still unchecked)

**YES**

 drivers/bluetooth/hci_nokia.c | 20 ++++++++++++++++++++
 1 file changed, 20 insertions(+)

diff --git a/drivers/bluetooth/hci_nokia.c b/drivers/bluetooth/hci_nokia.c
index 1e65b541f8ade..be2923231e712 100644
--- a/drivers/bluetooth/hci_nokia.c
+++ b/drivers/bluetooth/hci_nokia.c
@@ -354,9 +354,29 @@ static int nokia_setup_fw(struct hci_uart *hu)
 		u16 opcode;
 		struct sk_buff *skb;
 
+		if (pkt_size > fw_size - 2) {
+			err = -EINVAL;
+			dev_err(dev, "%s: Malformed firmware packet\n",
+				hu->hdev->name);
+			goto done;
+		}
+
 		switch (pkt_type) {
 		case HCI_COMMAND_PKT:
+			if (pkt_size < 1 + HCI_COMMAND_HDR_SIZE) {
+				err = -EINVAL;
+				dev_err(dev, "%s: Malformed firmware command\n",
+					hu->hdev->name);
+				goto done;
+			}
+
 			cmd = (struct hci_command_hdr *)(fw_ptr + 3);
+			if (cmd->plen > pkt_size - 1 - HCI_COMMAND_HDR_SIZE) {
+				err = -EINVAL;
+				dev_err(dev, "%s: Truncated firmware command\n",
+					hu->hdev->name);
+				goto done;
+			}
 			opcode = le16_to_cpu(cmd->opcode);
 
 			skb = __hci_cmd_sync(hu->hdev, opcode, cmd->plen,
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH AUTOSEL 6.18] Bluetooth: btusb: Add USB ID 13d3:3625 for MediaTek MT7922
       [not found] <20261019135441.1420968-1-sashal@kernel.org>
                   ` (5 preceding siblings ...)
  2026-10-19 13:48 ` [PATCH AUTOSEL 6.18-5.10] Bluetooth: hci_nokia: validate firmware packet bounds Sasha Levin
@ 2026-10-19 13:50 ` Sasha Levin
  2026-10-19 13:50 ` [PATCH AUTOSEL 6.18-6.1] Bluetooth: hci_sync: Disable legacy instance's ext adv before setup snapshot Sasha Levin
                   ` (2 subsequent siblings)
  9 siblings, 0 replies; 10+ messages in thread
From: Sasha Levin @ 2026-10-19 13:50 UTC (permalink / raw)
  To: patches, stable
  Cc: Gustavo Evgucci, Paul Menzel, Luiz Augusto von Dentz, Sasha Levin,
	marcel, luiz.dentz, linux-bluetooth, linux-kernel

From: Gustavo Evgucci <monesss315@gmail.com>

[ Upstream commit 849a3bf1489093996859ba0c3c1c0cd314d6ff96 ]

The IMC Networks MT7922 Bluetooth adapter with USB ID 13d3:3625 is not
recognized as a MediaTek device because it is missing from the btusb
device ID table. As a result, btmtk firmware loading is never triggered
and the HCI reset command times out with -ETIMEDOUT.

Add the device with BTUSB_MEDIATEK | BTUSB_WIDEBAND_SPEECH flags,
consistent with the neighboring 13d3:3627, 13d3:3628 and 13d3:3630
entries which use the same chip.

Tested on: MediaTek MT7922 (Wi-Fi 6E combo card, IMC Networks BT USB
interface), kernel 7.0.11-arch1-1.

/sys/kernel/debug/usb/devices:

T:  Bus=01 Lev=01 Prnt=01 Port=12 Cnt=03 Dev#=  4 Spd=480  MxCh= 0
D:  Ver= 2.10 Cls=ef(misc ) Sub=02 Prot=01 MxPS=64 #Cfgs=  1
P:  Vendor=13d3 ProdID=3625 Rev= 1.00
S:  Manufacturer=MediaTek Inc.
S:  Product=Wireless_Device
S:  SerialNumber=000000000
C:* #Ifs= 3 Cfg#= 1 Atr=e0 MxPwr=100mA
A:  FirstIf#= 0 IfCount= 3 Cls=e0(wlcon) Sub=01 Prot=01
I:* If#= 0 Alt= 0 #EPs= 3 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
E:  Ad=81(I) Atr=03(Int.) MxPS=  16 Ivl=125us
E:  Ad=82(I) Atr=02(Bulk) MxPS= 512 Ivl=0ms
E:  Ad=02(O) Atr=02(Bulk) MxPS= 512 Ivl=0ms
I:* If#= 1 Alt= 0 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
E:  Ad=83(I) Atr=01(Isoc) MxPS=   0 Ivl=1ms
E:  Ad=03(O) Atr=01(Isoc) MxPS=   0 Ivl=1ms
I:  If#= 1 Alt= 1 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
E:  Ad=83(I) Atr=01(Isoc) MxPS=   9 Ivl=1ms
E:  Ad=03(O) Atr=01(Isoc) MxPS=   9 Ivl=1ms
I:  If#= 1 Alt= 2 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
E:  Ad=83(I) Atr=01(Isoc) MxPS=  17 Ivl=1ms
E:  Ad=03(O) Atr=01(Isoc) MxPS=  17 Ivl=1ms
I:  If#= 1 Alt= 3 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
E:  Ad=83(I) Atr=01(Isoc) MxPS=  25 Ivl=1ms
E:  Ad=03(O) Atr=01(Isoc) MxPS=  25 Ivl=1ms
I:  If#= 1 Alt= 4 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
E:  Ad=83(I) Atr=01(Isoc) MxPS=  33 Ivl=1ms
E:  Ad=03(O) Atr=01(Isoc) MxPS=  33 Ivl=1ms
I:  If#= 1 Alt= 5 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
E:  Ad=83(I) Atr=01(Isoc) MxPS=  49 Ivl=1ms
E:  Ad=03(O) Atr=01(Isoc) MxPS=  49 Ivl=1ms
I:  If#= 1 Alt= 6 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
E:  Ad=83(I) Atr=01(Isoc) MxPS=  63 Ivl=1ms
E:  Ad=03(O) Atr=01(Isoc) MxPS=  63 Ivl=1ms
I:  If#= 2 Alt= 0 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
E:  Ad=8a(I) Atr=03(Int.) MxPS=  64 Ivl=125us
E:  Ad=0a(O) Atr=03(Int.) MxPS=  64 Ivl=125us
I:* If#= 2 Alt= 1 #EPs= 2 Cls=e0(wlcon) Sub=01 Prot=01 Driver=btusb
E:  Ad=8a(I) Atr=03(Int.) MxPS= 512 Ivl=125us
E:  Ad=0a(O) Atr=03(Int.) MxPS= 512 Ivl=125us

Signed-off-by: Gustavo Evgucci <monesss315@gmail.com>
Reviewed-by: Paul Menzel <pmenzel@molgen.mpg.de>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
Signed-off-by: Sasha Levin <sashal@kernel.org>
---

LLM Generated explanations, may be completely bogus:

This is a two-line USB ID addition for an existing MediaTek btusb path.
The local tree is **6.18.53** (`pending-6.18`); `13d3:3625` is missing
here, while neighboring MediaTek IDs and `BTUSB_MEDIATEK` setup already
exist.

===============================================================
PHASE 1: COMMIT MESSAGE FORENSICS
===============================================================

**Step 1.1: PARSE THE SUBJECT LINE**

Record: [Bluetooth / btusb] [Add] [USB ID 13d3:3625 for MediaTek MT7922]
- Subsystem: Bluetooth USB driver (`btusb`)
- Action verb: **Add** (device ID to an existing driver)
- Claimed intent: enable an IMC Networks / MediaTek MT7922 adapter that
  is already bound by generic Bluetooth USB matching but is not treated
  as MediaTek

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**

Record:
- **Fixes:** none (expected)
- **Reported-by:** none
- **Tested-by:** none as a tag; body says tested on kernel
  7.0.11-arch1-1
- **Reviewed-by:** Paul Menzel `<pmenzel@molgen.mpg.de>`
- **Acked-by:** none
- **Link:** none in the commit message
- **Cc: stable:** none (expected)
- **Signed-off-by:** Gustavo Evgucci `<monesss315@gmail.com>` (author);
  Luiz Augusto von Dentz `<luiz.von.dentz@intel.com>` (Bluetooth
  maintainer)
- Ignore: any pipeline “Upstream commit …” / Sasha Levin SOB if present

Notable: maintainer SOB plus an independent Reviewed-by. Bluetooth CI
(bluez.test.bot) ran on v1 and v2.

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**

Record:
- **Bug:** USB ID `13d3:3625` is missing from the btusb ID/quirks table,
  so the adapter is not flagged `BTUSB_MEDIATEK`.
- **Symptom:** MediaTek firmware load (`btmtk`) never runs; HCI reset
  times out with `-ETIMEDOUT` (`Opcode 0x0c03 failed: -110` in user
  reports).
- **Root cause:** generic Bluetooth class match binds `btusb` with
  `driver_info == 0`; MediaTek setup is skipped.
- **Fix:** add `{ USB_DEVICE(0x13d3, 0x3625), .driver_info =
  BTUSB_MEDIATEK | BTUSB_WIDEBAND_SPEECH }` next to
  `13d3:3627/3628/3630`.
- **Version info:** tested on 7.0.11-arch1-1;
  `/sys/kernel/debug/usb/devices` dump included (vendor 13d3, product
  3625, Manufacturer=MediaTek Inc., class e0/01/01, Driver=btusb).

**Step 1.4: DETECT HIDDEN BUG FIXES**

Record: Not a disguised cleanup. It is an explicit hardware ID addition.
That is a documented stable exception: new device IDs on an existing
driver. It also fixes a real functional failure (HCI timeout, adapter
unusable).

===============================================================
PHASE 2: DIFF ANALYSIS - LINE BY LINE
===============================================================

**Step 2.1: INVENTORY THE CHANGES**

Record:
- File: `drivers/bluetooth/btusb.c` only
- Scope: **+2 lines** in `quirks_table[]` (single-file surgical ID add)
- Functions: none; static `usb_device_id` table only
- Classification: single-file device ID addition

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**

Record:
- **Before:** `13d3:3625` is absent from `quirks_table`. Probe matches
  generic `{ USB_DEVICE_INFO(0xe0, 0x01, 0x01) }` in `btusb_table` with
  empty `driver_info`. `btusb_probe()` only consults `quirks_table` when
  `!id->driver_info` (lines 4064–4069). No MediaTek match →
  `hdev->setup` is not set to `btusb_mtk_setup`.
- **After:** `usb_match_id(intf, quirks_table)` hits the new entry.
  `id->driver_info & BTUSB_MEDIATEK` is true, so probe sets `hdev->setup
  = btusb_mtk_setup` and related MTK callbacks (lines 4244–4258).
  `BTUSB_WIDEBAND_SPEECH` sets `HCI_QUIRK_WIDEBAND_SPEECH_SUPPORTED`
  (lines 4344–4345).
- Path affected: probe/init of this USB ID only.

**Step 2.3: IDENTIFY THE BUG MECHANISM**

Record: **Hardware workaround / device ID addition (category h)**
- Broken: MediaTek combo card enumerates as generic Bluetooth USB;
  firmware is never loaded; HCI reset times out.
- Fix: same flags as neighboring IMC/MediaTek entries already in this
  tree.

**Step 2.4: ASSESS THE FIX QUALITY**

Record:
- Obviously correct: two-line table entry matching established pattern.
- Minimal; no unrelated edits; no API/locking/data-structure change.
- Regression risk: **very low**, scoped to VID/PID 13d3:3625. Wrong
  flags would only affect that device; flags match 3627/3628/3630.
- Chip naming is slightly inconsistent in history (3627 subject says
  MT7925, body says MT7922); **flags are the same**, so the driver path
  is identical.

===============================================================
PHASE 3: GIT HISTORY INVESTIGATION
===============================================================

**Step 3.1: BLAME THE CHANGED LINES**

Record:
- Insertion sits between `13d3:3613` (Youn Mélois, 2025-04-01,
  `bbf56029322c06`) and `13d3:3627` (Chris Lu, 2025-09-04,
  `576952cf981b7`).
- This is not a regression in old code; it is a **missing ID** for
  hardware that uses the long-standing MediaTek path.
- MT7922 USB support: `8c0401b7308cb` (“Bluetooth: Add support for
  MediaTek MT7922 device”), contained in v6.11-rc1 era. Present in this
  6.18 tree.

**Step 3.2: FOLLOW THE FIXES: TAG**

Record: No `Fixes:` tag. Not applicable. The “bug” is omission of this
VID/PID, not a later regression.

**Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES**

Record:
- This tree already has many of the same class of commits, including:
  - `576952cf981b7` 13d3/3627
  - `f63f401130e5c` 13d3/3628
  - `5bd5c716f7ec3` 13d3/3630
  - `70cd38d22d465` 13d3/3633 for MT7922
- Candidate `ddd25808d4c2` is **not** an ancestor of HEAD (`git merge-
  base --is-ancestor` exit 1).
- Standalone; not patch X/Y.

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**

Record: `git log --author="Gustavo Evgucci" -- drivers/bluetooth/` is
empty in this tree. Author is a first-time hardware-ID contributor, not
the subsystem maintainer. Weight comes from Luiz’s merge and Paul
Menzel’s Reviewed-by.

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS**

Record:
- Needs `quirks_table`, `BTUSB_MEDIATEK`, `BTUSB_WIDEBAND_SPEECH`, and
  `btusb_mtk_setup`. All exist here.
- `CONFIG_BT_HCIBTUSB_MTK` exists (`drivers/bluetooth/Kconfig`).
- No extra commits required.
- Can apply standalone. Parent of `ddd25808d4c2` also has `13d3:3609`,
  which this 6.18 tree lacks; that is **context only**. Insertion
  between 3613 and 3627 is valid here.

===============================================================
PHASE 4: MAILING LIST AND EXTERNAL RESEARCH
===============================================================

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**

Record:
- `b4 dig -c ddd25808d4c2` matched patch-id
  `ce1685f940593b167015292f6b73b7f2fc9ec8d9`
- Lore/msgid:
  https://patch.msgid.link/20260625083230.300651-1-monesss315@gmail.com
- Thread saved to `/tmp/btusb-3625.mbox` (7 messages)
- **v1** (2026-06-23): `[PATCH] Bluetooth: btusb: Add IMC Networks
  MT7922 device 0x13d3:0x3625`
- **v2** (2026-06-25): added usb/devices dump, Reviewed-by, full
  maintainer To/Cc. **Code hunk unchanged.**
- Applied to bluetooth-next as `ddd25808d4c2` by Luiz (patchwork-bot,
  2026-06-26).
- Review: Paul Menzel asked for usb/devices dump and get_maintainer.pl
  recipients; then Reviewed-by. **No NAK.**
- Bluetooth CI: v1 all PASS; v2 GitLint FAIL only for an 82-char notes
  line. Builds passed.
- No reviewer asked for `Cc: stable`.

**Step 4.2: CHECK WHO REVIEWED THE PATCH**

Record (`b4 dig -w`):
- Gustavo Evgucci (author)
- Luiz Augusto von Dentz (Bluetooth driver maintainer)
- Marcel Holtmann (Bluetooth maintainer)
- linux-bluetooth@, linux-kernel@
- Paul Menzel (reviewer)
Appropriate maintainers were on the thread; Luiz applied it.

**Step 4.3: SEARCH FOR THE BUG REPORT**

Record:
- User-tested on real hardware with a full usb/devices dump.
- External confirmation: DKMS workarounds for Mercusys MA80XE / IMC
  Networks `13d3:3625` (`hci0: Opcode 0x0c03 failed: -110`). That
  matches the commit’s -ETIMEDOUT description.
- Not syzbot; hardware enablement with a concrete timeout.

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**

Record: Single-patch series (v1 → v2 documentation only). Neighboring
IDs already in this tree.

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**

Record: No useful stable@ thread found (lore.kernel.org/stable WebFetch
blocked by anti-bot). Absence of prior stable discussion is not a
negative signal for a device-ID add.

===============================================================
PHASE 5: CODE SEMANTIC ANALYSIS
===============================================================

semcode MCP: not available. Used grep/read.

**Step 5.1: IDENTIFY KEY FUNCTIONS IN THE DIFF**

Record: No functions modified. Data: `quirks_table[]`. Consumers:
`btusb_probe()`.

**Step 5.2: TRACE CALLERS**

Record:
- `btusb_probe()` ← USB core when `btusb` matches.
- Generic match: `btusb_table` `{ USB_DEVICE_INFO(0xe0, 0x01, 0x01) }`
  (line 83), which matches this device’s If#0 Cls=e0 Sub=01 Prot=01.
- Then `usb_match_id(intf, quirks_table)` when `driver_info` is 0.

**Step 5.3: TRACE CALLEES**

Record: With the new flags, probe assigns `btusb_mtk_setup`,
`btusb_mtk_shutdown`, `btmtk_reset_sync`, `btmtk_set_bdaddr`,
`btusb_send_frame_mtk`, USB suspend/resume/disconnect MTK hooks.

**Step 5.4: FOLLOW THE CALL CHAIN**

Record: Userspace-reachable: plug in / boot with the adapter.
Unprivileged users do not need a special syscall; udev/bluetoothd open
the HCI device. High priority for owners of this card. Not a universal
path.

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**

Record: Dozens of `USB_DEVICE(0x13d3, …) … BTUSB_MEDIATEK |
BTUSB_WIDEBAND_SPEECH` entries. Same pattern as 3627/3628/3630 already
in this file. Systematic missing-ID class, not a one-off logic bug.

===============================================================
PHASE 6: CROSS-REFERENCING AGAINST THE LOCAL TREE
===============================================================

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?**

Record:
- Local tree: `git describe HEAD` → `p-6.18-1-g03b85e06ca9bf`; `make
  kernelversion` → **6.18.53**; branch `pending-6.18`.
- `13d3:3625` is **not** in `drivers/bluetooth/btusb.c` (`rg` found only
  unrelated Realtek `0x3625:0x010b`).
- `quirks_table` MediaTek block **is** here, with 3613 then 3627 (lines
  787–794).
- Neighbor commits 3627/3628/3630 **are** ancestors of HEAD.
- Candidate `ddd25808d4c2` is **not** an ancestor of HEAD.
- Driver support for MT7922 has been in this lineage since ~v6.11
  (`8c0401b7308cb`).

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**

Record: **Clean / minor context fuzz.** Candidate parent has extra
`13d3:3609` above 3613; 6.18 does not. Added lines themselves match. No
refactor of `quirks_table` vs probe matching.

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**

Record: No other 13d3:3625 MediaTek entry. `d9da920233ec8` is Realtek
`3625:010b` (different vendor). Not a duplicate.

===============================================================
PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT
===============================================================

**Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY**

Record: [drivers/bluetooth/btusb.c] [IMPORTANT]
- Common USB Bluetooth driver, not core mm/fs.
- MediaTek Wi-Fi 6E combo cards are widely used (laptops, USB adapters).
  Device-specific, but the class of fix is standard for stable.

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**

Record: Active. Recent 6.18 history includes many VID/PID adds and btusb
bugfixes. ID table is the normal place for this change.

===============================================================
PHASE 8: IMPACT AND RISK ASSESSMENT
===============================================================

**Step 8.1: DETERMINE WHO IS AFFECTED**

Record: Users of USB Bluetooth `13d3:3625` (IMC Networks / MediaTek
MT7922, e.g. combo cards / Mercusys MA80XE). Others unchanged. Requires
`CONFIG_BT_HCIBTUSB` and typically `CONFIG_BT_HCIBTUSB_MTK`.

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**

Record: Every probe of this device (boot or plug-in). Not a race. Not
unprivileged exploit; the device simply does not work. Reproduced by the
author and by out-of-tree DKMS users.

**Step 8.3: DETERMINE THE FAILURE MODE SEVERITY**

Record: [Bluetooth adapter fails HCI reset / -ETIMEDOUT; no controller]
[HIGH for affected hardware, LOW globally]
- Not a panic/UAF, but the device is dead without the ID. That is the
  usual severity for missing USB IDs.

**Step 8.4: CALCULATE RISK-BENEFIT RATIO**

Record:
- **Benefit:** High for holders of this adapter on 6.18; zero for
  everyone else.
- **Risk:** Very low (2 lines, existing flags, existing probe path).
- **Ratio:** Strongly favors backport. This is the textbook new-device-
  ID exception.

===============================================================
PHASE 9: FINAL SYNTHESIS
===============================================================

**Step 9.1: COMPILE THE EVIDENCE**

FOR:
- Explicit stable exception: new USB ID on an existing driver
- Real user-visible bug: HCI reset -ETIMEDOUT, adapter unusable
- 2-line, obviously correct, same flags as 3627/3628/3630 already in
  this tree
- MTK setup path (`btusb_mtk_setup`) present
- Reviewed-by Paul Menzel; merged by Luiz von Dentz; CI built
- Author tested on hardware; usb/devices dump matches
- Independent DKMS users hit the same ID/symptom
- Applies with at most minor context adjustment (missing 3609)

AGAINST:
- Not a crash/security/corruption bug (hardware enablement)
- Author is not a regular Bluetooth contributor
- Chip labeled MT7922 vs some neighbor commits saying MT7925 (flags
  still match)
- No Cc: stable (not a negative under these rules)

UNRESOLVED:
- lore.kernel.org HTTP 403 for WebFetch; thread recovered via `b4 dig
  -m`
- No stable@ discussion found (search not useful)

**Step 9.2: APPLY THE STABLE RULES CHECKLIST**

1. Obviously correct and tested? **PASS** — 2-line ID; hardware test;
   reviewer + maintainer
2. Fixes a real bug that affects users? **PASS** — missing ID → firmware
   never loads → HCI timeout
3. Important issue? **PASS** under the device-ID exception; adapter
   otherwise unusable
4. Small and contained? **PASS** — +2 lines, one table
5. No new features or APIs? **PASS** — ID only; no new driver/API
6. Can apply to the local tree? **PASS** — insertion point 3613/3627
   exists; 3625 absent

**Step 9.3: CHECK FOR EXCEPTION CATEGORIES**

Record: **Device ID addition to existing driver** — automatic YES
category.

**Step 9.4: MAKE YOUR DECISION**

Backport to this 6.18 tree. The bug exists here, the MediaTek path
exists here, neighboring IDs exist here, and the change is a two-line
USB ID with the established flags.

---

**What the commit solves for this tree**

On 6.18.53, `13d3:3625` still matches only the generic Bluetooth USB
class, so `btusb_probe()` never sets `BTUSB_MEDIATEK` and never calls
`btusb_mtk_setup`. HCI reset then times out. Adding the quirks_table
entry with `BTUSB_MEDIATEK | BTUSB_WIDEBAND_SPEECH` is the same
enablement already used for 3627/3628/3630 in this file.

**Risk vs benefit**

Benefit is making this MediaTek/IMC adapter work; risk is confined to
that VID/PID. No locking, no API, no refactor.

**Concerns**

Parent context includes `13d3:3609`, which 6.18 does not have. Insert
between existing 3613 and 3627. No other prerequisites.

Verification:
- [Phase 1] Parsed subject/tags/body from `git show -s ddd25808d4c2` and
  the supplied message: Add USB ID; Reviewed-by Paul Menzel; SOB Luiz;
  no Fixes/Cc stable
- [Phase 2] Diff: +2 lines in `quirks_table`; confirmed `btusb_probe`
  uses that table when `!id->driver_info` (btusb.c:4064–4069); MTK setup
  at 4244–4258; WBS quirk at 4344–4345
- [Phase 2] Generic match `USB_DEVICE_INFO(0xe0, 0x01, 0x01)` at line 83
  matches the dumped interface class
- [Phase 3] `git describe HEAD` / `make kernelversion`: p-6.18-1 /
  6.18.53
- [Phase 3] `git merge-base --is-ancestor ddd25808d4c2 HEAD` → not
  ancestor; 3627/3628/3630 commits are ancestors
- [Phase 3] `rg 0x3625 drivers/bluetooth/btusb.c`: no 13d3:3625; only
  Realtek 3625:010b
- [Phase 3] blame 785–796: 3613/3627/3628/3630 present as described
- [Phase 3] MT7922 intro `8c0401b7308cb` contained around v6.11-rc1;
  present in this tree
- [Phase 3] author log empty in drivers/bluetooth/
- [Phase 4] `b4 dig -c ddd25808d4c2` → msgid 20260625083230.300651-1;
  v1+v2; applied as ddd25808d4c2
- [Phase 4] `b4 dig -a`: v1 then v2 (docs only); `b4 dig -w`: Luiz,
  Marcel, linux-bluetooth, Paul Menzel
- [Phase 4] mbox: Paul Reviewed-by; CI pass (v2 gitlint notes-line
  only); no NAK
- [Phase 4] lore WebFetch 403; used b4 mbox instead. Stable list search:
  no relevant hit
- [Phase 5] semcode unavailable; callers via grep: quirks_table →
  btusb_probe only
- [Phase 6] 3613 and 3627 present, 3625 absent — insertion point
  verified in this checkout
- [Phase 8] Failure mode: HCI -ETIMEDOUT / no controller for this USB
  ID; not a kernel oops
- UNVERIFIED: live lore.kernel.org HTML of the thread (403); chip MT7922
  vs MT7925 labeling of neighbors (flags verified identical)

**YES**

 drivers/bluetooth/btusb.c | 2 ++
 1 file changed, 2 insertions(+)

diff --git a/drivers/bluetooth/btusb.c b/drivers/bluetooth/btusb.c
index 59fff918fd2de..9257341b01399 100644
--- a/drivers/bluetooth/btusb.c
+++ b/drivers/bluetooth/btusb.c
@@ -788,6 +788,8 @@ static const struct usb_device_id quirks_table[] = {
 						     BTUSB_WIDEBAND_SPEECH },
 	{ USB_DEVICE(0x13d3, 0x3613), .driver_info = BTUSB_MEDIATEK |
 						     BTUSB_WIDEBAND_SPEECH },
+	{ USB_DEVICE(0x13d3, 0x3625), .driver_info = BTUSB_MEDIATEK |
+						     BTUSB_WIDEBAND_SPEECH },
 	{ USB_DEVICE(0x13d3, 0x3627), .driver_info = BTUSB_MEDIATEK |
 						     BTUSB_WIDEBAND_SPEECH },
 	{ USB_DEVICE(0x13d3, 0x3628), .driver_info = BTUSB_MEDIATEK |
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH AUTOSEL 6.18-6.1] Bluetooth: hci_sync: Disable legacy instance's ext adv before setup snapshot
       [not found] <20261019135441.1420968-1-sashal@kernel.org>
                   ` (6 preceding siblings ...)
  2026-10-19 13:50 ` [PATCH AUTOSEL 6.18] Bluetooth: btusb: Add USB ID 13d3:3625 for MediaTek MT7922 Sasha Levin
@ 2026-10-19 13:50 ` Sasha Levin
  2026-10-19 13:51 ` [PATCH AUTOSEL 6.18] Bluetooth: btnxpuart: Fix use-after-free in probe error path Sasha Levin
  2026-10-19 13:52 ` [PATCH AUTOSEL 6.18] Bluetooth: fix BT dependency for submodules Sasha Levin
  9 siblings, 0 replies; 10+ messages in thread
From: Sasha Levin @ 2026-10-19 13:50 UTC (permalink / raw)
  To: patches, stable
  Cc: Muhammad Saheed, Luiz Augusto von Dentz, Sasha Levin, marcel,
	luiz.dentz, linux-bluetooth, linux-kernel

From: Muhammad Saheed <muhammad.saheed.iam@gmail.com>

[ Upstream commit 75722cde87ee24029e93e4e32d85309989f55991 ]

hci_setup_ext_adv_instance_sync(...) only disabled
HCI_OP_LE_SET_EXT_ADV_ENABLE before setup snapshot in case of non-legacy
instances (instance > 0) and never disabled the same for legacy instance
(instance == 0). This would lead to failure in setting ext adv params
with HCI_ERROR_COMMAND_DISALLOWED (0x0c) error like below, when toggling
the discoverable/connectable property of a controller with advertising
enabled.
```
$ btmgmt advertising off
hci0 Set Advertising complete, settings: powered ssp br/edr le
  secure-conn wide-band-speech cis-central cis-peripheral
$ btmgmt connectable on
hci0 Set Connectable complete, settings: powered connectable ssp br/edr
  le secure-conn wide-band-speech cis-central cis-peripheral
$ btmgmt connectable off
hci0 Set Connectable complete, settings: powered ssp br/edr le
  secure-conn wide-band-speech cis-central cis-peripheral

$ btmgmt advertising on
hci0 Set Advertising complete, settings: powered connectable ssp br/edr
  le advertising secure-conn wide-band-speech cis-central cis-peripheral
$ btmgmt connectable on
Set Connectable for hci0 failed with status 0x0a (Busy)
$ btmgmt connectable off
Set Connectable for hci0 failed with status 0x0a (Busy)

$ dmesg
...
[   21.970527] hci0: Opcode 0x2036
[   21.970529] hci0: opcode 0x2036 plen 25
[   21.970537] hci0: skb len 28
[   21.970539] hci0: length 1
[   21.976099] hci0: result 0x0c
[   21.976105] hci0: end: err -16
[   21.976114] Bluetooth: hci0: Opcode 0x2036 failed: -16
```

Signed-off-by: Muhammad Saheed <muhammad.saheed.iam@gmail.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
Signed-off-by: Sasha Levin <sashal@kernel.org>
---

LLM Generated explanations, may be completely bogus:

Connection lost, reconnecting to https://agentn.us.api5.cursor.sh
(attempt 1)...
Retry attempt 1...
I have the local-tree picture: 6.12.111 still has the `instance > 0`
hole, the prerequisites are already present, and the patch applies. The
rest of this is the full nine-phase write-up.

## Phase 1: Commit message forensics

**Step 1.1: Subject line**
- Record: `[Bluetooth / hci_sync] [Disable] legacy instance 0 extended
  advertising must be turned off before setup snapshot, matching the
  existing non-legacy path`

**Step 1.2: Tags**
- Record: No `Fixes:`, `Reported-by:`, `Tested-by:`, `Reviewed-by:`,
  `Acked-by:`, `Link:`, or `Cc: stable`. Signed-off-by: Muhammad Saheed
  (author), Luiz Augusto von Dentz (Bluetooth maintainer). Absence of
  `Fixes`/`Cc: stable` is expected for this review pipeline and is not a
  negative signal.

**Step 1.3: Body**
- Record: [Bug] `hci_setup_ext_adv_instance_sync()` only calls
  `HCI_OP_LE_SET_EXT_ADV_ENABLE` disable for `instance > 0`. Legacy
  instance 0 stays enabled, so `HCI_OP_LE_SET_EXT_ADV_PARAMS` (opcode
  0x2036) is rejected with `HCI_ERROR_COMMAND_DISALLOWED` (0x0c).
- [Symptom] `btmgmt connectable on/off` while advertising is enabled
  fails with MGMT Busy (0x0a). dmesg: `Opcode 0x2036 failed: -16`.
- [Version] none stated.
- [Root cause] the disable-before-snapshot comment already describes the
  HCI rule; instance 0 was left out because
  `hci_disable_ext_adv_instance_sync(hdev, 0)` means “disable all sets”
  (`num_of_sets = !!instance`).

**Step 1.4: Hidden bug fix?**
- Record: Not disguised. This is an explicit correctness fix for a
  documented HCI restriction.

## Phase 2: Diff analysis

**Step 2.1: Inventory**
- Record: One file, `net/bluetooth/hci_sync.c`, +30/−0. New helper
  `hci_disable_ext_adv_legacy_instance_sync()`. Call added in
  `hci_setup_ext_adv_instance_sync()` `instance == 0` branch.
  Classification: single-file surgical fix.

**Step 2.2: Code flow**
- Before: `instance > 0` disables that set, then snapshots under lock.
  `instance == 0` only sets `adv = NULL` and proceeds to
  `hci_set_ext_adv_params_sync()`.
- After: instance 0 first sends `LE_SET_EXT_ADV_ENABLE` disable for
  handle 0x00 if `HCI_LE_ADV_0` is set; otherwise no-op. Then the
  existing param-update path runs.
- Path: normal MGMT connectable/discoverable/advertising
  reconfiguration, not an error-only path.

**Step 2.3: Bug mechanism**
- Record: [Logic / HCI command-order] Spec forbids updating parameters
  of an active extended advertising set. Non-legacy sets were already
  disabled. Legacy set 0 was not. Cannot reuse
  `hci_disable_ext_adv_instance_sync(hdev, 0)` because that function
  treats 0 as “all sets” (`cp->num_of_sets = !!instance`). New helper
  sends `num_of_sets=1`, `enable=0`, `handle=0x00`, gated on
  `HCI_LE_ADV_0`.

**Step 2.4: Fix quality**
- Record: Obviously correct: mirrors the instance>0 path and the
  existing enable command layout. Minimal. Regression risk is low:
  disable is skipped unless instance 0 is actually enabled;
  `hci_start_ext_adv_sync()` re-enables after setup. Same “if
  disable/setup fails, advertising may stay off” behavior as the non-
  legacy path. No public API change.

## Phase 3: Git history

**Step 3.1: Blame**
- Record: Disable-before-snapshot intent is from `cba6b758711c`
  (“Bluetooth: hci_sync: Make use of hci_cmd_sync_queue set 2”,
  2021-10). Current `if (instance > 0)` / `else { adv = NULL; }` shape
  is from `95cdcd8c82a50` (“Bluetooth: hci_sync: Fix advertising data
  UAFs”, Chengfeng Ye, already in this tree). `HCI_LE_ADV_0` is from
  `3a9dfe641913b` (stable backport of `0d92808024b4e`, 2025-10-01), also
  in this tree.

**Step 3.2: Fixes tag**
- Record: None. Bug is the incomplete original disable logic from
  `cba6b758711c`, which is in this tree. The correct instance-0 disable
  needs `HCI_LE_ADV_0`, which is also here.

**Step 3.3: File history**
- Record: Recent `hci_sync.c` work is UAF/locking (`95cdcd8c82a50`),
  advertising instance free on failure, accept-list UAF. No conflicting
  rewrite of this setup snapshot. Standalone patch, not `X/Y`.

**Step 3.4: Author**
- Record: Muhammad Saheed has this one Bluetooth commit on
  origin/master. Applied by subsystem maintainer Luiz Augusto von Dentz.

**Step 3.5: Prerequisites**
- Record: Needs `HCI_LE_ADV_0` (present: `3a9dfe641913b`) and the post-
  UAF `if (instance > 0) ... else { adv = NULL; }` shape (present:
  `95cdcd8c82a50`). `git apply --check` of `75722cde87ee2` succeeded
  (hunks at +21 lines). No later origin/master commit touches
  `hci_disable_ext_adv_legacy_instance_sync`. Standalone.

## Phase 4: Mailing list / external

**Step 4.1: Original discussion**
- Record: `b4 dig -c 75722cde87ee2` → https://patch.msgid.link/202608042
  01051.484885-1-muhammad.saheed.iam@gmail.com. Single v1, no later
  revision. Thread (gnuweeb lore, lore.kernel.org 403): submission,
  BlueZ CI bot, patchwork “applied to bluetooth-next by Luiz”. No NAK,
  no reviewer-requested changes.

**Step 4.2: Recipients (`b4 dig -w`)**
- Record: linux-bluetooth@vger.kernel.org, Luiz von Dentz, Marcel
  Holtmann. Right maintainers/list.

**Step 4.3: Bug report**
- Record: No external bugzilla/syzbot. Author included a concrete
  `btmgmt` repro and dmesg. Opcode 0x2036 is
  `HCI_OP_LE_SET_EXT_ADV_PARAMS` in this tree. HCI 0x0c maps to `EBUSY`
  in `bt_to_errno()`; mgmt maps `-EBUSY` to `MGMT_STATUS_BUSY` (0x0a).
  Matches the reported userspace error.

**Step 4.4: Series**
- Record: Standalone v1. Not part of a multi-patch series.

**Step 4.5: Stable list**
- Record: gnuweeb `/stable/` search for this subject returned no
  dedicated discussion (only unrelated release noise). No recorded
  reason to exclude it.

**CI note:** BlueZ bot: CheckPatch/build PASS. `mgmt-tester` 494/501 (LL
Privacy unpair timeouts, Read Exp Feature); mesh send-cancel timeouts.
Failures are not advertising/connectable cases. Maintainer still applied
the patch (`2d4711f5ad1b` in bluetooth-next; `75722cde87ee2` on
origin/master).

## Phase 5: Semantic / impact surface

**Step 5.1: Functions**
- Record: Added `hci_disable_ext_adv_legacy_instance_sync()`. Modified
  `hci_setup_ext_adv_instance_sync()`.

**Step 5.2: Callers of setup**
- Record (verified in this tree):
  - `hci_start_ext_adv_sync()` → connectable update, set advertising,
    discoverable+limited privacy, re-enable adv, periodic adv start
  - `hci_powered_update_adv_sync()` with instance 0x00
  - `set_le_sync()` in `mgmt.c` with 0x00
  - `add_ext_adv_params_sync()` uses `cp->instance` (MGMT rejects
    instance < 1, so not the legacy path)

**Step 5.3: Callees**
- Record: `__hci_cmd_sync_status(HCI_OP_LE_SET_EXT_ADV_ENABLE, ...)`.
  Same command the existing disable helper uses.

**Step 5.4: Reachability**
- Record: Userspace MGMT (`btmgmt`/`bluetoothctl` Set Connectable / Set
  Discoverable / Set Advertising). `hci_update_connectable_sync()` calls
  `hci_start_ext_adv_sync(hdev, hdev->cur_adv_instance)` when
  `HCI_ADVERTISING` is set; `set_adv_sync()` sets `cur_adv_instance =
  0x00`. Repro path is real and unprivileged for a local Bluetooth admin
  (typically root/netdev).

**Step 5.5: Similar patterns**
- Record: Instance > 0 already disabled before snapshot.
  `hci_disable_ext_adv_instance_sync()` cannot target only handle 0.
  `HCI_LE_ADV_0` was added specifically because instance 0 is not in
  `adv_instances`. This commit fills that remaining hole.

## Phase 6: Local tree (6.12.111, branch `pending-6.12`)

**Step 6.1: Buggy code present?**
- Record: Yes. `net/bluetooth/hci_sync.c`
  `hci_setup_ext_adv_instance_sync()` lines 1387–1400 still skip disable
  for instance 0. Helper name is absent (`grep` found no
  `hci_disable_ext_adv_legacy_instance_sync`). `git merge-base --is-
  ancestor 75722cde87ee2 HEAD` is false. Introduced conceptually in 2021
  (`cba6b758711c`); instance-0 tracking needed for a correct fix landed
  in this tree as `3a9dfe641913b`.

**Step 6.2: Backport difficulty**
- Record: Clean apply (`git apply --check` succeeded). Context matches
  after Chengfeng UAF backport.

**Step 6.3: Related fixes already here?**
- Record: `HCI_LE_ADV_0` tracking is here. Chengfeng UAF restructure is
  here. No substitute that disables legacy instance 0 before param
  snapshot.

## Phase 7: Subsystem context

**Step 7.1:** Record: `net/bluetooth` HCI command-sync / LE extended
advertising. Criticality: IMPORTANT (common controllers, BlueZ MGMT),
not core mm/fs.

**Step 7.2:** Record: Actively maintained; Luiz is the Bluetooth HCI
maintainer and applied this. Advertising instance 0 is the legacy “Set
Advertising” path used by typical desktop/embedded BlueZ setups.

## Phase 8: Impact and risk

**Step 8.1:** Record: Users of Bluetooth 5+ controllers
(`ext_adv_capable`) who enable LE advertising and then change
connectable/discoverable. Very common on modern hardware.

**Step 8.2:** Record: Trigger is ordinary `btmgmt connectable on/off`
(or equivalent bluetoothctl/DBus) while advertising is on. Not a rare
race. Local mgmt socket; not a remote unprivileged network attack.

**Step 8.3:** Record: Failure mode is HCI Command Disallowed → kernel
`-EBUSY` → MGMT Busy. Advertising parameters are not updated;
connectable/discoverable toggle fails. Not a panic/UAF. Severity: HIGH
for Bluetooth management (core LE advertising reconfiguration is
broken), MEDIUM overall versus crash/corruption.

**Step 8.4:** Record: Benefit high for 6.12 users with BT5 controllers.
Risk low: 30 lines, flag-gated, same command as existing helper, applies
cleanly, no API/data-structure change.

## Phase 9: Synthesis

**Step 9.1: Evidence**

FOR:
- Real, reproduced user-visible bug with matching opcode/status mapping
  in this tree
- Completes an already-documented disable-before-update rule that
  already exists for instance > 0
- Small, surgical, obviously correct
- Prerequisites (`HCI_LE_ADV_0`, setup-function shape) already in
  6.12.111
- Applies cleanly
- Maintainer-applied; v1 only; no NAK
- Common mgmt path, not staging/experimental

AGAINST:
- Not a crash, UAF, leak, or CVE
- Workaround: turn advertising off, change connectable, turn it back on
- First-time author (mitigated by maintainer SOB)
- BlueZ CI had unrelated tester timeouts

UNRESOLVED:
- lore.kernel.org HTTP 403; thread read via b4 + gnuweeb instead
- No dedicated stable-list thread

**Step 9.2: Stable rules**
1. Obviously correct and tested? **PASS** — mirrors existing disable
   path; author repro; kernel + mgmt-tester build; maintainer applied
2. Real bug affecting users? **PASS** — connectable toggle fails while
   advertising
3. Important? **PASS** — breaks LE advertising reconfiguration on ext-
   adv hardware (Busy, not oops, but a serious functional failure of a
   common mgmt operation)
4. Small and contained? **PASS** — +30 lines, one file
5. No new features/APIs? **PASS** — HCI command already used; no new
   userspace API
6. Applies to this tree? **PASS** — verified `git apply --check`

**Step 9.3: Exceptions**
- Record: Not a device-ID/quirk/DT/build/docs exception. Qualifies as a
  contained functional HCI bug fix.

**Step 9.4: Decision**
This 6.12 tree still has the instance-0 hole. The helper it needs can
use `HCI_LE_ADV_0`, which is already backported. The patch is small,
applies, and restores a management operation that fails on typical
Bluetooth 5 controllers. That is enough for this tree.

---

### What the commit solves, and why it matters here

On 6.12.111, enabling LE advertising (legacy instance 0) and then
changing connectable/discoverable issues `LE Set Extended Advertising
Parameters` while that set is still enabled. Controllers reject it
(`0x0c` → `-EBUSY` → MGMT Busy). Non-legacy instances were already
disabled first; instance 0 was not, because the generic disable helper
treats 0 as “all sets.” This commit disables only handle 0x00 when
`HCI_LE_ADV_0` is set, then continues the existing snapshot/update/re-
enable flow.

### Risk vs benefit

Benefit: restores a common BlueZ management operation on ext-adv
hardware. Risk: low; disable is conditional, command layout matches the
existing helper, and `hci_start_ext_adv_sync()` re-enables afterward. No
follow-up fix exists on origin/master.

### Concerns

None that block backport on this tree. Prerequisites are present. Apply
is clean. Not a crash, but the failure is user-visible and easy to hit.

### Verification
- [Phase 1] Parsed subject/body/tags from `git log -1 --format=fuller
  75722cde87ee2`; no Fixes/Cc/Reported-by
- [Phase 2] Diff: +30 in `hci_sync.c`; helper + 4-line call in
  instance==0 branch
- [Phase 2] Confirmed `hci_disable_ext_adv_instance_sync()` uses
  `cp->num_of_sets = !!instance` so instance 0 disables all sets
- [Phase 2] Confirmed opcode 0x2036 is `HCI_OP_LE_SET_EXT_ADV_PARAMS`;
  `bt_to_errno(0x0c)=EBUSY`; mgmt `-EBUSY` → Busy 0x0a
- [Phase 3] `git describe HEAD` / `make kernelversion`: pending-6.12,
  6.12.111
- [Phase 3] `git merge-base --is-ancestor 75722cde87ee2 HEAD`: not in
  tree
- [Phase 3] blame: disable comment from `cba6b758711c`; `if (instance >
  0)` from `95cdcd8c82a50`; `HCI_LE_ADV_0` from `3a9dfe641913b`
- [Phase 3] `git merge-base --is-ancestor 3a9dfe641913b HEAD`: yes;
  `95cdcd8c82a50` in HEAD: yes
- [Phase 3] `git apply --check` of 75722cde87ee2: success
- [Phase 3] `git log origin/master -S
  hci_disable_ext_adv_legacy_instance_sync -- net/bluetooth/hci_sync.c`:
  only this commit
- [Phase 4] `b4 dig -c 75722cde87ee2` / `-a` / `-w`: v1 only; Luiz +
  linux-bluetooth; lore msgid as above
- [Phase 4] gnuweeb thread: CI bot + patchwork applied; no NAK
- [Phase 4] lore.kernel.org WebFetch: 403 (used b4/gnuweeb)
- [Phase 5] Callers traced in `hci_sync.c` / `mgmt.c`; connectable path
  uses `cur_adv_instance` (0 after Set Advertising)
- [Phase 6] Local setup function still skips disable for instance 0
- [Phase 8] Failure: MGMT Busy, not oops; severity HIGH for BT mgmt,
  MEDIUM vs crash class
- UNVERIFIED: Could not fetch lore.kernel.org HTML directly (403)

**YES**

 net/bluetooth/hci_sync.c | 30 ++++++++++++++++++++++++++++++
 1 file changed, 30 insertions(+)

diff --git a/net/bluetooth/hci_sync.c b/net/bluetooth/hci_sync.c
index 70fce6811d0a9..8da58c61e9723 100644
--- a/net/bluetooth/hci_sync.c
+++ b/net/bluetooth/hci_sync.c
@@ -1184,6 +1184,32 @@ int hci_update_random_address_sync(struct hci_dev *hdev, bool require_privacy,
 	return 0;
 }
 
+static int hci_disable_ext_adv_legacy_instance_sync(struct hci_dev *hdev)
+{
+	struct hci_cp_le_set_ext_adv_enable *cp;
+	struct hci_cp_ext_adv_set *set;
+	u8 data[sizeof(*cp) + sizeof(*set) * 1];
+	u8 size;
+
+	if (!hci_dev_test_flag(hdev, HCI_LE_ADV_0))
+		return 0;
+
+	memset(data, 0, sizeof(data));
+
+	cp = (void *)data;
+	set = (void *)cp->data;
+
+	cp->num_of_sets = 0x01;
+	cp->enable = 0x00;
+
+	set->handle = 0x00;
+
+	size = sizeof(*cp) + sizeof(*set) * cp->num_of_sets;
+
+	return __hci_cmd_sync_status(hdev, HCI_OP_LE_SET_EXT_ADV_ENABLE,
+				     size, data, HCI_CMD_TIMEOUT);
+}
+
 static int hci_disable_ext_adv_instance_sync(struct hci_dev *hdev, u8 instance)
 {
 	struct hci_cp_le_set_ext_adv_enable *cp;
@@ -1409,6 +1435,10 @@ int hci_setup_ext_adv_instance_sync(struct hci_dev *hdev, u8 instance)
 			return -EINVAL;
 		}
 	} else {
+		err = hci_disable_ext_adv_legacy_instance_sync(hdev);
+		if (err)
+			return err;
+
 		adv = NULL;
 	}
 
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH AUTOSEL 6.18] Bluetooth: btnxpuart: Fix use-after-free in probe error path
       [not found] <20261019135441.1420968-1-sashal@kernel.org>
                   ` (7 preceding siblings ...)
  2026-10-19 13:50 ` [PATCH AUTOSEL 6.18-6.1] Bluetooth: hci_sync: Disable legacy instance's ext adv before setup snapshot Sasha Levin
@ 2026-10-19 13:51 ` Sasha Levin
  2026-10-19 13:52 ` [PATCH AUTOSEL 6.18] Bluetooth: fix BT dependency for submodules Sasha Levin
  9 siblings, 0 replies; 10+ messages in thread
From: Sasha Levin @ 2026-10-19 13:51 UTC (permalink / raw)
  To: patches, stable
  Cc: Zhao Dongdong, Neeraj Sanjay Kale, Luiz Augusto von Dentz,
	Sasha Levin, amitkumar.karwar, marcel, luiz.dentz,
	linux-bluetooth, linux-kernel

From: Zhao Dongdong <zhaodongdong@kylinos.cn>

[ Upstream commit a2b3b4f00403a3a40c5627d1bf537c8fb166e221 ]

In nxp_serdev_probe(), if hci_register_dev() succeeds but ps_setup()
fails, the error path jumps to 'probe_fail' which only calls
hci_free_dev() and asserts the reset GPIO, but does NOT call
hci_unregister_dev() first.

This leaves the HCI device registered in the system with its backing
memory freed, leading to a use-after-free when userspace subsequently
accesses the device (e.g. via hciconfig or bluetoothd).

Fix by adding a 'probe_fail_unregister' label that calls
hci_unregister_dev() before falling through to the existing
'probe_fail' label. The original 'probe_fail' label is preserved
for the case where hci_register_dev() itself fails (device was
never registered, so no unregister is needed).

Signed-off-by: Zhao Dongdong <zhaodongdong@kylinos.cn>
Reviewed-by: Neeraj Sanjay Kale <neeraj.sanjaykale@nxp.com>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
Signed-off-by: Sasha Levin <sashal@kernel.org>
---

LLM Generated explanations, may be completely bogus:

The local tree is **6.18.53** (`pending-6.18`). The probe-path UAF is
present here, the fix is a 3-line unregister-before-free, and it should
be backported.

---

## PHASE 1: COMMIT MESSAGE FORENSICS

**Step 1.1: PARSE THE SUBJECT LINE**

Record: **[Bluetooth / btnxpuart] [Fix] [use-after-free in
`nxp_serdev_probe()` when `ps_setup()` fails after a successful
`hci_register_dev()`]**

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**

Record:
- **Fixes:** none (expected for this review pipeline)
- **Reported-by:** none
- **Tested-by:** none
- **Reviewed-by:** Neeraj Sanjay Kale `<neeraj.sanjaykale@nxp.com>`
  (listed `MAINTAINERS` co-maintainer of NXP Bluetooth)
- **Acked-by:** none
- **Link:** none
- **Cc: stable:** none (expected; not a negative)
- **Signed-off-by:** Zhao Dongdong `<zhaodongdong@kylinos.cn>` (author);
  Luiz Augusto von Dentz `<luiz.von.dentz@intel.com>` (Bluetooth
  maintainer)
- Pipeline SOBs (Sasha Levin / Upstream commit markers): ignored per
  instructions

Notable: maintainer review + Bluetooth maintainer SOB. No syzbot tag.

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**

Record:
- **Bug:** After `hci_register_dev()` succeeds, `ps_setup()` failure
  jumps to `probe_fail`, which asserts reset and calls `hci_free_dev()`
  without `hci_unregister_dev()`.
- **Symptom:** HCI device stays registered after its driver backing is
  torn down; userspace (`hciconfig`, bluetoothd) can then UAF.
- **Version info:** none in the message.
- **Root cause (author):** missing unregister on the post-register error
  path; `probe_fail` is correct only when registration itself failed.

**Step 1.4: DETECT HIDDEN BUG FIXES**

Record: **Not a hidden fix.** Subject and body explicitly describe a
UAF. The code change matches that description.

---

## PHASE 2: DIFF ANALYSIS - LINE BY LINE

**Step 2.1: INVENTORY THE CHANGES**

Record:
- **File:** `drivers/bluetooth/btnxpuart.c` only
- **Scope:** +3 / −1 (one function)
- **Function:** `nxp_serdev_probe()`
- **Classification:** single-file surgical error-path fix

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**

Record (verified against this tree at `nxp_serdev_probe()`):

**Before** (local `drivers/bluetooth/btnxpuart.c` lines 1919–1935):
```
if (hci_register_dev(hdev) < 0)
    goto probe_fail;
if (ps_setup(hdev))
    goto probe_fail;          // registered, but treated as never-
registered
...
probe_fail:
    reset_control_assert(nxpdev->pdn);
    hci_free_dev(hdev);
    return -ENODEV;
```

**After:**
- `ps_setup()` failure → `probe_fail_unregister` →
  `hci_unregister_dev(hdev)` then fall through
- `hci_register_dev()` failure still goes to `probe_fail` only (never
  registered)

**Path affected:** probe error path only, after successful HCI
registration.

**Step 2.3: IDENTIFY THE BUG MECHANISM**

Record:
- **Category:** use-after-free / lifetime bug (error-path cleanup)
- **Mechanism:** `hci_register_dev()` (`net/bluetooth/hci_core.c`) does
  `device_add()`, `hci_dev_hold()`, and `queue_work(...,
  &hdev->power_on)`. `hci_free_dev()` is only `put_device()`. Skipping
  unregister leaves `hdev` on `hci_dev_list` and in sysfs.
- **Worse than the message states (verified):** `nxpdev` is
  `devm_kzalloc()` at probe start. Probe returning `-ENODEV` releases
  managed resources, so `nxpdev` is freed while a still-registered
  `hdev` has `hci_set_drvdata(hdev, nxpdev)`. HCI callbacks
  (`btnxpuart_open`, `nxp_setup`, power-on work) then dereference freed
  driver state.
- **Fix:** same unregister-then-free order as `nxp_serdev_remove()`
  (local lines 1959–1962).

**Step 2.4: ASSESS THE FIX QUALITY**

Record:
- Obviously correct: pairs register with unregister; preserves the
  never-registered path.
- Minimal: 3 insertions, 1 deletion, no API/struct changes.
- Regression risk: low. `hci_unregister_dev()` is the designed teardown
  (cancels `power_on` via `disable_work_sync`). Probe failure means
  `remove()` is not called, so no double-unregister.
- Does not call `ps_cleanup()` on this path: correct, because
  `ps_setup()`’s only error return is `devm_gpiod_get_optional()`
  failure **before** `INIT_WORK` / `timer_setup` / `mutex_init` (local
  lines 511–517 vs 557–561). Calling `ps_cleanup()` there would operate
  on uninitialized state.

---

## PHASE 3: GIT HISTORY INVESTIGATION

**Step 3.1: BLAME THE CHANGED LINES**

Record:
- Buggy `if (ps_setup(hdev)) goto probe_fail;` introduced by
  **`c135a5bc34a89a75a739d07964ff3d1c4fa1b154`** (“Bluetooth: btnxpuart:
  Add GPIO support to power save feature”, Neeraj Sanjay Kale, committer
  date 2024-11-14).
- That commit changed `ps_setup()` from `void` to `int` and added the
  `probe_fail` label that frees without unregister.
- `git merge-base --is-ancestor c135a5bc34a89a HEAD` → **yes**. Makefile
  at that commit is **6.12.0-rc6**; this 6.18.53 tree contains the bug.
- Driver itself: `689ca16e523278` (2023-04-23). Original probe had
  `ps_setup()` as void after register, so it could not fail after
  register until `c135a5bc34a89`.

**Step 3.2: FOLLOW THE FIXES: TAG**

Record: No `Fixes:` tag. The real introducer is `c135a5bc34a89`, not the
original driver add. A later duplicate patch (Myeonghun Pak) incorrectly
tagged `Fixes: 689ca16e5232`. Absence of Fixes here does not change the
local-tree fact: the buggy goto is in this checkout.

**Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES**

Record:
- Recent `btnxpuart.c` work is firmware dump, OOB, IRQ, baudrate,
  coredump — none of it unregisters on the `ps_setup()` fail path.
- `git log --grep="use-after-free" -- drivers/bluetooth/btnxpuart.c` →
  empty.
- `probe_fail_unregister` is **not** in this tree.
- Standalone; not “patch X/Y”. v2 changelog was SubjectPrefix; v3 was
  gitlint. Same 3-line diff.

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**

Record: `git log --author="Zhao Dongdong" -- drivers/bluetooth/` in this
tree has no btnxpuart commits (author is not the NXP driver maintainer).
Weight comes from **Reviewed-by: Neeraj** (NXP maintainer) and **SOB:
Luiz** (Bluetooth maintainer). Neeraj is the author of the introducing
commit and of most later btnxpuart work.

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS**

Record: No new helpers. Uses existing `hci_unregister_dev()`. Local
probe matches the hunk (same `ps_setup` / `hci_devcd_register` /
`probe_fail` sequence). **Can apply standalone.**

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**

Record:
- `b4 dig -c <msgid>` for v1 msgid
  `tencent_05373BA21CEEB5195F2ECCED0C77D0C57108@qq.com` → no matching
  **commit** in this tree (expected: candidate not merged here).
- Lore.kernel.org fetches returned **403**.
- Discussion reconstructed from ratatoskr / spinics / lkml.iu.edu:
  - v1/v2/v3 by Zhao Dongdong, mid-May 2026, linux-bluetooth
  - v3: https://ratatoskr.run/linux-bluetooth/2026/05/9706550
  - Luiz replied 2026-05-15; Neeraj reviewed 2026-06-03
  - Revisions were cosmetic (prefix, gitlint), not logic changes
- **UNVERIFIED:** exact text of Luiz’s review comment (patchwork
  presented a bot wall; lore 403)

**Step 4.2: CHECK WHO REVIEWED THE PATCH**

Record: Recipients/maintainers from public threads: Luiz von Dentz,
Marcel Holtmann, Amitkumar Karwar, Neeraj Kale, linux-bluetooth.
Committed form has Neeraj `Reviewed-by` and Luiz SOB. No NAK found.

**Step 4.3: SEARCH FOR THE BUG REPORT**

Record: No syzbot/bugzilla link. Independent second patch (Myeonghun Pak
/ Ijae Kim, 2026-06-26, “unregister HCI device on probe failure”)
describes the same bug. Neeraj told them Zhao’s patch was already
approved and waiting on Luiz. Two independent submissions = real issue,
not one-off theory.

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**

Record: Standalone. Duplicate later patch is the same 3-line change with
a different label name (`unregister_dev` vs `probe_fail_unregister`). No
series dependency.

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**

Record: `WebFetch` of lore.kernel.org/stable returned 403.
**UNVERIFIED:** whether stable@ already discussed this specific commit.
No evidence it was rejected for stable.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

**Step 5.1: IDENTIFY KEY FUNCTIONS IN THE DIFF**

Record: `nxp_serdev_probe()` only. Calls added: `hci_unregister_dev()`.

**Step 5.2: TRACE CALLERS**

Record: `.probe = nxp_serdev_probe` in the serdev driver (local ~line
2030). Invoked on UART child-device bind (`compatible =
"nxp,88w8987-bt"` / `"nxp,88w8997-bt"`), not a syscall. Userspace
reaches the **aftermath** via HCI (`bluetoothd`, `hciconfig`) once the
device is left registered.

**Step 5.3: TRACE CALLEES**

Record:
- `hci_register_dev()`: `device_add`, list insert, `hci_dev_hold`,
  `queue_work(power_on)`
- `hci_unregister_dev()`: `HCI_UNREGISTER`, `list_del`,
  `disable_work_sync(power_on)`, close, mgmt removal
- `hci_free_dev()`: `put_device`
- `ps_setup()`: optional GPIO; only hard-fail is
  `IS_ERR(devm_gpiod_get_optional(...))`

**Step 5.4: FOLLOW THE CALL CHAIN**

Record:
1. Serdev probe for NXP UART BT
2. `hci_register_dev` → `hci0` visible; `power_on` queued
3. `ps_setup` fails
4. Probe returns error without unregister → `devm` frees `nxpdev`
5. HCI core / userspace / leftover `power_on` uses `hdev` callbacks →
   UAF

Reachable on any board using this driver with `device-wakeup-gpios` that
fails to resolve (property present, GPIO unavailable / `-EPROBE_DEFER`
converted to `-ENODEV`). Binding:
`Documentation/devicetree/bindings/net/bluetooth/nxp,88w8987-bt.yaml`
documents that GPIO. In-tree users of the compatible include i.MX
91/93/95 EVKs, i.MX8MP, TI Verdin AM62, Kobo Clara 2E.

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**

Record: Other Bluetooth UART drivers typically only `hci_free_dev()`
when **register** fails. This driver’s bug is specifically “work after
register that can fail.” Remove path already had the correct
unregister/free order.

---

## PHASE 6: CROSS-REFERENCING AGAINST THE LOCAL TREE

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?**

Record: **Yes.** `pending-6.18`, `make kernelversion` = **6.18.53**.
Exact snippet at lines 1924–1935 of `drivers/bluetooth/btnxpuart.c`.
Introduced in `c135a5bc34a89` (~6.13 era); present here. Candidate fix
**not** an ancestor of HEAD.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**

Record: **Clean apply.** Surrounding code matches the supplied hunk
(`hci_register_dev` / `ps_setup` / `hci_devcd_register` / `probe_fail` +
`reset_control_assert`). Line numbers differ slightly from the candidate
blob; context is the same. No conflicting refactor.

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**

Record: No unregister-on-`ps_setup`-fail fix. Other btnxpuart stable-
style fixes in this tree (OOB firmware read, FW dump header length) are
unrelated.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

**Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY**

Record:
- **Subsystem:** Bluetooth device driver
  (`drivers/bluetooth/btnxpuart.c`)
- **Criticality:** **IMPORTANT** (not core mm/VFS). Real shipping
  hardware (NXP 88W8987/8997 on i.MX and TI K3). `CONFIG_BT_NXPUART`
  depends on `BT_HCIUART` and `SERIAL_DEV_BUS`.

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**

Record: Actively maintained (many 2025 btnxpuart commits in this tree).
Bug is in a 2024 error-path addition that has sat unfixed.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

**Step 8.1: DETERMINE WHO IS AFFECTED**

Record: **Driver-specific / config-specific:** `CONFIG_BT_NXPUART` users
with NXP UART Bluetooth, especially DTs that include `device-wakeup-
gpios`.

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**

Record:
- Trigger: `ps_setup()` returns non-zero after successful
  `hci_register_dev()`.
- In this tree that is `devm_gpiod_get_optional("device-wakeup")`
  returning `IS_ERR` (GPIO specified but cannot be acquired). IRQ setup
  failures are ignored, not a probe fail.
- Not every boot. GPIO probe deferral / missing controller / bad DT are
  realistic.
- Unprivileged userspace does not need to *cause* the probe fail; once
  it happens, bluetoothd/hciconfig can trip the UAF. Concurrent
  `power_on` work can trip it without userspace.

**Step 8.3: DETERMINE THE FAILURE MODE SEVERITY**

Record:
- **Failure mode:** UAF of `btnxpuart_dev` (devm-freed) and/or HCI
  object lifetime violation while `hciX` remains registered; possible
  oops; `power_on` work not cancelled.
- **Severity: HIGH** (UAF / crash). Not a panic on every boot, but
  classically stable-worthy.

**Step 8.4: CALCULATE RISK-BENEFIT RATIO**

Record:
- **Benefit:** HIGH for affected hardware — prevents UAF/oops on a real
  probe failure.
- **Risk:** VERY LOW — 3 lines, existing API, same order as `remove()`,
  error path only.
- **Ratio:** strongly favors backport.

---

## PHASE 9: FINAL SYNTHESIS

**Step 9.1: COMPILE THE EVIDENCE**

**FOR:**
- Confirmed UAF / lifetime bug in this 6.18.53 tree
- Small, obviously correct unregister-before-free
- Matches `nxp_serdev_remove()`
- Cancels `power_on` work that `hci_register_dev()` queued
- NXP driver maintainer Reviewed-by; Bluetooth maintainer SOB
- Independent duplicate patch
- Clean apply; no prerequisites
- Real in-tree hardware (i.MX, TI K3)

**AGAINST:**
- Driver-specific, not core kernel
- Trigger is an error path (`ps_setup` GPIO get fail), not every probe
- No syzbot/CVE/Reported-by
- No Fixes tag (not a reason to reject)

**UNRESOLVED (do not drive the verdict):**
- Exact Luiz review comment text
- Mainline SHA of the candidate (not in this tree)
- stable@ discussion (lore 403)

**Step 9.2: APPLY THE STABLE RULES CHECKLIST**

1. Obviously correct and tested? **PASS** — pairing is the documented
   HCI lifetime; reviewed by driver + Bluetooth maintainers.
2. Fixes a real bug that affects users? **PASS** — registered HCI left
   after probe fail; UAF via callbacks/userspace.
3. Important issue? **PASS** — UAF / crash, HIGH (not
   deadlock/corruption, still stable-class).
4. Small and contained? **PASS** — 3 lines, one function.
5. No new features or APIs? **PASS**
6. Can apply to the local tree? **PASS** — buggy code present; hunk
   matches.

**Step 9.3: CHECK FOR EXCEPTION CATEGORIES**

Record: Not ID/quirk/DT/build/docs. It is a **normal UAF bugfix**, which
is in-scope without an exception.

**Step 9.4: MAKE YOUR DECISION**

This 6.18.53 tree has the buggy `ps_setup()` → `probe_fail` path from
`c135a5bc34a89`. The fix is the missing `hci_unregister_dev()` before
`hci_free_dev()`. That is required HCI lifetime management, matches
remove(), and prevents UAF of `devm`-managed driver state while `hciX`
stays registered. Scope and risk are appropriate for stable.

---

### What the commit solves for this tree

On NXP UART Bluetooth probe, if HCI registration succeeds and then
power-save GPIO setup fails, 6.18.53 currently frees the HCI object
(and, via `devm`, the driver private data) without unregistering.
Userspace and the queued `power_on` work can then use freed memory. The
backport adds one unregister on that path only.

### Stable rules / risk vs benefit

Meets all six criteria. Benefit is preventing a UAF on a shipping
driver; risk is a 3-line error-path change that uses the existing
unregister helper.

### Concerns

None that block backport. Trigger is uncommon (GPIO get failure), but
the failure mode is severe enough. No extra commits needed.

---

### Verification

- **[Phase 1]** Parsed subject/tags/body: UAF fix; Reviewed-by Neeraj;
  SOB Luiz; no Fixes/syzbot/Cc-stable
- **[Phase 2]** Diff: +3/−1 in `nxp_serdev_probe()`; `ps_setup` fail now
  unregisters before free
- **[Phase 2]** Read local probe/remove/`ps_setup`: bug and GPIO-only
  fail return confirmed
- **[Phase 2]** Read
  `hci_register_dev`/`hci_unregister_dev`/`hci_free_dev`: register
  queues `power_on` and holds refs; free is `put_device` only
- **[Phase 3]** `git describe HEAD` / `make kernelversion`:
  `p-6.18-1-g03b85e06ca9bf`, **6.18.53**
- **[Phase 3]** `git blame -L 1915,1940`: buggy goto from
  `c135a5bc34a89`
- **[Phase 3]** `git merge-base --is-ancestor c135a5bc34a89a HEAD`: yes
- **[Phase 3]** `git show c135a5bc34a89a`: introduced int `ps_setup` +
  `goto probe_fail` without unregister
- **[Phase 3]** Original driver `689ca16e523278`: `ps_setup` could not
  fail after register
- **[Phase 3]** `git log --grep="use-after-free"` on this file: empty;
  fix not in tree
- **[Phase 4]** `b4 dig` on v1 msgid: no commit in this tree
- **[Phase 4]** lore.kernel.org: 403 — UNVERIFIED full thread body
- **[Phase 4]** ratatoskr v3 + lkml.iu.edu: v1–v3 standalone; Neeraj
  approved; duplicate June 2026 patch
- **[Phase 5]** Callers: serdev `.probe`; `nxpdev` is `devm_kzalloc`
- **[Phase 5]** DTS: `nxp,88w8987-bt` on i.MX and TI boards; binding
  documents `device-wakeup-gpios`
- **[Phase 6]** Exact buggy snippet present; `probe_fail_unregister`
  absent
- **[Phase 8]** Failure: UAF/oops on probe error after register;
  severity HIGH
- **UNVERIFIED:** Luiz comment text; candidate mainline SHA; stable@
  archive

The fix is small, surgical, already in the local probe shape, and
addresses a real UAF.

**YES**

 drivers/bluetooth/btnxpuart.c | 4 +++-
 1 file changed, 3 insertions(+), 1 deletion(-)

diff --git a/drivers/bluetooth/btnxpuart.c b/drivers/bluetooth/btnxpuart.c
index c7acf6c7efcf6..870ce16ad40b1 100644
--- a/drivers/bluetooth/btnxpuart.c
+++ b/drivers/bluetooth/btnxpuart.c
@@ -1924,13 +1924,15 @@ static int nxp_serdev_probe(struct serdev_device *serdev)
 	}
 
 	if (ps_setup(hdev))
-		goto probe_fail;
+		goto probe_fail_unregister;
 
 	hci_devcd_register(hdev, nxp_coredump, nxp_coredump_hdr,
 			   nxp_coredump_notify);
 
 	return 0;
 
+probe_fail_unregister:
+	hci_unregister_dev(hdev);
 probe_fail:
 	reset_control_assert(nxpdev->pdn);
 	hci_free_dev(hdev);
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

* [PATCH AUTOSEL 6.18] Bluetooth: fix BT dependency for submodules
       [not found] <20261019135441.1420968-1-sashal@kernel.org>
                   ` (8 preceding siblings ...)
  2026-10-19 13:51 ` [PATCH AUTOSEL 6.18] Bluetooth: btnxpuart: Fix use-after-free in probe error path Sasha Levin
@ 2026-10-19 13:52 ` Sasha Levin
  9 siblings, 0 replies; 10+ messages in thread
From: Sasha Levin @ 2026-10-19 13:52 UTC (permalink / raw)
  To: patches, stable
  Cc: Iva Kasprzaková, Luiz Augusto von Dentz, Sasha Levin, marcel,
	luiz.dentz, linux-bluetooth, linux-kernel

From: Iva Kasprzaková <iva@yenya.net>

[ Upstream commit 6ec1896b5331563fedf3f01014aba9c9e35d7f29 ]

The modules rfcomm (BT_RFCOMM), bnep (BT_BNEP), hidp (BT_HIDP), and
bluetooth_6lowpan (BT_6LOWPAN) are dependent on the bluetooth module
(BT, tristate) only transitively through the boolean BT_BREDR for the
first three and through the boolean BT_LE for the bluetooth_6lowpan.
Therefore, the modules can be selected as built-in even if the BT=m.
The combination of BT=m and =y for the said modules leads to the kernel
build system silently ignoring those modules, without ever compiling
them as built-in or as loadable modules.

Add BT as a direct dependency to the Kconfig of rfcomm, bnep, hidp, and
bluetooth_6lowpan. The modules set to =y when BT=m will default to =m,
rather then getting silently ignored by the build system.

Signed-off-by: Iva Kasprzaková <iva@yenya.net>
Signed-off-by: Luiz Augusto von Dentz <luiz.von.dentz@intel.com>
Signed-off-by: Sasha Levin <sashal@kernel.org>
---

LLM Generated explanations, may be completely bogus:

The local tree is **6.12.111** (`pending-6.12`). The buggy Kconfig is
present here; the fix is a small, correct build/config change that
should be backported.

---

## PHASE 1: COMMIT MESSAGE FORENSICS

**Step 1.1: PARSE THE SUBJECT LINE**
Record: `[Bluetooth] [fix] Make RFCOMM/BNEP/HIDP/6LoWPAN depend directly
on tristate CONFIG_BT so they cannot be =y when BT=m`

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**
Record:
- Signed-off-by: Iva Kasprzaková \<iva@yenya.net\> (author)
- Signed-off-by: Luiz Augusto von Dentz \<luiz.von.dentz@intel.com\>
  (Bluetooth maintainer)
- No Fixes:, Reported-by, Tested-by, Reviewed-by, Acked-by, Link:, or
  Cc: stable
- Absence of Fixes:/Cc: stable is expected for this review queue and is
  not a negative

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**
Record:
- **Bug:** RFCOMM, BNEP, HIDP, and 6LoWPAN depend on CONFIG_BT only
  through boolean `BT_BREDR` / `BT_LE`. A boolean that depends on a
  tristate is `y` when the tristate is `m`, so the protocol options can
  be `y` while `BT=m`.
- **Symptom:** Those protocols are silently not compiled (neither built-
  in nor as modules).
- **Fix:** Add `depends on BT` so `=y` with `BT=m` becomes `=m` and they
  actually build.
- **Version info:** None in the message. Root cause is kconfig
  tristate/bool transitivity.

**Step 1.4: DETECT HIDDEN BUG FIXES**
Record: Not hidden. This is an explicit Kconfig/build correctness fix,
not cleanup-as-fix.

---

## PHASE 2: DIFF ANALYSIS

**Step 2.1: INVENTORY THE CHANGES**
Record:
- `net/bluetooth/Kconfig`: `BT_6LOWPAN` `depends on BT_LE && 6LOWPAN` →
  `depends on BT && BT_LE && 6LOWPAN`
- `net/bluetooth/bnep/Kconfig`: `BT_BNEP` `depends on BT_BREDR` →
  `depends on BT && BT_BREDR`
- `net/bluetooth/hidp/Kconfig`: `BT_HIDP` `depends on BT_BREDR && HID` →
  `depends on BT && BT_BREDR && HID`
- `net/bluetooth/rfcomm/Kconfig`: `BT_RFCOMM` `depends on BT_BREDR` →
  `depends on BT && BT_BREDR`
- **Scope:** 4 files, 4 insertions / 4 deletions. Surgical Kconfig-only
  change.

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**
Record: Before, Kconfig allowed `BT=m` + protocol `=y`. After, `depends
on BT` forces the protocol to follow BT’s tristate (`m` if BT is `m`).
No C code or ABI change.

**Step 2.3: IDENTIFY THE BUG MECHANISM**
Record: **Build/Kconfig correctness** (documented stable exception:
build fix). Mechanism: `net/Makefile` has `obj-$(CONFIG_BT) +=
bluetooth/`. With `BT=m` the bluetooth directory is descended as a
module (`need-builtin` unset). `scripts/Makefile.lib` then does `obj-y
:= $(filter-out %/, $(obj-y))`, so `rfcomm/` / `bnep/` / `hidp/` listed
as `obj-y` are dropped and never built.

**Step 2.4: ASSESS THE FIX QUALITY**
Record: Obviously correct (standard tristate `depends on` pattern).
Minimal. Regression risk is very low: the only configs that change are
invalid ones (`BT=m` + proto `=y`), which currently produce missing
modules; they become `=m` and actually work. No API or data-structure
change.

---

## PHASE 3: GIT HISTORY INVESTIGATION

**Step 3.1: BLAME THE CHANGED LINES**
Record: The broken `depends on BT_BREDR` / `depends on BT_LE` lines come
from **65efd2bf48853** (“Bluetooth: Introduce BT_BREDR and BT_LE config
options”, Marcel Holtmann, 2014-11-02). That commit replaced `depends on
BT` with the booleans. Present since ~v3.19; well before 6.12.

**Step 3.2: FOLLOW THE FIXES: TAG**
Record: No Fixes: tag. The introducing commit is in this tree (`git
merge-base --is-ancestor 65efd2bf48853 HEAD` succeeded). Upstream fix
SHA from patchwork: **646d8e385271** — **not** an ancestor of this HEAD.

**Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES**
Record:
- HIDP extra deps: **6cc90ccd4f6cf** (“HID: fix BT_HIDP Kconfig
  dependencies”, 2022) — **in this tree**. Local line is `depends on
  BT_BREDR && INPUT && HID_SUPPORT` plus `select HID`, not upstream’s
  `depends on BT_BREDR && HID`.
- CMTP still exists here (`depends on BT_BREDR && ISDN_CAPI &&
  DEPRECATED`) and has the same class of bug; this patch does not touch
  it (CMTP was later removed). Standalone otherwise; v2 only added
  6LoWPAN.

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**
Record: Iva Kasprzaková has no other commits in this tree’s bluetooth
history. Luiz von Dentz (SOB / applier) is the Bluetooth maintainer.

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS**
Record: No functional prerequisites. HIDP hunk needs a one-line context
tweak (`BT && BT_BREDR && INPUT && HID_SUPPORT`). RFCOMM, BNEP, and
6LoWPAN match this tree exactly.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**
Record:
- Lore/msgid:
  https://patch.msgid.link/20260722130849.7813-1-iva@yenya.net
- v1: 2026-07-20 \<20260720150919.9602-1-iva@yenya.net\>
- v2 (applied): 2026-07-22
- Luiz asked v1 to also cover `BT_6LOWPAN`; v2 did that. No NAKs. No
  reviewer `Cc: stable`. Applied to bluetooth-next as 646d8e385271; in
  bluetooth-next pull 2026-08-07.

**Step 4.2: CHECK WHO REVIEWED THE PATCH**
Record: Recipients: Marcel Holtmann, Luiz von Dentz, linux-bluetooth.
Luiz requested the 6LoWPAN addition and applied v2. BlueZ CI:
CheckPatch/BuildKernel/IncrementalBuild PASS; mgmt/mesh tester fails
look pre-existing, not caused by this Kconfig change.

**Step 4.3: SEARCH FOR THE BUG REPORT**
Record: No syzbot/bugzilla. Author analysis plus maintainer
confirmation. **In-tree proof:** `arch/arm/configs/s5pv210_defconfig`
has `CONFIG_BT=m`, `CONFIG_BT_RFCOMM=y`, `CONFIG_BT_BNEP=y`.

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**
Record: Single-patch series. v1→v2 only added 6LoWPAN. Not part of a
larger refactor.

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**
Record: gnuweeb stable search for this subject found no discussion of
this patch (unrelated “dependency” hits only).

---

## PHASE 5: CODE SEMANTIC ANALYSIS

**Step 5.1: IDENTIFY KEY FUNCTIONS IN THE DIFF**
Record: No C functions. Symbols: `BT_RFCOMM`, `BT_BNEP`, `BT_HIDP`,
`BT_6LOWPAN`. Build sites: `net/bluetooth/Makefile`
`obj-$(CONFIG_BT_RFCOMM)` etc., gated by `net/Makefile`
`obj-$(CONFIG_BT) += bluetooth/`.

**Step 5.2: TRACE CALLERS**
Record: RFCOMM: DUN/OBEX/serial. BNEP: PAN. HIDP: Bluetooth HID.
6LoWPAN: BLE IPv6. Reachable whenever those Kconfig options are enabled.

**Step 5.3: TRACE CALLEES**
Record: N/A (Kconfig only).

**Step 5.4: FOLLOW THE CALL CHAIN**
Record: Yes, userspace-visible: missing
`rfcomm`/`bnep`/`hidp`/`bluetooth_6lowpan` when the bad combo is set.
`s5pv210_defconfig` is a concrete in-tree trigger.

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**
Record: `BT_CMTP` in this tree still `depends on BT_BREDR` only
(deprecated). Out of this patch’s scope.

---

## PHASE 6: CROSS-REFERENCING AGAINST THE LOCAL TREE

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?**
Record: **Yes.**
- `net/bluetooth/rfcomm/Kconfig:4` `depends on BT_BREDR`
- `net/bluetooth/bnep/Kconfig:4` `depends on BT_BREDR`
- `net/bluetooth/hidp/Kconfig:4` `depends on BT_BREDR && INPUT &&
  HID_SUPPORT`
- `net/bluetooth/Kconfig:86` `depends on BT_LE && 6LOWPAN`
Introduced 2014 (65efd2bf48853); still here. Fix 646d8e385271 is **not**
in HEAD.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**
Record: **Minor conflict on HIDP only** (this tree still has
INPUT/HID_SUPPORT + `select HID`). Other three hunks apply cleanly.
Expected backport: add `BT &&` on the local HIDP depends line.

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**
Record: No equivalent `depends on BT &&` on these four symbols.
6cc90ccd4f6cf only added HID_SUPPORT.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

**Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY**
Record: `net/bluetooth` Kconfig. **IMPORTANT** — Bluetooth stack, not
core mm/VFS, but RFCOMM/HIDP/BNEP are widely used.

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**
Record: Active (many Luiz fixes on this branch). The bug itself is old
(2014), not churn from a new subsystem.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

**Step 8.1: DETERMINE WHO IS AFFECTED**
Record: Config-specific: `CONFIG_BT=m` and a protocol `=y`. Hits custom
configs, oldconfig `BT=y`→`m` transitions, and **s5pv210_defconfig** in
this tree. Distros that set all of them to `=m` are unaffected.

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**
Record: At **build** time, not a runtime race. Unprivileged users cannot
trigger it; builders/defconfigs can. Likelihood: uncommon but **real**
(in-tree defconfig).

**Step 8.3: DETERMINE THE FAILURE MODE SEVERITY**
Record: Protocols silently omitted — no RFCOMM TTY/DUN, no PAN, no
Bluetooth HID, no BT 6LoWPAN. Not a panic. **MEDIUM–HIGH** functional
breakage; matches stable’s “build error” / “oh, that’s not good”.

**Step 8.4: CALCULATE RISK-BENEFIT RATIO**
Record:
- **Benefit:** High for affected configs — modules actually get built
  (s5pv210 RFCOMM/BNEP included).
- **Risk:** Very low — 4 Kconfig depends lines; only invalid configs
  change, and they change toward working.
- **Ratio:** Favor backport.

---

## PHASE 9: FINAL SYNTHESIS

**Step 9.1: COMPILE THE EVIDENCE**

**FOR:**
- Real Kconfig/build bug: `BT=m` + proto `=y` drops
  rfcomm/bnep/hidp/6lowpan (verified in `scripts/Makefile.lib` via
  `need-builtin`).
- In-tree `s5pv210_defconfig` has that combo.
- Bug exists in 6.12 since 65efd2bf48853 (2014).
- Four one-line depends fixes; no new API.
- Maintainer-requested v2, applied by Luiz, CI build PASS.
- Matches stable “build fix” exception.

**AGAINST:**
- Not a crash/UAF/security bug.
- No Cc: stable (must not count as a negative here).
- Lived a long time; many distros use all-`=m`.
- HIDP hunk needs a one-line context adjust.
- CMTP in 6.12 has the same pattern and is not fixed (deprecated).

**UNRESOLVED:** Exact mainline commit that switched HIDP from `INPUT &&
HID_SUPPORT` + `select HID` to `depends on HID` (post-6.12); does not
change the `depends on BT` fix.

**Step 9.2: APPLY THE STABLE RULES CHECKLIST**
1. Obviously correct and tested? **PASS** — standard depends; Luiz
   applied; build CI passed.
2. Fixes a real bug that affects users? **PASS** — silent missing
   Bluetooth protocols; s5pv210_defconfig.
3. Important issue? **PASS** — build/config omission of
   RFCOMM/BNEP/HIDP/6LoWPAN (severity MEDIUM–HIGH, not panic).
4. Small and contained? **PASS** — 4 lines, Kconfig only.
5. No new features or APIs? **PASS**
6. Can apply to the local tree? **PASS** — 3/4 clean; HIDP needs
   `depends on BT && BT_BREDR && INPUT && HID_SUPPORT`.

**Step 9.3: CHECK FOR EXCEPTION CATEGORIES**
Record: **Build fix** (Kconfig dependency). Qualifies.

**Step 9.4: DECISION**
Backport. The bug is in this 6.12 tree, the fix is surgical and correct,
and it restores Bluetooth protocol modules that kbuild currently throws
away.

---

### What the commit solves for this tree

With `CONFIG_BT=m`, kbuild visits `net/bluetooth/` without `need-
builtin`. Protocol dirs listed as `obj-y` are filtered out, so
RFCOMM/BNEP/HIDP/6LoWPAN never compile. Adding `depends on BT` forces
those symbols to `=m` when BT is a module, which is the working
configuration. That includes `arch/arm/configs/s5pv210_defconfig` in
this checkout.

### Stable rules / risk vs benefit

Meets the rules: obviously correct, real user-visible build bug, small,
no new API. Benefit is restoring missing Bluetooth profiles; risk is a
Kconfig depends tweak on configs that already did not build those
objects.

### Concerns

HIDP must be backported as `depends on BT && BT_BREDR && INPUT &&
HID_SUPPORT` (this tree does not yet use `depends on HID`). CMTP is left
as-is (deprecated, not in the upstream patch).

---

Verification:
- [Phase 1] Tags: author SOB Iva Kasprzaková; maintainer SOB Luiz; no
  Fixes/Reported-by/Cc: stable
- [Phase 2] Diff: four `depends on BT &&` additions in Kconfig only
- [Phase 2] Kbuild: `scripts/Makefile.lib` drops `obj-y` directories
  when `need-builtin` is unset; `net/Makefile` uses `obj-$(CONFIG_BT) +=
  bluetooth/`
- [Phase 3] blame: 65efd2bf48853 (2014) introduced `depends on
  BT_BREDR`/`BT_LE`; ancestor of HEAD
- [Phase 3] `git merge-base --is-ancestor 646d8e385271 HEAD` failed —
  fix not in this tree
- [Phase 3] HIDP in this tree is 6cc90ccd4f6cf (`INPUT && HID_SUPPORT`),
  not upstream `depends on HID`
- [Phase 4] b4 dig: v1 20260720150919.9602-1-iva@yenya.net, v2
  20260722130849.7813-1-iva@yenya.net
- [Phase 4] Luiz asked for BT_6LOWPAN on v1; v2 applied to bluetooth-
  next 646d8e385271
- [Phase 4] Recipients: Holtmann, Luiz, linux-bluetooth; no stable
  nomination
- [Phase 4] stable lore search: no discussion of this patch
- [Phase 6] `git describe HEAD`: p-6.12-3-g710455e2077bb; `make
  kernelversion`: 6.12.111
- [Phase 6] Local files still have the old depends lines
- [Phase 8] `arch/arm/configs/s5pv210_defconfig`: CONFIG_BT=m +
  CONFIG_BT_RFCOMM=y + CONFIG_BT_BNEP=y
- [Phase 8] Failure mode: protocols silently not built; severity
  MEDIUM–HIGH
- UNVERIFIED: exact later commit that rewrote HIDP to `depends on HID`
  (not required for the 6.12 backport)

**YES**

 net/bluetooth/Kconfig        | 2 +-
 net/bluetooth/bnep/Kconfig   | 2 +-
 net/bluetooth/hidp/Kconfig   | 2 +-
 net/bluetooth/rfcomm/Kconfig | 2 +-
 4 files changed, 4 insertions(+), 4 deletions(-)

diff --git a/net/bluetooth/Kconfig b/net/bluetooth/Kconfig
index 6b2b65a667008..86618afb855d3 100644
--- a/net/bluetooth/Kconfig
+++ b/net/bluetooth/Kconfig
@@ -83,7 +83,7 @@ config BT_LE_L2CAP_ECRED
 
 config BT_6LOWPAN
 	tristate "Bluetooth 6LoWPAN support"
-	depends on BT_LE && 6LOWPAN
+	depends on BT && BT_LE && 6LOWPAN
 	help
 	  IPv6 compression over Bluetooth Low Energy.
 
diff --git a/net/bluetooth/bnep/Kconfig b/net/bluetooth/bnep/Kconfig
index aac02b5b0d170..f8087e2d2c00e 100644
--- a/net/bluetooth/bnep/Kconfig
+++ b/net/bluetooth/bnep/Kconfig
@@ -1,7 +1,7 @@
 # SPDX-License-Identifier: GPL-2.0-only
 config BT_BNEP
 	tristate "BNEP protocol support"
-	depends on BT_BREDR
+	depends on BT && BT_BREDR
 	select CRC32
 	help
 	  BNEP (Bluetooth Network Encapsulation Protocol) is Ethernet
diff --git a/net/bluetooth/hidp/Kconfig b/net/bluetooth/hidp/Kconfig
index e08aae35351a7..ba52c7296f18f 100644
--- a/net/bluetooth/hidp/Kconfig
+++ b/net/bluetooth/hidp/Kconfig
@@ -1,7 +1,7 @@
 # SPDX-License-Identifier: GPL-2.0-only
 config BT_HIDP
 	tristate "HIDP protocol support"
-	depends on BT_BREDR && HID
+	depends on BT && BT_BREDR && HID
 	help
 	  HIDP (Human Interface Device Protocol) is a transport layer
 	  for HID reports.  HIDP is required for the Bluetooth Human
diff --git a/net/bluetooth/rfcomm/Kconfig b/net/bluetooth/rfcomm/Kconfig
index 9b9953ebf4c02..e7af2d565cea8 100644
--- a/net/bluetooth/rfcomm/Kconfig
+++ b/net/bluetooth/rfcomm/Kconfig
@@ -1,7 +1,7 @@
 # SPDX-License-Identifier: GPL-2.0-only
 config BT_RFCOMM
 	tristate "RFCOMM protocol support"
-	depends on BT_BREDR
+	depends on BT && BT_BREDR
 	help
 	  RFCOMM provides connection oriented stream transport.  RFCOMM
 	  support is required for Dialup Networking, OBEX and other Bluetooth
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 10+ messages in thread

end of thread, other threads:[~2026-10-19 14:05 UTC | newest]

Thread overview: 10+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
     [not found] <20261019135441.1420968-1-sashal@kernel.org>
2026-10-19 13:45 ` [PATCH AUTOSEL 6.18-6.1] Bluetooth: hci_event: fix out-of-bounds read in LE PA report reassembly Sasha Levin
2026-10-19 13:45 ` [PATCH AUTOSEL 6.18-5.10] Bluetooth: btrsi: Move set_bt_context after successful HCI registration Sasha Levin
2026-10-19 13:47 ` [PATCH AUTOSEL 6.18] Bluetooth: bfusb: validate received block boundaries Sasha Levin
2026-10-19 13:48 ` [PATCH AUTOSEL 6.18-5.15] Bluetooth: btusb: Add support for 1357:c123 Realtek 8852BE device Sasha Levin
2026-10-19 13:48 ` [PATCH AUTOSEL 6.18-5.10] Bluetooth: hci_bcsp: validate received packet lengths Sasha Levin
2026-10-19 13:48 ` [PATCH AUTOSEL 6.18-5.10] Bluetooth: hci_nokia: validate firmware packet bounds Sasha Levin
2026-10-19 13:50 ` [PATCH AUTOSEL 6.18] Bluetooth: btusb: Add USB ID 13d3:3625 for MediaTek MT7922 Sasha Levin
2026-10-19 13:50 ` [PATCH AUTOSEL 6.18-6.1] Bluetooth: hci_sync: Disable legacy instance's ext adv before setup snapshot Sasha Levin
2026-10-19 13:51 ` [PATCH AUTOSEL 6.18] Bluetooth: btnxpuart: Fix use-after-free in probe error path Sasha Levin
2026-10-19 13:52 ` [PATCH AUTOSEL 6.18] Bluetooth: fix BT dependency for submodules Sasha Levin

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox