Skip to contentSkip to conversation

net: dsa: mt7530: check CORE_PLL_GROUP4 access in mt7531_setup()

PATCH New Sasha Levin 9 participants 624 messages Oct 19 – Oct 28 Page 2 of 15

Subsystems (71)
lore
Share & tools
lore
author maintainer
#46 lore raw

PATCH 1/1 selftests/ftrace: Force C locale in ftracetest

In reply to Sasha Levin

From: Rui Qi <[email protected]>

[ Upstream commit c13fcd3951dcc19524ce0b3e852844b16cd32b22 ]

Some ftracetest test cases parse command output by matching English field names. Tools such as readelf may localize their output via gettext, while ftracetest currently inherits the user locale from the environment.

If a translated field name is printed, parsing can fail even though the tested kernel behavior is unchanged. For example, add_remove_uprobe can fail to find the ELF entry point and then write a uprobe event with a missing offset.

Export LC_ALL=C in the top-level ftracetest runner so every test case gets stable command output by default.

---

LLM Generated explanations, may be completely bogus:

I have enough to decide: this is a three-line selftest locale fix, the companion uprobe offset patch is already in this 6.18 tree, and the runner still inherits the user locale.

## Phase 1: Commit message forensics

**Step 1.1: Subject line**
- Record: [selftests/ftrace] [Force] Force C locale in ftracetest so test parsing is locale-stable

**Step 1.2: Tags**
- Record:
- `Link: https://lore.kernel.org/all/20260807081512.2974757-2-

    [email protected]/`

- Signed-off-by: Rui Qi <[email protected]> (author)
- Signed-off-by: Masami Hiramatsu (Google) <[email protected]> (ftrace/probes maintainer)
- No Fixes:, Reported-by:, Tested-by:, Reviewed-by:, Acked- by:, or Cc: stable (absence is expected for this review)
- Upstream SHA: c13fcd3951dcc19524ce0b3e852844b16cd32b22

**Step 1.3: Body**
- Record: [Bug] ftracetest inherits the user locale; tools such as readelf can print translated field names. Tests that grep English strings then fail even though kernel behavior is unchanged. [Symptom] add_remove_uprobe fails to parse the ELF entry point and writes a uprobe event with a missing offset. [Versions] none stated. [Root cause] command-output parsing depends on English gettext strings while LC_ALL is not forced.

**Step 1.4: Hidden bug fix?**
- Record: [Not disguised.] This is an explicit robustness fix for locale-dependent test parsing, not a style cleanup.

## Phase 2: Diff analysis

**Step 2.1: Inventory**
- Record: [Files] tools/testing/selftests/ftrace/ftracetest +3 / -0 [Functions] none; top-level shell runner [Scope] single-file, surgical]

**Step 2.2: Code flow**
- Record: [Before] ftracetest and every sourced .tc inherit LANG/LC_* from the environment. [After] export LC_ALL=C at runner start, inherited by all test cases including readelf in add_remove_uprobe. [Path] initialization of the test harness, not kernel runtime.

**Step 2.3: Bug mechanism**
- Record: [Category] logic/correctness in the test harness (locale- dependent parsing). [Mechanism] add_remove_uprobe.tc does grep "Entry point" and grep LOAD on readelf output. If those strings are translated, ENTRY is empty, OFFSET is empty, and the script writes p:myevent ${REALBIN}: with no offset.

**Step 2.4: Fix quality**
- Record: [Quality] obviously correct; LC_ALL=C is the standard way to freeze tool output. Three comment+export lines, no API change. [Regression risk] very low. C locale can change collation/number formatting, but ftrace tests parse English tracefs and ELF field names. Maintainer asked for runner-wide export rather than per-readelf wrappers.

## Phase 3: Git history

**Step 3.1: Blame**
- Record: [Introduced] ftracetest header is from 6e68e6c5e4b67 (2014). The locale-sensitive parsing was added by dc4b165855f23 ("Use readelf to find entry point in uprobe test", 2025-02-26) and tightened by bd4e5a97edf8c (already in this tree), which greps "Entry point" with no LC_ALL=C. [Age] parsing bug present since v6.15-era code; still present here.

**Step 3.2: Fixes: tag**
- Record: [N/A] no Fixes: tag. Companion series patch 2/2 (bd4e5a97edf8c / upstream 24aa630f6259) fixes dc4b165855f23 and is already an ancestor of HEAD.

**Step 3.3: File history**
- Record: [Related] bd4e5a97edf8c already backported here with Cc:
stable. That is v2 2/2 of the same series. In v2, per-command LC_ALL=C was removed from the uprobe test because patch 1/2 was supposed to set it in the runner. This tree has 2/2 without 1/2. [Standalone?] yes as a diff; semantically it completes that series.

**Step 3.4: Author**
- Record: [Author] Rui Qi (ByteDance); not the subsystem maintainer. Only other ftrace selftest commit in this tree is the companion offset conversion. Maintainer Masami Hiramatsu applied both.

**Step 3.5: Prerequisites**
- Record: [Dependencies] none for apply. Insertion is after the copyright block, which matches this tree. Local ftracetest lacks mainline --rv; that is later context only and is not required. [Standalone apply] yes.

## Phase 4: Mailing list

**Step 4.1: Original discussion**
- Record: `[Lore] https://patch.msgid.link/20260807081512.2974757-2-
[email protected] (WebFetch on lore.kernel.org returned 403; thread recovered via b4 dig -m).
- [Revisions] v1 (2026-08-06): LC_ALL=C only on one readelf in add_remove_uprobe. v2 (2026-08-07): moved to top-level ftracetest per Masami. Applied version is v2, latest.
- [Feedback] Masami on v1: force C locale in the top-level runner, not per test. Author agreed and sent v2. Masami applied v2 2/2 with "Good catch! OK, let me take it." No NAKs. No reviewer Cc: stable on this patch (2/2 had Fixes: and later got Cc: stable in the backport).

**Step 4.2: Recipients**
- Record: [To/Cc] Steven Rostedt, Masami Hiramatsu, Mathieu Desnoyers, Shuah Khan, Heiko Carstens, linux-trace-kernel, linux-kselftest, linux-kernel.

**Step 4.3: Bug report**
- Record: [No syzbot/bugzilla.] Cover letter: series fixes two ways add_remove_uprobe can build an invalid uprobe offset. v1 body: if readelf is translated, ENTRYPOINT is empty and the uprobe_events write is rejected because the offset after PATH: is missing. Author is a real user of a non-C locale (ByteDance).

**Step 4.4: Series**
- Record: [v2 0/2] "Fix add_remove_uprobe robustness". Patch 1 = this commit. Patch 2 = ELF VA→file offset (bd4e5a97edf8c), already in this tree. v2 2/2 dropped inline LC_ALL=C and relies on the runner.

**Step 4.5: Stable list**
- Record: [No stable-list discussion found] for this subject. Companion 2/2 was taken into this tree with Cc: [email protected].

## Phase 5: Code semantics

**Step 5.1: Functions**
- Record: [No C functions.] Change is export LC_ALL=C in ftracetest. Affected consumer: add_remove_uprobe.tc` readelf parsing.`

**Step 5.2: Callers**
- Record: [ftracetest-ktap] runs ./ftracetest -K -v. kselftest Makefile lists ftracetest / ftracetest-ktap. __run_test sources each .tc in a subshell, so LC_ALL=C is inherited. Reachable whenever someone runs ftrace selftests.

**Step 5.3: Callees**
- Record: [readelf -hW / -lW, grep, awk, writes to uprobe_events.] Kernel ABI involved is uprobe_events, already exercised by the test.

**Step 5.4: Call chain**
- Record: `[kselftest runner → ftracetest-ktap → ftracetest → add_remove_uprobe.tc → readelf → uprobe_events.] Userspace-only. Not a syscall bug; it does cause a false test failure and a malformed probe write.`

**Step 5.5: Similar patterns**
- Record: [Only this ftrace test greps readelf "Entry point".] Other selftests (e.g. mptcp) already pin LC_ALL=C on individual commands. No export LC_ALL=C in this tree's ftrace runner yet.

## Phase 6: This tree (pending-6.18 / 6.18.53)

**Step 6.1: Buggy code present?**
- Record: [Yes.] tools/testing/selftests/ftrace/ftracetest has no LC_ALL=C. add_remove_uprobe.tc lines 17 and 37 grep English readelf strings. git describe HEAD = p-6.18-1-g03b85e06ca9bf; make kernelversion = 6.18.53. Introduced by dc4b165855f23 (ancestor of HEAD).

**Step 6.2: Backport difficulty**
- Record: [Clean apply.] Copyright-block context matches. --rv in the candidate hunk is later mainline noise, not needed here.

**Step 6.3: Related fixes already here?**
- Record: [Partial.] Offset conversion bd4e5a97edf8c is here; locale export is not. No earlier equivalent LC_ALL=C in this file.

## Phase 7: Subsystem context

**Step 7.1**
- Record: [Subsystem] tools/testing/selftests/ftrace [Criticality] PERIPHERAL for production kernel runtime; IMPORTANT for anyone running ftrace kselftests on this stable tree (distro CI, KernelCI, vendor QA).

**Step 7.2**
- Record: [Activity] active; recent ftrace selftest fixes already landed in this 6.18.y tree, including the companion uprobe test fix.

## Phase 8: Impact and risk

**Step 8.1: Who is affected**
- Record: [config/test-specific] users/CI running ftracetest with a non-C locale (zh_CN, de_DE, ja_JP, etc.). No effect on kernel boot or production tracing if tests are not run.

**Step 8.2: Trigger**
- Record: `[Trigger] run ftracetest (or kselftest ftrace) with translated binutils/gettext. Common on non-English developer and QA machines. Unprivileged users can run the tests if they have tracefs access; this is not a privilege-escalation bug.`

**Step 8.3: Failure mode**
- Record: [Failure] false-negative kselftest; possible write of p:myevent <path>: with empty offset, which the kernel rejects. Not a panic, UAF, or data corruption. [Severity] MEDIUM for QA/CI correctness; LOW for production kernel runtime.

**Step 8.4: Risk-benefit**
- Record: [Benefit] medium for this tree: completes a 2-patch series whose second half is already here, so add_remove_uprobe stays locale- broken without it. [Risk] very low (3 lines, userspace test runner only). [Ratio] favorable.

## Phase 9: Synthesis

**Step 9.1: Evidence**

For:
- Real, reproducible test failure when readelf is localized.
- Companion v2 2/2 is already in this 6.18 tree and depends on runner LC_ALL=C (inline LC_ALL=C was removed in v2).
- Tiny, obviously correct, maintainer-directed.
- Applies cleanly; no kernel ABI/feature change.
- kselftest false failures on stable are used by distros and CI.

Against:
- Not a kernel crash, security hole, deadlock, or data corruption.
- Only hits people who run ftrace selftests under a non-C locale.
- This patch itself was not Cc: stable (not used as a NO vote per the review rules).

Unresolved:
- Could not fetch lore.kernel.org over HTTP (403); discussion was recovered from b4 dig mbox. No stable-list thread found.

**Step 9.2: Stable rules**
1. Obviously correct and tested? **PASS** — 3-line export; maintainer requested and applied; author ran checkpatch and sh -n.
2. Real bug affecting users? **PASS** — false ftracetest failure and malformed uprobe write on localized systems.
3. Important issue? **PASS** — not a kernel oops, but it is a real kselftest break, and this tree already took the paired functional fix. Leaving this out keeps that test locale-fragile.
4. Small and contained? **PASS** — +3 lines, one file.
5. No new features/APIs? **PASS**.
6. Can apply to this tree? **PASS**.

**Step 9.3: Exception category**
- Record: [Not a device-ID/quirk/DT/build/docs exception.] Closest analogue is a kselftest robustness/false-failure fix, which stable trees routinely take when the test exists in-tree.

**Step 9.4: Decision**
This should be backported to **this** 6.18.y tree. The bug exists here, the patch is surgical, and it finishes a series that is already half- applied.

### What the commit solves for stable users
On a non-C locale, readelf can translate "Entry point", so add_remove_uprobe computes an empty offset and fails even though uprobes work. Distros and CI that run ftrace kselftests against 6.18.y get a false failure. The offset-conversion fix already in this tree still greps English readelf text and assumed this runner change.

### Risk vs benefit
Benefit is restoring a test that this tree already ships. Risk is
negligible: LC_ALL=C only affects the ftracetest process tree.

### Concerns
None material. --rv in the original hunk context is not in this tree and is not required. No further commits are needed for the export to work.

## Verification
- [Phase 1] Parsed tags: Link to lore msgid 20260807081512.2974757-2; SOBs Rui Qi and Masami Hiramatsu; no Fixes/Reported-by/Cc: stable.
- [Phase 2] Diff: +3 lines in ftracetest (export LC_ALL=C); confirmed local file lacks it.
- [Phase 3] git describe HEAD → p-6.18-1-g03b85e06ca9bf; make kernelversion → 6.18.53.
- [Phase 3] git merge-base --is-ancestor c13fcd3951dcc1 HEAD → not an ancestor (fix not in tree).
- [Phase 3] git merge-base --is-ancestor bd4e5a97edf8c HEAD → yes (companion 2/2 is in tree).
- [Phase 3] git merge-base --is-ancestor dc4b165855f23 HEAD → yes (readelf parsing introduced here).
- [Phase 3] git blame on ftracetest header: 6e68e6c5e4b67 (2014); no LC_ALL.
- [Phase 3] Read add_remove_uprobe.tc: greps "Entry point" and LOAD with no LC_ALL.
- [Phase 4] b4 dig -c c13fcd3951dcc1 → v2 1/2 msgid link above.
- [Phase 4] b4 dig -a → v1 per-readelf LC_ALL, v2 runner-wide (applied).
- [Phase 4] b4 dig -w → Rostedt, Masami, Desnoyers, Shuah, kselftest and trace lists.
- [Phase 4] mbox: Masami asked to set LC_ALL in the runner; no NAKs; cover letter describes two invalid-offset paths.
- [Phase 4] lore WebFetch 403; stable-list search found no discussion of this subject.
- [Phase 5] ftracetest-ktap invokes ./ftracetest -K -v; __run_test sources .tc files so export is inherited.
- [Phase 6] Insertion context after copyright block is present; export LC_ALL=C is not.
- [Phase 8] Failure mode verified from v1 message and current test
script: empty ENTRY → p:myevent path: write → test fail, not kernel oops.
- UNVERIFIED: live readelf translation under a specific locale was not executed on this machine; the gettext localization claim is from the author and is consistent with binutils behavior, but was not reproduced here.

**YES**

 tools/testing/selftests/ftrace/ftracetest | 3 +++
 1 file changed, 3 insertions(+)
tools/testing/selftests/ftrace/ftracetest +3 -0
index cce72f8b03dce..ee3b950e872f6 100755
@@ -7,6 +7,9 @@
 #  Written by Masami Hiramatsu <[email protected]>
 #
 
+# Keep command output parsing stable regardless of the user's locale.
+export LC_ALL=C
+
 usage() { # errno [message]
 [ ! -z "$2" ] && echo $2
 echo "Usage: ftracetest [options] [testcase(s)] [testcase-directory(s)]"
Signature · 1 line
2.53.0
author maintainer
#47 lore raw

PATCH 1/1 nvme: clamp FDP nruhsd to allocated RUH status descriptor count

In reply to Sasha Levin

From: Hari Mishal <[email protected]>

[ Upstream commit 29261f8bb41662f2a660c479e5cf592942b53f78 ]

nvme_query_fdp_info() allocates the RUH status buffer for at most S8_MAX
- 1 descriptors, and then copies ruhs->ruhsd[] into head->plids[] using the controller reported ruhs->nruhsd directly as the loop bound. However, that count wasn't taken into account for the actual buffer's size, so there was a chance for a controller reporting a larger nruhsd to cause the copy to overflow the buffer. Clamp nr_plids to the same bound used for the allocation.

---

LLM Generated explanations, may be completely bogus:

This is a one-line out-of-bounds-read clamp in NVMe FDP setup. The local tree is **v7.3-rc4** (7.3.0-rc4, HEAD f0100363d8c37). nvme_query_fdp_info() exists here; the overflow is real; the change is surgical.

## PHASE 1: COMMIT MESSAGE FORENSICS

**Step 1.1: PARSE THE SUBJECT LINE**
Record: **[nvme]** **[clamp]** clamp FDP nruhsd to the allocated RUH status descriptor count. “Clamp” is a bounds-fix verb.

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**
Record:
- **Reviewed-by:** Christoph Hellwig <[email protected]>
- **Assisted-by:** gkh_clanker_t1000
- **Signed-off-by:** Hari Mishal (author), Greg Kroah-Hartman (submitter), Keith Busch (NVMe maintainer)
- **No Fixes:** tag (expected)
- **No Reported-by / Tested-by / Link / Cc: stable**
- Ignore pipeline SOBs; Greg’s SOB is from the actual submission, not a stable-prep marker

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**
Record:
- **Bug:** nvme_query_fdp_info() allocates a RUH-status buffer for at most S8_MAX - 1 descriptors, then copies ruhs->ruhsd[] using controller-reported ruhs->nruhsd as the loop bound.
- **Symptom:** a controller that reports nruhsd larger than the allocated descriptor count overflows that buffer on the copy into head->plids[].
- **Root cause:** allocation size and copy bound were not the same.
- **Fix:** clamp nr_plids to the same bound used for allocation.
- **Version info in message:** none.

**Step 1.4: DETECT HIDDEN BUG FIXES**
Record: Not hidden. This is an explicit buffer-overflow / OOB-read fix.

## PHASE 2: DIFF ANALYSIS

**Step 2.1: INVENTORY THE CHANGES**
Record:
- **File:** drivers/nvme/host/core.c — 1 insertion, 1 deletion
- **Function:** nvme_query_fdp_info()
- **Scope:** single-file, one-line surgical fix

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**
Record: Before: head->nr_plids = le16_to_cpu(ruhs->nruhsd); then kcalloc(head->nr_plids, …) and for (i = 0; i < head->nr_plids; i++) head->plids[i] = le16_to_cpu(ruhs->ruhsd[i].pid);. After: nr_plids is min(reported, S8_MAX - 1), so the copy cannot walk past the allocated ruhs buffer. Path is namespace-head init when the controller advertises FDP.

**Step 2.3: IDENTIFY THE BUG MECHANISM**
Record: **(g) logic/correctness + (d) memory safety — out-of-bounds read.** nruhsd is a __le16 from the device (0..65535). Allocation used struct_size(ruhs, ruhsd, S8_MAX - 1) (126 descriptors, 4048 bytes). Verified layout in include/linux/nvme.h: 16-byte header + 32-byte nvme_fdp_ruh_status_desc. If nruhsd == 65535, the loop reads ~2MB past the buffer. plids is sized from nr_plids, so the overflow is an OOB **read** of ruhs, not a write into plids.

**Step 2.4: ASSESS THE FIX QUALITY**
Record: Obviously correct: clamp matches the allocation bound. Minimal. Regression risk is low: extra reported placement IDs are dropped instead of overflowing. Later mainline commit 53cdaeab2e30e raised that cap to U8_MAX / NVME_MAX_PLIDS; that is a follow-up improvement, not a sign this clamp is wrong.

## PHASE 3: GIT HISTORY INVESTIGATION

**Step 3.1: BLAME THE CHANGED LINES**
Record:
- Allocation struct_size(..., S8_MAX - 1) introduced in 30b5f20bb2dda (“nvme: register fdp parameters with the block layer”, Keith Busch, 2025-05-06).
- Unclamped nr_plids assignment plus the ruhsd[] copy loop:
38e8397dde633 (“nvme: use fdp streams if write stream is provided”).
- Both first appear in **v6.16-rc1** (git describe --contains --match 'v*').

**Step 3.2: FOLLOW THE FIXES: TAG**
Record: No Fixes: tag. Introducing commits identified by blame, not by tag.

**Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES**
Record:
- 29261f8bb4166 — this clamp (candidate)
- 53cdaeab2e30e — raise cap to U8_MAX and introduce NVME_MAX_PLIDS (depends on the clamp being present)
- 56e1c6bbe4bb0 — race on the plids array (independent locking fix)
- Series partner 3c568b35a0d30 — NS descriptor bounds (different function, not a prerequisite)

Standalone. Labeled [PATCH 2/2] but 1/2 is an independent bounds check in nvme_identify_ns_descs().

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**
Record: Hari Mishal also authored sibling overflow fixes (nvme: bound ns descriptor header…, nvmet: passthru: fix OOB reads…). Submitted via Greg; merged by NVMe maintainer Keith Busch. Christoph Hellwig reviewed.

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS**
Record: None for the clamp itself. It only needs nvme_query_fdp_info() with S8_MAX - 1 allocation and the copy loop — present since v6.16. No new helpers or APIs.

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**
Record:
- b4 dig -c 29261f8bb4166 → https://patch.msgid.link/2026070932-fried-
frying-9c36@gregkh
- **v1 only** (b4 dig -a): [PATCH 1/2] nvme: bound ns descriptor… + [PATCH 2/2] this clamp
- Full thread saved via b4 dig -m; lore HTTP fetch returned 403, so discussion is from the mbox, not lore HTML
- Christoph: “Looks good: Reviewed-by: Christoph Hellwig”
- Keith Busch: “Thanks, series applied to nvme-7.3.”
- No NAK, no stable discussion in-thread, no reviewer risk flags

**Step 4.2: CHECK WHO REVIEWED THE PATCH**
Record (b4 dig -w): linux-nvme, linux-kernel, Keith Busch, Jens Axboe, Christoph Hellwig, Sagi Grimberg. Appropriate maintainers were on Cc. Christoph reviewed; Keith applied.

**Step 4.3: SEARCH FOR THE BUG REPORT**
Record: No syzbot/bugzilla/Reported-by. Bug is from code review / static analysis (Greg/clanker-assisted). Still a concrete OOB from device-provided nruhsd.

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**
Record: 2/2 is independent of 1/2. Follow-up 53cdaeab2e30e changes the numeric cap but does not replace the need to clamp. Race fix 56e1c6bbe4bb0 is separate.

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**
Record: lore.kernel.org/stable search returned 403. **UNVERIFIED** whether stable@ already discussed this. No evidence in the nvme thread of a stable NAK.

## PHASE 5: CODE SEMANTIC ANALYSIS

**Step 5.1: IDENTIFY KEY FUNCTIONS**
Record: nvme_query_fdp_info() only.

**Step 5.2: TRACE CALLERS**
Record: Only caller is nvme_alloc_ns_head() in
drivers/nvme/host/core.c:

```4043:4047:drivers/nvme/host/core.c
        if (ctrl->ctratt & NVME_CTRL_ATTR_FDPS) {
                ret = nvme_query_fdp_info(ns, info);
                if (ret < 0)
                        goto out_cleanup_srcu;
        }
```

Triggered during namespace-head creation when Identify Controller ctratt has NVME_CTRL_ATTR_FDPS. That is probe/scan, not a hot I/O path, but it runs for every FDP-capable namespace.

**Step 5.3: TRACE CALLEES**
Record: nvme_get_features(), nvme_query_fdp_granularity(), kzalloc/kcalloc, nvme_submit_sync_cmd() (device fills ruhs), then the copy loop.

**Step 5.4: FOLLOW THE CALL CHAIN**
Record: Device probe / namespace scan → nvme_init_ns_head → nvme_alloc_ns_head → nvme_query_fdp_info. Reachable from attaching an NVMe device, including NVMe over Fabrics. A malicious or buggy target can set FDPS and return a huge nruhsd. Not a direct unprivileged syscall, but device/Fabrics-controlled and kernel-reachable.

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**
Record: Same author series also bounded NS identify descriptors. Follow- up kept the clamp and only raised the cap. No second unclamped nruhsd copy found.

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

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?**
Record: **Yes, in this lineage.** This checkout is **v7.3-rc4** (make kernelversion → 7.3.0-rc4). FDP query exists. Bug introduced **v6.16-rc1**, before 7.3. Candidate 29261f8bb4166 is already an ancestor of HEAD (git merge-base --is-ancestor succeeded; first contained in **v7.3-rc1**). Current HEAD already clamps:

```2371:2371:drivers/nvme/host/core.c
        head->nr_plids = min(le16_to_cpu(ruhs->nruhsd), NVME_MAX_PLIDS);
```

That is this fix plus 53cdaeab2e30e (NVME_MAX_PLIDS = U8_MAX). The unclamped assignment is gone at HEAD because the fix landed in 7.3-rc1; the overflow pattern is still the code this tree maintains.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**
Record: Against **current HEAD**, the original hunk would not apply (S8_MAX - 1 vs NVME_MAX_PLIDS). Against the pre-fix function (parent of 29261f8bb4166 in this history), it is a one-line change on head->nr_plids = le16_to_cpu(ruhs->nruhsd) with matching S8_MAX - 1 allocation. **Expected backport difficulty: clean apply** on trees that still have that allocation; this 7.3 checkout already has the later form.

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**
Record: This clamp and the NVME_MAX_PLIDS follow-up are both in HEAD. That is this tree already containing the upstream fix, not a different substitute.

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

**Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY**
Record: **NVMe host core** (drivers/nvme/host/). **IMPORTANT** — common storage stack, not staging. Overflow is in host core during namespace setup.

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**
Record: Active (recent FDP, multipath, scan, SRCU fixes). FDP streams themselves date to v6.16; this is not brand-new experimental code in 7.3.

## PHASE 8: IMPACT AND RISK ASSESSMENT

**Step 8.1: DETERMINE WHO IS AFFECTED**
Record: **Driver-specific / config-specific:** NVMe controllers with FDP (NVME_CTRL_ATTR_FDPS + FDPCFG_FDPE). Includes local NVMe and Fabrics targets that advertise FDP.

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**
Record: Namespace scan/probe on an FDP-enabled controller that returns nruhsd > allocated descriptor count. Not every boot. A buggy SSD can hit it; an untrusted NVMe/TCP target can hit it on purpose. Unprivileged local users cannot trigger it without a device.

**Step 8.3: DETERMINE THE FAILURE MODE SEVERITY**
Record: **Kernel out-of-bounds read** of ruhs->ruhsd[] → KASAN/oops or infoleak of adjacent heap. **Severity: HIGH.**

**Step 8.4: CALCULATE RISK-BENEFIT RATIO**
Record: **Benefit: high** (stops device-triggered OOB). **Risk: very low** (one min(), same bound as allocation). **Ratio: strongly favorable.**

## PHASE 9: FINAL SYNTHESIS

**Step 9.1: COMPILE THE EVIDENCE**

**FOR:**
- Real OOB read from device-controlled nruhsd vs a 126-descriptor buffer
- One-line, obviously correct clamp
- Reviewed by Christoph Hellwig; applied by Keith Busch
- No new API/feature
- Self-contained; series 1/2 is not required
- FDP path exists in this tree; bug dates to v6.16

**AGAINST:**
- No public user/syzbot report (code-analysis find)
- Only FDP-capable devices
- HEAD already has this clamp (and a later cap raise), so this exact hunk is not what HEAD’s source line looks like
- Lore stable@ search could not be fetched (403)

**UNRESOLVED:**
- Whether stable@ already queued it (lore/stable HTTP 403)
- No runtime reproducer in the message (mechanism is still verified in code)

**Step 9.2: APPLY THE STABLE RULES CHECKLIST**
1. Obviously correct and tested? **PASS** — clamp equals allocation bound; reviewed and merged to nvme-7.3
2. Fixes a real bug that affects users? **PASS** — OOB read on FDP namespace setup
3. Important issue (crash/security/corruption/deadlock)? **PASS** — HIGH, kernel OOB from device data
4. Small and contained? **PASS** — 1 line, one function
5. No new features or APIs? **PASS**
6. Can apply to the local tree? **PASS** for this codebase’s pre-fix form (S8_MAX - 1 allocation + unclamped nruhsd). HEAD already has the evolved clamp; that does not make the fix inapplicable to this lineage.

**Step 9.3: CHECK FOR EXCEPTION CATEGORIES**
Record: None (not a device-ID/quirk/DT/build/docs exception). It is a normal memory-safety fix.

**Step 9.4: MAKE YOUR DECISION**
This tree’s NVMe host core has the FDP RUH-status query, and using the controller’s nruhsd as the copy bound without capping it to the allocated descriptor count is a real overflow. The fix is the smallest correct change. This 7.3 checkout already contains that logic (then raised the cap to U8_MAX); that is the upstream landing, not a reason to treat the overflow as unworthy of stable. Benefit vs risk is strongly in favor of backporting.

### What the commit solves, and why it matters
A Flexible Data Placement controller returns how many Reclaim Unit Handle status descriptors it has (nruhsd). The driver only allocated room for 126, then indexed ruhs->ruhsd[i] up to the raw reported count. That is a kernel heap OOB read during namespace setup, including from a remote NVMe/TCP target.

### Stable rules
Small, obviously correct, no new API, real memory-safety bug.

### Risk vs benefit
One min() vs device-triggered OOB: take the fix.

### Concerns
Patch 2/2 does not need patch 1/2. Trees that already switched allocation to NVME_MAX_PLIDS should keep clamp and allocation in sync (already true here via 53cdaeab2e30e). Trees still on S8_MAX - 1 should get this commit as-is.

Verification:
- [Phase 1] Parsed tags: Reviewed-by Christoph Hellwig; SOBs Hari Mishal, Greg KH, Keith Busch; no Fixes/Reported-by/Cc stable
- [Phase 2] Diff: 1 line in nvme_query_fdp_info(); le16_to_cpu(ruhs->nruhsd) → min(..., S8_MAX - 1)
- [Phase 2] Struct sizes verified in include/linux/nvme.h: 16-byte header + 32-byte descriptors; 126 descriptors → 4048-byte buffer; nruhsd up to 65535
- [Phase 3] Blame: allocation 30b5f20bb2dda, copy loop 38e8397dde633; both git describe --contains --match 'v*' → v6.16-rc1
- [Phase 3] git merge-base --is-ancestor 29261f8bb4166 HEAD → commit is in this tree; describe --contains → v7.3-rc1
- [Phase 3] Parent of candidate still has size = struct_size(ruhs, ruhsd, S8_MAX - 1) and unclamped nr_plids
- [Phase 4] b4 dig -c → msgid 2026070932-fried-frying-9c36@gregkh; -a v1 only; -w nvme maintainers; -m full thread
- [Phase 4] mbox: Christoph R-b; Keith “applied to nvme-7.3”; no NAK
- [Phase 4] lore.kernel.org and patch.msgid.link HTTP 403; LKML mirrors agree with mbox
- [Phase 5] grep callers: only nvme_alloc_ns_head() when NVME_CTRL_ATTR_FDPS
- [Phase 6] git describe HEAD / make kernelversion: v7.3-rc4 / 7.3.0-rc4; current clamp is min(..., NVME_MAX_PLIDS) from 53cdaeab2e30e
- [Phase 8] Failure mode: OOB read of ruhs->ruhsd[], severity HIGH
- UNVERIFIED: stable@ mailing-list history (HTTP 403); no runtime reproducer in the commit message

**YES**

 drivers/nvme/host/core.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/nvme/host/core.c +1 -1
index 5ed62e070f715..ad725e346c94e 100644
@@ -2313,7 +2313,7 @@ static int nvme_query_fdp_info(struct nvme_ns *ns, struct nvme_ns_info *info)
 		goto free;
 	}
 
-	head->nr_plids = le16_to_cpu(ruhs->nruhsd);
+	head->nr_plids = min(le16_to_cpu(ruhs->nruhsd), S8_MAX - 1);
 	if (!head->nr_plids)
 		goto free;
 
Signature · 1 line
2.53.0
author maintainer
#48 lore raw

PATCH 1/1 remoteproc: qcom: Check subdev start status in rproc_stop()

In reply to Sasha Levin

From: Jingyi Wang <[email protected]>

[ Upstream commit f44ae8ce156a387b07d40e2d6a0ef979a2748aa1 ]

For rproc that doing attach, rproc_start_subdevices() is called only when attach successfully. If rproc_report_crash() is called in the attach function, rproc_boot_recovery()->rproc_stop()->rproc_stop_subdevices()-> glink_subdev_stop() could be called and cause NULL pointer dereference:

 Unable to handle kernel NULL pointer dereference at virtual address 0000000000000300
 Mem abort info:
 ...
 pc : qcom_glink_smem_unregister+0x14/0x48 [qcom_glink_smem]
 lr : glink_subdev_stop+0x1c/0x30 [qcom_common]
 ...
 Call trace:
  qcom_glink_smem_unregister+0x14/0x48 [qcom_glink_smem] (P)
  glink_subdev_stop+0x1c/0x30 [qcom_common]
  rproc_stop+0x58/0x17c
  rproc_trigger_recovery+0xb0/0x150
  rproc_crash_handler_work+0xa4/0xc4
  process_scheduled_works+0x18c/0x2d8
  worker_thread+0x144/0x280
  kthread+0x124/0x138
  ret_from_fork+0x10/0x20
 Code: a9be7bfd 910003fd a90153f3 aa0003f3 (b9430000)
 ---[ end trace 0000000000000000 ]---

Introduce "subdevs_started" flag to indicate rproc_start_subdevices() has been called successfully. Ensure subdevices are only stopped if they have been started.

---

LLM Generated explanations, may be completely bogus:

This tree is **v7.3-rc4** (7.3.0-rc4). The change is a real NULL-deref fix on the remoteproc attach/recovery path, and the triggering code is present here.

## Phase 1: Commit message forensics

**Step 1.1: Subject**
Record: [remoteproc/qcom] [Check] Check subdev start status in rproc_stop() — despite the qcom: prefix, the diff is in remoteproc core, not a Qualcomm-only file.

**Step 1.2: Tags**
Record:
- Signed-off-by: Jingyi Wang <[email protected]> (author)
- `Link: https://lore.kernel.org/r/20260623-rproc-attach-
[email protected]`
- Signed-off-by: Bjorn Andersson <[email protected]> (subsystem maintainer)
- No Fixes:, Reported-by:, Tested-by:, Reviewed-by:, `Cc:
stable` (absence is expected for this review)
- Ignore any pipeline Signed-off-by: Sasha Levin — none present on this commit

**Step 1.3: Body**
Record:
- **Bug:** On attach, rproc_start_subdevices() runs only after attach succeeds. If rproc_report_crash() fires during attach, recovery calls rproc_stop() → rproc_stop_subdevices() → glink_subdev_stop() while GLINK was never started.
- **Symptom:** kernel NULL deref / oops (qcom_glink_smem_unregister at pc offset into a NULL smem pointer). Full stack in the message.
- **Root cause:** stop is not paired with a successful start.
- **Fix:** subdevs_started flag; skip stop unless start completed.
- **Version info:** none in the message. Link id v3-2 = patch 2 of a 3-patch series.

**Step 1.4: Hidden bug fix?**
Record: Not hidden. Explicit crash + stack trace. Cover letter: “Failure in rproc_attach() path can cause issues like NULL pointer dereference when doing recovery.”

## Phase 2: Diff analysis

**Step 2.1: Inventory**
Record:
- drivers/remoteproc/remoteproc_core.c: +7 (set flag on successful start; bail/clear on stop)
- include/linux/remoteproc.h: +2 (doc + bool subdevs_started in struct rproc)
- Functions: rproc_start_subdevices(), rproc_stop_subdevices()
- Scope: single-subsystem, surgical, 9 insertions

**Step 2.2: Code flow**
Record:
- **Before:** rproc_stop_subdevices() always walked rproc->subdevs and called stop(). glink_subdev_stop() always called qcom_glink_smem_unregister(glink->edge) with edge still NULL if start never ran.
- **After:** flag set only after a full successful start loop; stop is a no-op until then; flag cleared after stop.
- Path: attach failure + crash recovery (not the normal successful boot path).

**Step 2.3: Bug mechanism**
Record: **NULL pointer dereference (memory safety).** Verified in this tree: qcom_glink_smem_unregister() does smem->glink with no NULL check. Crash VA 0x300 matches a field access through NULL. Same pattern in smd_subdev_stop() (qcom_smd_unregister_edge(smd->edge)).

**Step 2.4: Fix quality**
Record: Obviously correct. rproc_alloc() uses kzalloc, so the flag starts false. Partial start failure already unrolls via unroll_registration and does not set the flag. Start/stop run under rproc->lock (rproc_boot, rproc_trigger_recovery, __rproc_shutdown). Regression risk is low; the flag is not a new UAPI.

## Phase 3: Git history

**Step 3.1: Blame**
Record: Subdevice start/stop dates to 7bdc9650f03604 (2016, “Introduce subdevices”). The missing start-vs-stop pairing is old. This commit only adds the flag.

**Step 3.2: Fixes tag**
Record: No Fixes: tag. Concrete trigger in this tree is qcom_pas_attach() from 16472c99f4699 (“Add late attach support”, 2026-07-01), which calls rproc_report_crash() when the coprocessor already crashed. That commit is an ancestor of HEAD.

**Step 3.3: Related file history**
Record: Same series, same author:
- 026a3fada4326 — [PATCH v3 1/3] async attach via schedule_work() (immediate parent)
- f44ae8ce156a3 — this commit, 2/3
- 0ec167625b4fe — [PATCH v3 3/3] cancel crash_handler on rproc_add() error

This patch does not use attach_work; it stands alone. Patch 1 makes failed attach keep the rproc registered so recovery actually runs; patch 2 stops that recovery from oopsing.

**Step 3.4: Author**
Record: Jingyi Wang (Qualcomm). Subsystem maintainers Bjorn Andersson and Mathieu Poirier were To:’d; Bjorn applied the series.

**Step 3.5: Dependencies**
Record: No new helpers. Needs existing rproc_start_subdevices / rproc_stop_subdevices / struct rproc — all present. Can apply without patch 1. This tree already has patch 1 and late-attach, so the crash path is live here.

## Phase 4: Mailing list

**Step 4.1: Original discussion**
Record:
- b4 dig -c f44ae8ce156a3 → https://patch.msgid.link/20260623-rproc-
[email protected]
- Series: [PATCH v3 0/3] remoteproc: improve robustness for rproc_attach fail cases
- v1 used a NULL check; v2 introduced subdevs_started; v3 moved the flag into start/stop. Applied version is v3.
- No NAK in the saved thread. Bjorn: “Applied, thanks!”

**Step 4.2: Recipients**
Record: To Bjorn Andersson and Mathieu Poirier (REMOTEPROC maintainers); Cc linux-remoteproc. Right people.

**Step 4.3: Bug report**
Record: No syzbot/bugzilla. Evidence is the oops in the commit (Qualcomm attach/crash). Trigger is also in-tree: qcom_pas_attach() reports crash if fatal IRQ is already high.

**Step 4.4: Series**
Record: 2/3. 1/3 is robustness (async attach). 3/3 is a UAF-style cancel of crash work on rproc_add() failure. This patch is self-contained.

**Step 4.5: Stable list**
Record: lore.kernel.org/stable was blocked (Anubis). UNVERIFIED whether anyone nominated this on stable@. No Cc: stable on the patch itself.

## Phase 5: Semantic / call graph

**Step 5.1: Functions**
Record: rproc_start_subdevices, rproc_stop_subdevices.

**Step 5.2: Callers**
Record:
- rproc_start_subdevices: rproc_start() (firmware boot), __rproc_attach() (attach)
- rproc_stop_subdevices: rproc_stop() (recovery/__rproc_shutdown), __rproc_detach() (attach recovery)

**Step 5.3: Callees**
Record: subdev->start / subdev->stop (GLINK, SMD, SSR, virtio).

**Step 5.4: Reachability**
Record: Yes. Qualcomm PAS attach: rproc_add → auto-boot attach work → rproc_boot → rproc_attach → qcom_pas_attach → rproc_report_crash → rproc_crash_handler_work → rproc_trigger_recovery → rproc_boot_recovery → rproc_stop. Matches the posted stack. Coprocessor already crashed at probe is a real boot-time case.

**Step 5.5: Similar patterns**
Record: smd_subdev_stop() has the same NULL-edge unregister. Core flag covers all subdevs, which is why v2 dropped a GLINK-only NULL check.

## Phase 6: This tree

**Step 6.1: Buggy code here?**
Record: Yes. git describe HEAD = v7.3-rc4-27-gf0100363d8c37; make kernelversion = 7.3.0-rc4. Attach, late-attach crash report, GLINK stop-without-NULL-check, and recovery all exist. The fix is already an ancestor of HEAD (git merge-base --is-ancestor f44ae8ce156a3 HEAD succeeded); that is apply-evidence, not the reason to accept it.

**Step 6.2: Backport difficulty**
Record: Clean apply on this tree (already applied). No conflicting refactor of those two functions.

**Step 6.3: Alternate fix already here?**
Record: No other start/stop guard. Later commits (0ec167625b4fe, 74ee3b2f57674) address crash-work vs teardown, not this pairing.

## Phase 7: Subsystem

**Step 7.1:** Record: drivers/remoteproc — **IMPORTANT** (Qualcomm DSP/modem/WiFi remoteprocs; not core mm/vfs, but widely used on phones/embedded).

**Step 7.2:** Record: Actively developed (late attach, async attach, crash-handler races in 2026).

## Phase 8: Impact and risk

**Step 8.1:** Record: Qualcomm (and any rproc) users who attach to an already-running remoteproc. Config: CONFIG_REMOTEPROC plus QCOM PAS/GLINK. Not universal, but a large device population.

**Step 8.2:** Record: Trigger = attach while the remote CPU already crashed (fatal IRQ high) or crash during attach. Seen in the field (oops dump). Not a pure theoretical race; crash work vs rproc->lock is ordered, then stop runs on unstarted subdevs.

**Step 8.3:** Record: Kernel oops / NULL deref. **HIGH/CRITICAL**.

**Step 8.4:** Record: Benefit high (avoids oops during subsystem recovery). Risk very low (9 lines, internal bool, kzalloc-zeroed, lock- held).

## Phase 9: Synthesis

**Step 9.1: Evidence**
**For:**
- Real oops with stack; qcom_glink_smem_unregister(NULL) is visible in code
- In-tree trigger: qcom_pas_attach() + recovery
- This tree has late attach and async attach, so the path is reachable
- Small, obviously correct, maintainer-applied (v3)
- No new UAPI

**Against:**
- Part of a 3-patch series (1/3 is behavioral); this hunk does not need 1/3
- No Fixes: / Cc: stable (not a negative per rules)
- Adds a struct rproc field (in-tree only; kzalloc-safe)

**Unresolved:** Stable mailing-list discussion (lore/stable fetch blocked).

**Step 9.2: Stable rules**
1. Obviously correct and tested? **PASS** — pairing is clear; oops is the test evidence; maintainer applied v3
2. Real user-visible bug? **PASS** — NULL deref oops
3. Important (crash/security/corruption/deadlock)? **PASS** — oops on attach/recovery
4. Small and contained? **PASS** — 9 lines, two functions + one bool
5. No new features/APIs? **PASS** — internal flag
6. Applies to this tree? **PASS** — files and call paths exist; would apply cleanly

**Step 9.3: Exception category**
Record: None. Ordinary crash fix.

**Step 9.4: Decision**
This tree needs the fix: attach can report a crash before subdevices start, and rproc_stop_subdevices() would then oops. The change is minimal and correct.

### What it solves for this tree
If a Qualcomm remoteproc is already crashed when Linux attaches (or crashes during attach), recovery calls rproc_stop() while GLINK/SMD were never started. That is a kernel oops, not a soft failure. The flag makes stop a no-op until start has succeeded.

### Risk vs benefit
Benefit: prevent a boot/recovery oops on common Qualcomm attach hardware. Risk: negligible; flag is zero-initialized and only mutated under rproc->lock.

### Concerns
Patch 1/3 is not required for this hunk. Patch 3/3 is a separate teardown UAF. Neither blocks applying this commit here. No Fixes: tag; the late-attach crash report (16472c99f4699) is in this tree and is the practical introducer of the reported path.

## Verification
- [Phase 1] Parsed tags: author SOB, maintainer SOB, lore Link v3-2; no Fixes/Reported-by/Cc:stable
- [Phase 2] Diff: +7 core, +2 header; flag on successful start; early return in stop
- [Phase 2] qcom_glink_smem_unregister(): smem->glink with no NULL check — matches oops at VA 0x300
- [Phase 3] git describe HEAD: v7.3-rc4-27-gf0100363d8c37; make kernelversion: 7.3.0-rc4
- [Phase 3] git merge-base --is-ancestor f44ae8ce156a3 HEAD: yes (applies/is present)
- [Phase 3] Parent 026a3fada4326 is series 1/3 (async attach); 3/3 is 0ec167625b4fe
- [Phase 3] Blame: start/stop from 2016; flag from this commit
- [Phase 3] Trigger qcom_pas_attach crash report from 16472c99f4699 (in this tree, before this fix)
- [Phase 4] b4 dig -c f44ae8ce156a3: lore thread; v1→v3; Bjorn applied; no NAK
- [Phase 4] b4 dig -w: To Andersson + Poirier
- [Phase 4] Cover letter v2: flag replaced a GLINK-only NULL check
- [Phase 4] UNVERIFIED: stable@ discussion (lore/stable Anubis 403)
- [Phase 5] Call chain verified: qcom_pas_attach → rproc_report_crash → rproc_crash_handler_work → rproc_trigger_recovery → rproc_stop → rproc_stop_subdevices
- [Phase 5] rproc_alloc() uses kzalloc — flag starts false
- [Phase 5] rproc_boot / rproc_trigger_recovery / __rproc_shutdown hold rproc->lock around start/stop
- [Phase 6] Buggy stop-without-start exists conceptually; this tree has attach + late-attach trigger
- [Phase 8] Failure mode: NULL deref oops, severity HIGH/CRITICAL

**YES**

 drivers/remoteproc/remoteproc_core.c | 7 +++++++
 include/linux/remoteproc.h           | 2 ++
 2 files changed, 9 insertions(+)
drivers/remoteproc/remoteproc_core.c +7 -0
index 2336c55eb021d..068a3ef467f78 100644
@@ -1104,6 +1104,8 @@ static int rproc_start_subdevices(struct rproc *rproc)
 		}
 	}
 
+	rproc->subdevs_started = true;
+
 	return 0;
 
 unroll_registration:
@@ -1119,10 +1121,15 @@ static void rproc_stop_subdevices(struct rproc *rproc, bool crashed)
 {
 	struct rproc_subdev *subdev;
 
+	if (!rproc->subdevs_started)
+		return;
+
 	list_for_each_entry_reverse(subdev, &rproc->subdevs, node) {
 		if (subdev->stop)
 			subdev->stop(subdev, crashed);
 	}
+
+	rproc->subdevs_started = false;
 }
 
 static void rproc_unprepare_subdevices(struct rproc *rproc)
include/linux/remoteproc.h +2 -0
index de98462d58889..ef711a5b1a7f2 100644
@@ -273,6 +273,7 @@ enum rproc_features {
  * @has_iommu: flag to indicate if remote processor is behind an MMU
  * @auto_boot: flag to indicate if remote processor should be auto-started
  * @sysfs_read_only: flag to make remoteproc sysfs files read only
+ * @subdevs_started: flag to indicate if subdevs have started
  * @dump_segments: list of segments in the firmware
  * @nb_vdev: number of vdev currently handled by rproc
  * @elf_class: firmware ELF class
@@ -317,6 +318,7 @@ struct rproc {
 	bool has_iommu;
 	bool auto_boot;
 	bool sysfs_read_only;
+	bool subdevs_started;
 	struct list_head dump_segments;
 	int nb_vdev;
 	u8 elf_class;
Signature · 1 line
2.53.0
author maintainer
#49 lore raw

PATCH 1/1 regmap: irq: Free the irqdomain we create

In reply to Sasha Levin

From: Mark Brown <[email protected]>

[ Upstream commit 2e42cade8ff1ff579e77976d9869db4df1feaf74 ]

When domain support was added to regmap-irq it was not possible to remove domains, this was added later by 8ee99ada293b (irqdomain: Support removal of IRQ domains.). We did update the main removal path to free the domain but forgot the error unwinding case during creation that is now in regmap_add_irq_chip_fwnode() after some code motion, meaning that errors during instantiation result in an unused irqchip being left hanging around. Add the missing irq_remove_domain() call where the comment says it should be.

---

LLM Generated explanations, may be completely bogus:

The local tree is **6.18.57**. At that base, regmap_add_irq_chip_fwnode() still has the “Should really dispose of the domain but...” stub, so the leak exists here and the one-line irq_domain_remove() change applies cleanly.

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

**Step 1.1: PARSE THE SUBJECT LINE**
Record: [regmap: irq:] [Free] [Release the irqdomain created during chip setup]

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**
Record:
- Reported-by: Farhad Alemi <[email protected]> (researcher report)
- Reported-by: Thomas Gleixner <[email protected]> (irq subsystem maintainer)
- `Link: https://patch.msgid.link/20260901-regmap-irq-deallocate-
[email protected]`
- Signed-off-by: Mark Brown <[email protected]> (regmap maintainer; author)
- No Fixes: tag (expected)
- No Cc: stable (expected)
- Pipeline-added [Upstream commit 2e42cade8ff1...] and Sasha Levin SOB ignored per instructions
- Notable: two reporters, one of them tglx

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**
Record:
- Bug: when irqdomain support was added to regmap-irq, domains could not be removed. irq_domain_remove() was added later (58ee99ada293b; the message cites 8ee99ada293b, missing the leading 5). The success teardown path was updated; the **creation error-unwind** path was not.
- Symptom: failed instantiation leaves an unused irqchip/domain hanging around.
- Failure mode: resource leak of a published irq domain on request_threaded_irq() failure after regmap_irq_create_domain().
- Root cause (author): missing irq_domain_remove() at the err_domain: label (the comment already said it should be there). The message says irq_remove_domain(); the actual API is irq_domain_remove().
- Version info: none beyond the historical API gap.

**Step 1.4: DETECT HIDDEN BUG FIXES**
Record: Not hidden. This is an explicit error-path resource-leak fix. External reporting (KASAN during CPU hotplug) shows the leaked objects can become a use-after-free, not only a leak.

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

**Step 2.1: INVENTORY THE CHANGES**
Record:
- File: drivers/base/regmap/regmap-irq.c (1 insertion, 1 deletion)
- Function: regmap_add_irq_chip_fwnode()
- Scope: single-file surgical fix

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**
Record:
- Before: domain created → request_threaded_irq() fails → goto err_domain → comment only → mutex/key teardown → kfree(d) while d->domain stays published with host_data = d.
- After: same path calls irq_domain_remove(d->domain) before freeing d.
- Path affected: probe error path only, after successful domain creation.

**Step 2.3: IDENTIFY THE BUG MECHANISM**
Record:
- Category: error-path resource leak; can escalate to UAF because the domain is published (irq_domain_list / fwnode) with host_data pointing at memory that is then freed.
- Mechanism: missing counterpart to the existing irq_domain_remove() in regmap_del_irq_chip().

**Step 2.4: ASSESS THE FIX QUALITY**
Record:
- For irq_base == 0 (most DT callers): obviously correct. Domain has no mappings yet; irq_domain_remove() is the right unwind and matches the del path.
- For irq_base != 0 (legacy/irq_alloc_descs() path, including callers passing -1): incomplete. Domain creation associates IRQs up front. irq_domain_remove() does not dispose those mappings. tglx said the descriptor chip/domain pointers remain and the UAF remains.
- Regression risk: low for irq_base == 0. For irq_base > 0, the domain object is freed while descriptors still reference it (already a UAF on desc->chip before this patch). The change is still a subset of the correct unwind, not a new feature.
- Red flags: none on APIs/scope. Completeness gap is real but does not make the one-line change wrong for the common path.

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

**Step 3.1: BLAME THE CHANGED LINES**
Record:
- Comment/label introduced by 4af8be67fd9989 (“regmap: Convert regmap_irq to use irq_domain”, 2012).
- Domain remove on the **del** path: b5ab3e5cae097 (“regmap: irq:
Remove domain on exit”, 2014).
- err_domain: still only had the comment at **v6.18.57**.
- This is long-lived error-path debt, not a brand-new 6.18-only bug.

**Step 3.2: FOLLOW THE FIXES: TAG**
Record: No Fixes: tag. Historical introducer is 4af8be67fd9989; that commit **is** an ancestor of this tree.

**Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES**
Record:
- Nearby: 1da33858af625 (mutex destroy on error), 76b6e14aa7b08 (lockdep key). Both already in v6.18.57; this patch’s context matches.
- Domain creation helper: dde286ee57704 / regmap_irq_create_domain() already in this tree.
- Standalone 1-line fix, not patch X/Y.
- No follow-up in this tree adding irq_dispose_mapping() on err_domain.

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**
Record: Author is Mark Brown, **regmap maintainer**. He applied his own patch to broonie/regmap.git for-7.3 the same day.

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS** Record:
- Needs irq_domain_remove(): present (58ee99ada293b, exported in this tree).
- Needs d->domain and err_domain:: present.
- Can apply standalone to v6.18.57. No missing helpers.

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

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**
Record:
- Lore/msgid: https://patch.msgid.link/20260901-regmap-irq-deallocate-
[email protected]
- Only v1 (b4 dig -a); no v2 in that thread.
- Thread:
1. Mark posts the 1-line patch (1 Sep 2026).
2. Mark applies it to for-7.3 ~1 hour later.
3. tglx (4 Sep): “That won’t work” for the irq_alloc_descs() / virq_base > 0 case; descriptors keep chip/domain pointers; UAF remains. First suggestion: irq_domain_free_irqs().
4. tglx follow-up: irq_domain_free_irqs() only works with hierarchical domains; use irq_dispose_mapping(irq_base + i) then remove the domain.
5. Mark: “Ah, thanks - I’d expected removing the domain to clean everything up.”
- No NAK of calling irq_domain_remove() itself; the request is additional dispose before remove.
- No reviewer Cc: stable in the thread.

**Step 4.2: CHECK WHO REVIEWED THE PATCH**
Record: Recipients were linux-kernel, Farhad Alemi, tglx, Mark Brown. tglx reviewed after apply. No Acked-by/Reviewed-by on the committed patch.

**Step 4.3: SEARCH FOR THE BUG REPORT**
Record:
- Public write-up (31 Aug 2026): KASAN invalid read in irq_migrate_all_off_this_cpu during CPU offline. tglx traced it to this failed-setup path: descriptors remain mapped to a caller-owned irq_chip after that chip/regmap_irq_chip_data is freed.
- Trigger: device IRQ setup fails, then CPU hotplug walks descriptors.
- Radu Rendec mentioned a similar syzbot hotplug stack; tglx criticized allocation info in that report. Overlap is suggestive, not proven identical.
- Unprivileged exploit/CVE: not established.

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**
Record: Standalone v1. tglx’s dispose-mapping addition was not in this series and is not in this tree. GitHub master snapshot still showed the old comment, consistent with this being a 7.3-era fix not yet universal.

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**
Record: No useful stable-list hit that this was previously rejected or requested. UNVERIFIED beyond search noise.

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

**Step 5.1: IDENTIFY KEY FUNCTIONS IN THE DIFF**
Record: regmap_add_irq_chip_fwnode() only. Callees of interest:
regmap_irq_create_domain(), request_threaded_irq(), irq_domain_remove().

**Step 5.2: TRACE CALLERS**
Record:
- regmap_add_irq_chip() → regmap_add_irq_chip_fwnode()
- devm_regmap_add_irq_chip_fwnode() → same
- git grep -l "regmap_add_irq_chip" → **87** .c files
- Call context: driver probe (MFD/PMIC, ASoC codecs, power, GPIO, RTC, DSA). Not a syscall hot path; boot/enumeration and probe-retry.
- irq_base != 0 callers exist, including popular PMICs: rk8xx-core.c (-1), retu-mfd.c, 88pm800.c, 88pm805.c, mt6370.c, plus board irq_base in tps65910/wm8994/tps65090.

**Step 5.3: TRACE CALLEES**
Record:
- regmap_irq_create_domain() → irq_domain_instantiate() with virq_base = irq_base, host_data = d. If virq_base > 0, __irq_domain_instantiate() runs irq_domain_associate_many().
- if (irq_base) also calls irq_alloc_descs() first (-1 is truthy).
- irq_domain_remove() unpublishes and kfrees the domain; comment requires mappings already disposed.

**Step 5.4: FOLLOW THE CALL CHAIN**
Record:
- Reachable from device probe of many PMICs/codecs.
- Userspace does not call this directly. Probe failure + later CPU offline is the documented KASAN path.
- Deferred probe retry can also leave a stale fwnode domain if the domain is not removed.

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**
Record: regmap_del_irq_chip() already disposes mappings then calls irq_domain_remove(). That is the model tglx wants on err_domain when irq_base > 0. This patch only adds the remove.

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

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?**
Record: Yes, at v6.18.57 drivers/base/regmap/regmap-irq.c err_domain: still has /* Should really dispose of the domain but... */. Introduced 2012; never unwound on this error path here.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**
Record: Expected **clean apply** to v6.18.57. Surrounding mutex_destroy / lockdep_unregister_key already match. irq_domain_remove() already used in the same file’s del path.

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**
Record: Del-path domain remove is here (b5ab3e5cae097). No other fix of this err_domain leak. No irq_dispose_mapping follow-up on that label.

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

**Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY**
Record: drivers/base/regmap IRQ helper. **IMPORTANT** (shared by many PMICs/MFDs, not core mm/sched, but widely used on ARM/embedded and laptops).

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**
Record: Mature (2011+). Recent work is lockdep nesting, mutex free, domain suffix. This is leftover unwind, not churn from a new subsystem.

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

**Step 8.1: DETERMINE WHO IS AFFECTED**
Record: Driver-specific / config-specific (CONFIG_REGMAP_IRQ), but that config is selected by many common PMICs. Affects anyone whose regmap-irq probe fails after domain create.

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**
Record:
- Trigger: regmap_irq_create_domain() succeeds, then request_threaded_irq() fails (bad/missing IRQ, busy IRQ, probe deferral, etc.).
- Not every boot. Realistic on flaky firmware, wrong DT IRQ, deferred probe.
- Unprivileged trigger: not verified. CPU hotplug typically needs privilege. KASAN still shows a real kernel UAF.

**Step 8.3: DETERMINE THE FAILURE MODE SEVERITY**
Record:
- Always: leaked published irq domain; d freed while domain host_data dangles.
- With irq_base != 0: leaked associated IRQ descriptors; desc->chip can UAF on CPU offline (irq_migrate_all_off_this_cpu). **HIGH** (UAF / KASAN).
- This patch fully fixes the domain leak; it does **not** fully fix the descriptor UAF when irq_base > 0.

**Step 8.4: CALCULATE RISK-BENEFIT RATIO**
Record:
- Benefit: high for a 1-line unwind of a published irq domain used by dozens of drivers; needed for probe retry and to stop leaking domain objects.
- Risk: very low for irq_base == 0. For irq_base > 0, incomplete; not a new feature; same class of UAF already existed.
- Ratio: benefit > risk. Follow-up dispose-mapping should also be backported when it exists; that is not a reason to keep the domain leak.

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

**Step 9.1: COMPILE THE EVIDENCE**

FOR:
- Real error-path leak of a published irq domain; comment admitted the gap since 2012.
- Reported by tglx; KASAN UAF on CPU hotplug is a serious failure mode.
- 1 line, same API already used in regmap_del_irq_chip().
- Buggy code is in v6.18.57; irq_domain_remove() is in this tree; applies cleanly.
- Author is the regmap maintainer; 87 in-tree callers.
- Probe-path resource leaks are standard stable material.

AGAINST:
- Incomplete vs the reported irq_base > 0 UAF; tglx asked for irq_dispose_mapping() first; Mark agreed the remove-alone assumption was wrong.
- No Fixes:/Cc: stable (not a negative by itself).
- Applied to for-7.3 before tglx’s review; no v2 in that thread.

UNRESOLVED:
- Whether a later mainline follow-up with irq_dispose_mapping() landed after this tree’s branch.
- Whether the KASAN report was reproduced on 6.18.y specifically (code path is present).
- No stable-list discussion found.

**Step 9.2: APPLY THE STABLE RULES CHECKLIST**
1. Obviously correct and tested? **PASS** for the domain leak (irq_base == 0 and domain object itself). Incomplete for preassociated descriptors, but the added call is the correct API and is already used on the del path.
2. Fixes a real bug that affects users? **PASS** — leaked irq domain on failed probe; KASAN UAF documented on related leftover mappings.
3. Important issue? **PASS** — UAF / resource leak of irq core objects, not cosmetic.
4. Small and contained? **PASS** — 1 line, one function.
5. No new features or APIs? **PASS**
6. Can apply to the local tree? **PASS** — v6.18.57 has the exact hunk context.

**Step 9.3: CHECK FOR EXCEPTION CATEGORIES**
Record: Not ID/quirk/DT/docs. Ordinary error-path leak fix. Build-fix exception N/A.

**Step 9.4: MAKE YOUR DECISION**
This should be backported to **this** 6.18.y tree. The bug is here, the helper is here, and the change is the missing unwind the code has documented for years. Incompleteness for irq_base > 0 means a later dispose-mapping patch is still needed for the full KASAN UAF; it does not make this line a net negative.

### What the commit solves, and why it matters here regmap_add_irq_chip_fwnode() publishes an irq domain, then on request_threaded_irq() failure frees struct regmap_irq_chip_data without removing that domain. Stable 6.18.57 still does this. The leftover domain stays on the global list with dangling host_data, and on the legacy irq_base != 0 path associated descriptors can later be walked during CPU hotplug (KASAN UAF). Many PMICs/MFDs use this helper, including rk8xx with irq_base = -1.

### Stable rules / risk
Small, obviously intended, no new API, applies cleanly. Benefit is fixing a real leak/UAF-adjacent unwind; risk is a 1-line call that the same file already uses on teardown.

Verification:
- [Phase 1] Tags: Farhad Alemi + tglx Reported-by; lore msgid link; Mark Brown SOB; no Fixes/Cc stable
- [Phase 1] Body describes creation-path domain leak after 8ee99ada293b; actual SHA in this tree is 58ee99ada293b
- [Phase 2] Diff is 1 line in regmap_add_irq_chip_fwnode() err_domain:: comment → irq_domain_remove(d->domain)
- [Phase 3] git blame at v6.18.57: comment from 4af8be67fd9989 (2012); del-path remove b5ab3e5cae097 (2014)
- [Phase 3] git merge-base --is-ancestor 4af8be67fd9989 HEAD yes; 58ee99ada293b is ancestor of v6.18.57
- [Phase 3] No follow-up dispose-mapping commit on this file in this tree
- [Phase 4] b4 dig -c 4784831655ab5: v1 only, applied to for-7.3 same day
- [Phase 4] tglx: remove-alone does not clear associated descriptors when virq_base > 0; use irq_dispose_mapping then remove
- [Phase 4] Mark acknowledged he expected remove to clean everything up
- [Phase 4] External write-up: KASAN in irq_migrate_all_off_this_cpu after failed regmap IRQ setup
- [Phase 5] 87 files call regmap_add_irq_chip*; probe of MFD/PMIC/codec/etc.
- [Phase 5] if (irq_base) irq_alloc_descs() plus virq_base associate_many confirmed in this tree
- [Phase 6] git describe HEAD → v6.18.57-155-gcdf239ca885b2; make kernelversion → 6.18.57
- [Phase 6] v6.18.57 still has the dispose comment; irq_domain_remove() already in regmap_del_irq_chip()
- [Phase 8] Failure mode: leaked irq domain; UAF on CPU hotplug for preassociated IRQs; severity HIGH
- UNVERIFIED: later mainline follow-up with irq_dispose_mapping on err_domain; whether syzbot report is the same bug; stable-list history beyond unsuccessful search

**YES**

 drivers/base/regmap/regmap-irq.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/base/regmap/regmap-irq.c +1 -1
index 6112d942499be..8c297156ea402 100644
@@ -941,7 +941,7 @@ int regmap_add_irq_chip_fwnode(struct fwnode_handle *fwnode,
 	return 0;
 
 err_domain:
-	/* Should really dispose of the domain but... */
+	irq_domain_remove(d->domain);
 err_mutex:
 	mutex_destroy(&d->lock);
 	lockdep_unregister_key(&d->lock_key);
Signature · 1 line
2.53.0
author maintainer
#50 lore raw

PATCH 1/1 tty: serial: pch_uart: add check for pci_get_slot()

In reply to Sasha Levin

From: Haoxiang Li <[email protected]>

[ Upstream commit 970ede67de0e3f6a1e707ec99ae49d80bf3f2966 ]

Add check for pci_get_slot() to prevent a potetial null pointer dereference in pch_request_dma().

---

LLM Generated explanations, may be completely bogus:

## Phase 1: Commit message forensics

**Step 1.1: Subject line**
Record: [tty: serial: pch_uart] [add] [NULL check on pci_get_slot() in pch_request_dma()]

**Step 1.2: Tags** (from the candidate message; original mail had extra tags — see Phase 4)
- Reviewed-by: Andy Shevchenko <[email protected]> (serial/PCI reviewer; author of the pci_get_slot() call)
- Link: https://patch.msgid.link/20260623140539.2272473-1- [email protected]
- Signed-off-by: Haoxiang Li (author); Greg Kroah-Hartman (tty maintainer)
- No Reported-by, Tested-by, Acked-by in the committed message
- No Fixes:/Cc: stable in the committed message (expected for this review queue)

**Step 1.3: Body**
Record:
- Bug: pci_get_slot() can return NULL; the caller then does param->dma_dev = &dma_dev->dev.
- Symptom: potential NULL pointer dereference in pch_request_dma().
- No stack trace, reproducer, or version range. Typo “potetial”.
- Root cause as stated: missing return-value check.

**Step 1.4: Hidden bug fix?**
Record: Not hidden. Explicit defensive NULL check. Same pattern as other static-analysis “add check for X()” patches from this author.

---

## Phase 2: Diff analysis

**Step 2.1: Inventory**
Record:
- File: drivers/tty/serial/pch_uart.c (+5 / −0)
- Function: pch_request_dma()
- Scope: single-file surgical fix

**Step 2.2: Flow**
Record: After pci_get_slot(priv->pdev->bus, PCI_DEVFN(PCI_SLOT(priv->pdev->devfn), 0)), the code used dma_dev unconditionally. After the patch, NULL returns with dev_err and no pci_dev_put (correct: no reference was taken). Later failures still use goto err_pci_get → pci_dev_put(dma_dev).

**Step 2.3: Bug mechanism**
Record: **NULL pointer dereference.** pci_get_slot() is documented to return NULL when the slot/function is absent (drivers/pci/search.c). The next statement dereferences dma_dev.

**Step 2.4: Fix quality**
Record: Obviously correct, minimal, no API/lock/structure changes. Regression risk is very low. Early return leaves DMA unset; pch_uart_verify_port() only sets use_dma if priv->chan_rx is set, so PIO fallback still works on that path.

---

## Phase 3: Git history

**Step 3.1: Blame**
Record:
- Driver added in 3c6a483275f47 (2010, “Serial: EG20T: add PCH_UART driver”) using hardcoded pci_get_bus_and_slot().
- Current lookup introduced in 8368d6a2b73900 (Andy Shevchenko, 2014-07-30, v3.17-rc1).
- NULL check added by this commit 970ede67de0e3 (2026-06-23).
- Bug has been in tree for ~12 years.

**Step 3.2: Fixes: tag**
Committed message has none. Original mail (Phase 4) had Fixes: 8368d6a2b739 ("pch_uart: don't hardcode PCI slot to get DMA device").
Record: 8368d6a2b739 **is** an ancestor of this checkout (git merge- base --is-ancestor succeeded; contained in v3.17-rc1).

**Step 3.3: Related file history**
Record:
- 8be3a7bf77370 (2022): missing pci_dev_put() after pci_get_slot() — confirms the API contract (refcount on success, NULL on failure).
- 6fe472c1bbbe2 (2026): NULL check for dma_alloc_coherent() in the same function, with Fixes: + Cc: stable.
- e41c0981213f3 (2013): real NULL deref in this driver when DMA setup failed.
Standalone 5-line patch, not part of a numbered series.

**Step 3.4: Author**
Record: Haoxiang Li is a regular static-analysis contributor, not the tty maintainer. One pch_uart commit. Reviewed by Andy Shevchenko; applied by Greg Kroah-Hartman.

**Step 3.5: Dependencies**
Record: None. Uses existing pci_get_slot(), dev_err, and pch_request_dma(). Applies standalone.

---

## Phase 4: Mailing list / external

**Step 4.1: Original discussion**
Record:
- b4 dig -c 970ede67de0e3 → https://patch.msgid.link/20260623140539.22
[email protected]
- b4 dig -a: v1 only; that version was applied.
- Original body **did** include Fixes: 8368d6a2b739 and `Cc:
[email protected]` (stripped in the git commit; that is why this is in the manual queue, not a reason to reject).
- Andy Shevchenko: *“Not that it's quite possible, but probably you found this due to AI review which might have considered some cases of manual binding a PCI device to any PCI driver. Given that is the case, I'm fine with the change.”*
- No NAK.

**Step 4.2: Recipients (b4 dig -w)**
Record: gregkh, jirislaby, andriy.shevchenko, linux-serial, linux- kernel, **[email protected]**, [email protected]. Right maintainers were on CC. Andy reviewed; Greg applied.

**Step 4.3: Bug report**
Record: No syzbot, bugzilla, or user report. Static/AI analysis of a documented NULL return.

**Step 4.4: Series**
Record: Standalone v1. Related in-function fix 6fe472c1bbbe2 is independent.

**Step 4.5: Stable list**
Record: lore stable search shows the original patch (because it was CCed there) and Andy’s reply. No follow-up rejecting it for stable. WebFetch to lore returned 403; thread recovered via b4 dig -m and curl.

---

## Phase 5: Semantic / call graph

**Step 5.1: Functions**
Record: pch_request_dma() only.

**Step 5.2: Callers**
Record (from this tree):
1. pch_uart_startup() — if priv->use_dma
2. pch_uart_verify_port() — TIOCSSERIAL / setserial path, which this driver historically runs during install (af6d17cdc8c89)

**Step 5.3: Callees**
Record: pci_get_slot, dma_request_channel, dma_alloc_coherent, pci_dev_put.

**Step 5.4: Reachability**
Record: Yes, from userspace serial setup (TIOCSSERIAL) and from UART startup when DMA was already enabled. Needs CONFIG_SERIAL_PCH_UART and typically CONFIG_PCH_DMA. Not a syscall fuzz target for unprivileged users; admin/boot path on EG20T/ML72xx hardware.

**Step 5.5: Similar patterns**
Record: Same function already checks dma_request_channel and dma_alloc_coherent. DMA PCI ID 0x8810 is function-0 sibling of UART IDs 0x8811–0x8814; lookup is “same slot, function 0”.

---

## Phase 6: This checkout

**Step 6.1: Buggy code in this tree?**
Record: Local tree is **v7.3-rc4-27** (Makefile 7.3.0-rc4). Driver and pci_get_slot() lookup are present. Introducing commit 8368d6a2b739 is an ancestor. Current pch_request_dma() already contains the NULL check from 970ede67de0e3 (first appeared v7.2-rc1-21). The bug class exists in this lineage; the file is not missing.

**Step 6.2: Backport difficulty**
Record: Clean apply. Hunk is independent of the later goto ladder.

**Step 6.3: Other fixes already here?**
Record: Refcount leak fix and dma_alloc_coherent check are present. No alternate fix for this NULL case besides this commit.

---

## Phase 7: Subsystem context

**Step 7.1:**
Record: drivers/tty/serial/pch_uart.c — Intel EG20T PCH / LAPIS ML7213/ML7223/ML7831 UART (Atom E6xx-era embedded/IVI). **PERIPHERAL**, but a real in-tree production driver.

**Step 7.2:**
Record: Low churn; occasional correctness fixes. Mature, not staging.

---

## Phase 8: Impact and risk

**Step 8.1: Who is affected**
Record: Driver/config-specific: CONFIG_SERIAL_PCH_UART on 32-bit x86 or MIPS (or COMPILE_TEST). Not universal.

**Step 8.2: Trigger**
Record: pch_request_dma() when function 0 of the UART’s PCI slot is not enumerated (firmware hid DMA, sparse multifunction device, or sysfs bind of this driver to a non-fn0 device with no fn0 sibling). On stock EG20T, fn0 DMA (0x8810) is normally present, so pci_get_slot() succeeds. Unprivileged users cannot bind PCI drivers. verify_port is a real install/setserial path.

**Step 8.3: Failure mode**
Record: Kernel oops (NULL deref) instead of PIO fallback. Severity:
**HIGH** if it fires, **low likelihood** on intended hardware. Andy called the trigger unlikely but accepted the case.

**Step 8.4: Risk/benefit**
Record: Benefit: prevent oops, match existing error handling. Risk: very low (5 lines, error path only). Ratio: favorable.

---

## Phase 9: Synthesis

**Step 9.1: Evidence**

For:
- Real, documented NULL return from pci_get_slot(), immediately dereferenced.
- 5-line, obviously correct check; UART continues without DMA.
- Reviewed by Andy Shevchenko; applied by Greg KH.
- Original submission asked for stable and cited Fixes: 8368d6a2b739 (in tree since v3.17).
- Same function already treats DMA setup failure as a crash-worthy bug (e41c0981213f3, 6fe472c1bbbe2).
- Applies cleanly; no new API; no prerequisites.

Against:
- Niche ~2010 embedded UART.
- No user/syzbot report; likely AI/static analysis.
- Reviewer: trigger is “not quite possible” except odd PCI bind.
- Committed message dropped Cc: stable / Fixes: (auto-select would have needed those tags).

Unresolved: none that change the technical call. Lore WebFetch 403 was covered by b4 + curl.

**Step 9.2: Stable rules**
1. Obviously correct and tested? **PASS** — reviewed; Greg merged; logic is local and clear.
2. Real bug affecting users? **PASS** — API can return NULL; oops if DMA setup runs without fn0. Rare, but not fictional.
3. Important (crash/security/corruption/deadlock)? **PASS** — NULL deref → oops; small blast radius.
4. Small and contained? **PASS** — +5 lines, one function.
5. No new features/APIs? **PASS**.
6. Can apply to this tree? **PASS** — driver and call site exist; hunk is clean.

**Step 9.3: Exception category**
Record: None (not an ID/quirk/DT/build/docs exception). Ordinary memory- safety fix.

**Step 9.4: Decision**
This tree is 7.3-rc4 and already contains the driver. The bug is a NULL deref on a documented failure path, the patch is a five-line guard with PIO fallback, and it needs no other commits. Niche hardware and a rare trigger do not outweigh an oops fix this small. It belongs in this tree.

---

### Problem and why it matters here

pch_request_dma() looks up the EG20T/ML72xx DMA function with pci_get_slot(..., function 0) and then uses dma_dev->dev. If that function is missing, the kernel oopses while opening or reconfiguring the UART. The patch logs and returns so the port can keep running in PIO mode.

### Stable rules / risk

Meets the rules: real crash, tiny, no features, clean apply on this checkout. Benefit (avoid oops) dwarfs regression risk.

### Concerns

Trigger is uncommon on real EG20T boards; this is defensive. That is not a reason to keep a NULL deref. No extra backport work.

---

Verification:
- [Phase 1] Parsed committed tags: Reviewed-by Andy Shevchenko, Link to msgid, SOBs Haoxiang Li + Greg KH; no Reported-by/syzbot.
- [Phase 2] git show 970ede67de0e3: +5 lines in pch_request_dma() after pci_get_slot().
- [Phase 2] Read pch_request_dma() in this tree: check + err_pci_get/pci_dev_put paths confirmed.
- [Phase 3] git blame / git log -L: lookup from 8368d6a2b739 (v3.17-rc1); driver from 3c6a483275f47 (2010).
- [Phase 3] git merge-base --is-ancestor 8368d6a2b739 HEAD → yes.
- [Phase 3] Related: 8be3a7bf77370 refcount, 6fe472c1bbbe2 dma_alloc check, e41c0981213f3 historical DMA NULL oops.
- [Phase 4] b4 dig -c/-a/-w/-m: v1 thread; original had Fixes:+Cc:stable; Andy Reviewed-by; no NAK.
- [Phase 4] WebFetch lore 403; curl on lore stable showed patch + Andy reply only.
- [Phase 5] Callers: pch_uart_startup (line 1267), pch_uart_verify_port (line 1427).
- [Phase 5] pci_get_slot() in drivers/pci/search.c returns NULL if not found.
- [Phase 6] git describe HEAD = v7.3-rc4-27-gf0100363d8c37; make kernelversion = 7.3.0-rc4.
- [Phase 6] git merge-base --is-ancestor 970ede67de0e3 HEAD → yes (first at v7.2-rc1-21).
- [Phase 7] Kconfig SERIAL_PCH_UART: EG20T/ML7213/ML7223/ML7831.
- [Phase 8] DMA ID 0x8810 vs UART 0x8811–0x8814 in pch_dma.c / pch_uart.c.
- UNVERIFIED: live crash on real EG20T hardware (no user report).

**YES**

 drivers/tty/serial/pch_uart.c | 5 +++++
 1 file changed, 5 insertions(+)
drivers/tty/serial/pch_uart.c +5 -0
index c3f32e0590b7f..9104361ccb14f 100644
@@ -678,6 +678,11 @@ static void pch_request_dma(struct uart_port *port)
 	/* Get DMA's dev information */
 	dma_dev = pci_get_slot(priv->pdev->bus,
 			PCI_DEVFN(PCI_SLOT(priv->pdev->devfn), 0));
+	if (!dma_dev) {
+		dev_err(priv->port.dev, "%s: failed to get DMA device\n",
+			__func__);
+		return;
+	}
 
 	/* Set Tx DMA */
 	param = &priv->param_tx;
Signature · 1 line
2.53.0
#51 lore raw

Re: [PATCH AUTOSEL 6.18-5.10] tty: serial: pch_uart: add check for pci_get_slot()

Sashiko has reviewed this patch and found no issues.
Quoted 4 lines

From: Haoxiang Li <[email protected]>

[ Upstream commit 970ede67de0e3f6a1e707ec99ae49d80bf3f2966 ]

Quoted 8 lines

Add check for pci_get_slot() to prevent a potetial null pointer dereference in pch_request_dma().

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author maintainer
#52 lore raw

PATCH 1/1 nvme: ratelimit the completion-path messages driven by device data

In reply to Sasha Levin

From: Chao Shi <[email protected]>

[ Upstream commit c05c86681170e381e24498257db3a879deb1ae89 ]

nvme_find_rq() and nvme_handle_cqe() print an unratelimited message for every completion queue entry whose command id does not resolve to an in-flight request. Both are reached from the completion interrupt path (nvme_irq() -> nvme_poll_cq() -> nvme_handle_cqe()) and the decision to print is made entirely from device-supplied data, so a controller that posts a stream of bogus command ids drives unbounded printk from hard interrupt context.

This is not hypothetical. A single boot under an emulated controller that posts invalid completions produced 846 "could not locate request for tag 0x0", 846 "invalid id 0 completed on queue 2" and 123 "genctr mismatch" lines. Once the tag set has been torn down every subsequent completion resolves to nothing, so the print rate is bounded only by how fast the device can post entries.

Ratelimit the three messages. The information they carry is diagnostic and repeats, so the suppression count printed by the ratelimit helpers is enough to tell that the condition persists. This matches how the other device-driven error prints in the driver are already handled, for example the status messages in nvme_log_error() and nvme_log_err_passthru().

nvme_find_rq() lives in nvme.h and is shared by pci, tcp, rdma, apple and target-loop, so all transports are covered.

Found by FuzzNvme.

---

LLM Generated explanations, may be completely bogus:

I have enough local-tree and review evidence to decide. The remaining work is to write the full nine-phase analysis.

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

Step 1.1: PARSE THE SUBJECT LINE
Record: **[nvme]** **[ratelimit]** Completion-path messages that fire from device-supplied command IDs are unbounded; the commit rate-limits those three prints.

Step 1.2: PARSE ALL COMMIT MESSAGE TAGS
Record:
- **Signed-off-by:** Chao Shi \<[email protected]\> (author)
- **Signed-off-by:** Keith Busch \<[email protected]\> (NVMe maintainer; applied the patch)
- **No Fixes:** tag (expected for this review queue)
- **No Cc: stable** (expected; not a negative)
- **No Reported-by / Tested-by / Reviewed-by / Acked-by / Link:**
- Notable: “Found by FuzzNvme” in the body (fuzzer-found, not syzbot)
- Ignore any pipeline “Upstream commit” / “Signed-off-by: Sasha Levin” markers

Step 1.3: ANALYZE THE COMMIT BODY TEXT
Record:
- **Bug:** nvme_find_rq() and nvme_handle_cqe() print on every CQE whose command id does not map to an in-flight request. The print decision is made from device-supplied data.
- **Symptom:** Unbounded printk from the completion interrupt path (nvme_irq() → nvme_poll_cq() → nvme_handle_cqe()). One emulated- controller boot produced 846 “could not locate request for tag 0x0”, 846 “invalid id 0 completed on queue 2”, and 123 “genctr mismatch” lines. After the tag set is torn down, every later completion prints; rate is limited only by how fast the device posts entries.
- **Version info:** None in the message. The prints have been in-tree since v5.15 / v5.9 (verified in Phase 3).
- **Root cause:** Device-controlled, unratelimited diagnostics on the hard-IRQ completion path. Other device-driven NVMe error prints (nvme_log_error(), nvme_log_err_passthru()) are already ratelimited.

Step 1.4: DETECT HIDDEN BUG FIXES
Record: Not a disguised cleanup. It is an explicit fix for IRQ-context log flood. The subject uses “ratelimit” rather than “fix”, but the body states the failure mode and a concrete reproduction.

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

Step 2.1: INVENTORY THE CHANGES
Record:
- drivers/nvme/host/nvme.h: nvme_find_rq() — pr_err → pr_err_ratelimited; dev_err → dev_err_ratelimited (~5 lines net churn)
- drivers/nvme/host/pci.c: nvme_handle_cqe() — dev_warn → dev_warn_ratelimited (3 lines)
- Scope: **single-purpose surgical fix**, two files, ~9 insertions / 8 deletions. No logic, locking, or API changes.

Step 2.2: UNDERSTAND THE CODE FLOW CHANGE
Record:
- Hunk 1 (nvme_find_rq, missing request): same return NULL; only the error print is ratelimited.
- Hunk 2 (nvme_find_rq, genctr mismatch): same return NULL; only the error print is ratelimited.
- Hunk 3 (nvme_handle_cqe, invalid id): same early return; only the warning is ratelimited.
- Affected path: completion / IRQ / poll error path when the device posts a bad command id. Success path is unchanged.

Step 2.3: IDENTIFY THE BUG MECHANISM
Record:
- **Category:** Logic / correctness of diagnostics; IRQ-context resource/DoS (unbounded printk driven by device data).
- **Mechanism:** A malicious or failing controller can post a stream of CQEs with bogus command ids. Each entry hits pr_err/dev_err/dev_warn in nvme_irq(). After tag-set teardown the miss path is permanent. _ratelimited variants cap volume while still reporting that the condition persists (suppression count).

Step 2.4: ASSESS THE FIX QUALITY
Record:
- Obviously correct: swap to helpers already used in the same driver (nvme_log_error(), PCI timeout path).
- Minimal: three call-site changes, no behavior change on the success path.
- Regression risk: very low. Worst case is fewer repeated log lines for a persistent fault; first occurrences and the ratelimit “suppressed” count remain.
- Red flags: none (no API, locking, or data-structure changes).

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

Step 3.1: BLAME THE CHANGED LINES
Record:
- nvme_find_rq() and both prints: e7006de6c23803 (“nvme: code command_id with a genctr for use-after-free validation”, Sagi Grimberg, 2021-06-16). Contained in **v5.15-rc1**. Present in this tree (git merge-base --is-ancestor succeeded).
- PCI “invalid id” print: 50b7c24390a53c (“nvme-pci: fix NULL req in completion handler”, Xianting Tian, 2020-09-22). Contained in **v5.9-rc7**. Present in this tree.
- The buggy prints have been in NVMe for years, including all 6.12.y history.

Step 3.2: FOLLOW THE FIXES: TAG
Record: No Fixes: tag. N/A. The introducing commits above are the functional origin.

Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES
Record:
- git log --oneline -15 HEAD -- drivers/nvme/host/nvme.h shows no later rewrite of nvme_find_rq().
- git log --oneline --grep="ratelimit the completion-path" HEAD -- drivers/nvme/ is empty: this fix is **not** in the local tree.
- Standalone one-patch change. Not “patch X/Y”. Keith applied it to nvme-7.3 with only a line-wrap tweak.

Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS
Record:
- Chao Shi: only 4298c52252cf6 (“nvme: reject passthrough of driver- managed Set Features”) in this tree under drivers/nvme/. Not a series dependency.
- Keith Busch is an NVMe maintainer; his SOB is a strong quality signal.

Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS
Record: No new helpers or structs. pr_err_ratelimited / dev_err_ratelimited / dev_warn_ratelimited exist in this tree (include/linux/printk.h, include/linux/dev_printk.h) and are already used in drivers/nvme/host/core.c and pci.c. Applies standalone.

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

Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION
Record:
- b4 dig -c <msgid> failed: the landed commit is not in this checkout, so there is no local commit-ish to match.
- Thread recovered from Patchew and Openwall (lore.kernel.org returned 403):
- Submission: https://patchew.org/linux/20260810220258.1960208-1-

    [email protected]/
  - Message-ID: `[email protected]`
    (2026-08-10)

- Single v1 patch (not a multi-revision series).
- Keith Busch: agreed that dumping every garbage CQE adds no diagnostic value; **applied to nvme-7.3** with a minor overly-long-line wrap. No NAK, no stability concern.
- Author replied that later submissions would avoid long lines. That is style only; Keith already applied the wrap.

Step 4.2: CHECK WHO REVIEWED THE PATCH
Record: To/Cc on the v1: Keith Busch, Jens Axboe, Christoph Hellwig, Sagi Grimberg, linux-nvme, linux-kernel. Maintainer applied it. No separate Reviewed-by on the provided commit text.

Step 4.3: SEARCH FOR THE BUG REPORT
Record: No bugzilla/syzbot link. Reproduction is in the commit: FuzzNvme
+ emulated controller, 1815 diagnostic lines in one boot. Severity from the author’s data: hard-IRQ printk flood, unbounded after tag-set teardown.

Step 4.4: CHECK FOR RELATED PATCHES AND SERIES
Record: Standalone. Sibling unratelimited prints remain in apple/tcp/rdma/loop *after* nvme_find_rq() fails; those are extra transport messages, not prerequisites. This patch still covers the shared nvme_find_rq() prints on all of those transports.

Step 4.5: CHECK STABLE MAILING LIST HISTORY
Record: lore.kernel.org/stable search returned 403. Openwall/Patchew show no stable NAK or “already rejected” discussion. UNVERIFIED: no evidence this was previously declined for stable.

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

Step 5.1: IDENTIFY KEY FUNCTIONS IN THE DIFF
Record: nvme_find_rq() (inline in nvme.h); nvme_handle_cqe() (pci.c).

Step 5.2: TRACE CALLERS
Record (verified with grep + reads):
- nvme_find_rq():
- nvme_handle_cqe() — PCI
- nvme_tcp_process_nvme_cqe(), nvme_tcp_handle_c2h_data(),

    `nvme_tcp_handle_r2t()` — TCP

- nvme_rdma_process_nvme_rsp() — RDMA
- apple_nvme_handle_cqe() — Apple
- nvme_loop completion path — target-loop
- nvme_handle_cqe() ← nvme_poll_cq() ← nvme_irq() (hard IRQ or threaded IRQ), nvme_poll_irqdisable(), nvme_poll(), nvme_reap_pending_cqes().
- Impact: every NVMe transport’s completion path. PCI hard-IRQ is the hottest and the one the commit calls out.

Step 5.3: TRACE CALLEES
Record: blk_mq_tag_to_rq(), genctr helpers, then pr_* / dev_*. No allocation, no new locking.

Step 5.4: FOLLOW THE CALL CHAIN
Record: PCI: device posts CQE → MSI/MSI-X → nvme_irq() → nvme_poll_cq() → nvme_handle_cqe() → nvme_find_rq(). Reachable whenever an NVMe controller is attached, including VMs/emulators and failing real devices. Userspace does not need a special syscall; a bad device is enough. FuzzNvme reached it.

Step 5.5: SEARCH FOR SIMILAR PATTERNS
Record: Same driver already ratelimits device-driven errors (nvme_log_error, nvme_log_err_passthru, PCI timeout dev_warn_ratelimited). Apple still has an unratelimited “invalid id” dev_warn; TCP/RDMA/loop have their own unratelimited “bad command_id” prints. Those leftovers do not block this fix.

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

Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?
Record: **Yes.** Local tree is **6.12.111** (git describe HEAD → p-6.12-3-gc504cf0baa3d8, make kernelversion → 6.12.111).
- drivers/nvme/host/nvme.h:598-607 still uses pr_err / dev_err.
- drivers/nvme/host/pci.c:1128-1130 still uses dev_warn.
- Introducing commits are ancestors of HEAD. Bug present since v5.15 (find_rq) / v5.9 (PCI invalid-id print).

Step 6.2: CHECK FOR BACKPORT COMPLICATIONS
Record: **Clean apply (line-number offset only).** The 6.12 nvme_find_rq() body matches the hunk. nvme_handle_cqe() differs later (trace_nvme_sq lacks the newer data_race() comment in this tree), but that is after the changed warn. No conflicting refactor.

Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE
Record: No commit in this tree ratelimits these three messages. No alternate fix found.

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

Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY
Record: **NVMe host** (drivers/nvme/host/). **IMPORTANT** — primary block storage on servers, workstations, and many embedded/Android platforms. Not core mm/VFS, but a very common production driver.

Step 7.2: ASSESS SUBSYSTEM ACTIVITY
Record: Active in this 6.12 branch (recent PCI IRQ, doorbell, quirk, and core lifetime fixes). The buggy prints themselves have been unchanged since 2021.

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

Step 8.1: DETERMINE WHO IS AFFECTED
Record: **Driver-specific**, all NVMe host transports via nvme_find_rq(); PCI users are the main hard-IRQ case. Large user population whenever a controller posts invalid completions (faulty firmware, reset/teardown, emulator, fuzzer, passthrough VM).

Step 8.2: DETERMINE THE TRIGGER CONDITIONS
Record:
- Trigger: CQE with a command id that does not resolve, or genctr mismatch; also every completion after tag-set teardown.
- Commonness: rare on healthy hardware; realistic on failing devices, resets, and VMs. FuzzNvme hit it in one boot.
- Unprivileged userspace: not via a normal syscall on a healthy disk. A VM user with an emulated/passthrough NVMe device, or a malicious controller, can drive it. Device-controlled printk from IRQ is a host DoS vector in those setups.

Step 8.3: DETERMINE THE FAILURE MODE SEVERITY
Record:
- **Failure mode:** Unbounded printk from hard IRQ / completion context. Can stall on console_lock, flood the log, and contribute to soft lockups on slow consoles. Not a UAF/oops by itself.
- **Severity: HIGH** (IRQ-context flood / hang risk), not CRITICAL (no panic/corruption on the success path).

Step 8.4: CALCULATE RISK-BENEFIT RATIO
Record:
- **Benefit:** High for NVMe users who hit a dying, resetting, or emulated controller — stops IRQ printk storms that have been demonstrated in practice.
- **Risk:** Very low (3 call-site swaps to existing ratelimit helpers).
- **Ratio:** Strongly favors backport.

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

Step 9.1: COMPILE THE EVIDENCE
**FOR:**
- Real, reproduced bug (1815 lines in one boot; FuzzNvme).
- Hard-IRQ, device-controlled printk — known lockup/DoS class.
- After tag-set teardown the miss path is permanent; print rate = device CQE rate.
- Tiny, obviously correct, matches existing NVMe style.
- Maintainer (Keith Busch) applied it with agreement, no NAK.
- Buggy code present in this 6.12.111 tree since v5.15/v5.9.
- Applies cleanly; no prerequisites.
- nvme_find_rq() is shared across PCI/TCP/RDMA/Apple/loop.

**AGAINST:**
- Not a crash, UAF, or data-corruption fix.
- Healthy devices rarely hit the path.
- Transport-local “bad command_id” prints in tcp/rdma/apple/loop stay unratelimited (incomplete sibling coverage, not a dependency).

**UNRESOLVED:**
- lore.kernel.org 403; discussion recovered from Patchew/Openwall.
- b4 dig -c could not run against a local SHA (commit not in this tree).
- No stable-list discussion found (search blocked).

Step 9.2: APPLY THE STABLE RULES CHECKLIST
1. Obviously correct and tested? **PASS** — three _ratelimited swaps; maintainer applied; FuzzNvme reproduction.
2. Fixes a real bug that affects users? **PASS** — documented IRQ printk flood; teardown path makes it unbounded.
3. Important issue (crash, security, corruption, deadlock)? **PASS** — IRQ-context flood can stall the console / soft-lockup; device-driven DoS. Severity HIGH.
4. Small and contained? **PASS** — ~9/+8 lines, two files, error prints only.
5. No new features or APIs? **PASS**.
6. Can apply to the local tree? **PASS** — buggy code present; helpers present; clean apply expected.

Step 9.3: CHECK FOR EXCEPTION CATEGORIES
Record: Not a device-ID / quirk / DT / build / docs exception. Qualifies as a normal small stability fix.

Step 9.4: MAKE YOUR DECISION
This belongs on 6.12.y. The tree still has the unratelimited IRQ prints, the fix is surgical, and the failure mode is a real host-stability problem on failing or emulated NVMe — not a feature or cleanup.

Detailed explanation:
The problem is unbounded printk from NVMe completion handling when the device supplies a command id that does not map to an in-flight request. That path runs from nvme_irq() in hard interrupt context (or the equivalent completion callbacks on other transports). After the tag set is torn down, every CQE misses, so a broken controller can print as fast as it can post completions. That is a real production concern during reset/remove of a failing disk and in VMs; FuzzNvme already produced thousands of lines in one boot. Rate-limiting those three diagnostics matches nvme_log_error() and does not change I/O completion logic. Risk is negligible; benefit is avoiding IRQ-context log storms on a widely deployed storage stack.

Verification:
- [Phase 1] Parsed tags: author SOB Chao Shi; maintainer SOB Keith Busch; no Fixes/Cc stable/Reported-by (expected).
- [Phase 1] Body: concrete counts (846/846/123) and IRQ path nvme_irq → nvme_poll_cq → nvme_handle_cqe.
- [Phase 2] Diff: pr_err/dev_err/dev_warn → _ratelimited in nvme_find_rq and nvme_handle_cqe only.
- [Phase 3] git blame drivers/nvme/host/nvme.h: prints from e7006de6c23803 (v5.15-rc1).
- [Phase 3] git blame drivers/nvme/host/pci.c: invalid-id print from 50b7c24390a53c (v5.9-rc7).
- [Phase 3] git merge-base --is-ancestor e7006de6c23803 HEAD and 50b7c24390a53c HEAD: both ancestors.
- [Phase 3] git log --grep="ratelimit the completion-path" HEAD -- drivers/nvme/: empty; fix not in this tree.
- [Phase 4] b4 dig needs a local commit-ish; candidate is not in this checkout — UNVERIFIED via b4.
- [Phase 4] Patchew + Openwall: v1 applied by Keith Busch to nvme-7.3; no NAK.
- [Phase 4] lore.kernel.org fetch: 403 — discussion taken from Patchew/Openwall instead.
- [Phase 5] Callers of nvme_find_rq: pci, tcp, rdma, apple, target/loop (grep).
- [Phase 5] nvme_poll_cq called from nvme_irq, nvme_poll_irqdisable, nvme_poll, nvme_reap_pending_cqes.
- [Phase 5] queue_request_irq() registers nvme_irq as the hard-IRQ handler (or thread fn).
- [Phase 5] Ratelimit macros present in include/linux/printk.h and include/linux/dev_printk.h; already used in nvme_log_error().
- [Phase 6] git describe HEAD / make kernelversion: 6.12.111 (p-6.12-3-gc504cf0baa3d8).
- [Phase 6] Read nvme.h:598-607 and pci.c:1126-1131: unratelimited prints still present.
- [Phase 8] Failure mode: device-driven printk flood from hard IRQ; severity HIGH (lockup/DoS), not oops/UAF.
- UNVERIFIED: whether this SHA already exists on some other remote branch (not required; local tree does not have the fix).
- UNVERIFIED: stable mailing-list history (lore/stable 403).

**YES**

 drivers/nvme/host/nvme.h | 6 +++---
 drivers/nvme/host/pci.c  | 6 +++---
 2 files changed, 6 insertions(+), 6 deletions(-)
drivers/nvme/host/nvme.h +3 -3
index ec03a07617af1..b28c1a82f79e6 100644
@@ -672,12 +672,12 @@ static inline struct request *nvme_find_rq(struct blk_mq_tags *tags,
 
 	rq = blk_mq_tag_to_rq(tags, tag);
 	if (unlikely(!rq)) {
-		pr_err("could not locate request for tag %#x\n",
-			tag);
+		pr_err_ratelimited("could not locate request for tag %#x\n",
+				   tag);
 		return NULL;
 	}
 	if (unlikely(nvme_genctr_mask(nvme_req(rq)->genctr) != genctr)) {
-		dev_err(nvme_req(rq)->ctrl->device,
+		dev_err_ratelimited(nvme_req(rq)->ctrl->device,
 			"request %#x genctr mismatch (got %#x expected %#x)\n",
 			tag, genctr, nvme_genctr_mask(nvme_req(rq)->genctr));
 		return NULL;
drivers/nvme/host/pci.c +3 -3
index 4efb55f1e3833..6e4261b0a0821 100644
@@ -1375,9 +1375,9 @@ static inline void nvme_handle_cqe(struct nvme_queue *nvmeq,
 
 	req = nvme_find_rq(nvme_queue_tagset(nvmeq), command_id);
 	if (unlikely(!req)) {
-		dev_warn(nvmeq->dev->ctrl.device,
-			"invalid id %d completed on queue %d\n",
-			command_id, le16_to_cpu(cqe->sq_id));
+		dev_warn_ratelimited(nvmeq->dev->ctrl.device,
+				     "invalid id %d completed on queue %d\n",
+				     command_id, le16_to_cpu(cqe->sq_id));
 		return;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#53 lore raw

PATCH 1/1 PCI: switchtec: Add Microchip PCI1008 to NTB DMA alias quirk

In reply to Sasha Levin

From: Logan Gunthorpe <[email protected]>

[ Upstream commit 00a479ba1d01249d43ca5e453380d1ed60946f8a ]

Add the PCI1008 device ID to the quirk_switchtec_ntb_dma_alias PCI fixup table. Without it, DMA transactions from a PCI1008 switch's NTB function are not given the correct requester ID alias, which can misdirect them under an IOMMU.

---

LLM Generated explanations, may be completely bogus:

This is a one-line PCI ID addition to an existing NTB DMA-alias quirk. The local tree is **v7.3-rc4** (7.3.0-rc4, HEAD f0100363d8c37). The SWITCHTEC_PCI100X_QUIRK table is present, so the change belongs here.

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

**Step 1.1: PARSE THE SUBJECT LINE**

Record: [PCI: switchtec:] [Add] [PCI1008 device ID to the existing NTB DMA alias quirk table]

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

Record:
- Fixes: — none (expected)
- Reported-by: — none
- Tested-by: — none
- Reviewed-by: — none
- Acked-by: — none on this patch; Vinod Koul acked series patch 1/3 (dmaengine ID)
- Link:
https://patch.msgid.link/[email protected]
(series 3/3)
- Cc: [email protected] — none (expected)
- Signed-off-by: Logan Gunthorpe <[email protected]> (author; SWITCHTEC DMA maintainer)
- Signed-off-by: Bjorn Helgaas <[email protected]> (PCI subsystem maintainer)

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

Record:
- **Bug:** PCI1008 is missing from quirk_switchtec_ntb_dma_alias. Switchtec NTB replaces the original requester ID with a hardware proxy ID. Without an IOMMU alias, those TLPs are not attributed to the NTB device.
- **Symptom:** DMA from a PCI1008 NTB function can be misdirected or blocked when an IOMMU is on (IOMMU faults / failed peer DMA).
- **Versions:** none named. Series cover letter says the patches were based on v7.2-rc3; Bjorn applied them for v7.3.
- **Root cause:** the PCI100X quirk table lists 0x1001–0x1006 only; PCI1008 (0x1008) was never added.

**Step 1.4: DETECT HIDDEN BUG FIXES**

Record: Not hidden. It is an explicit hardware-quirk / device-ID addition. That is a documented stable exception, not cleanup.

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

**Step 2.1: INVENTORY THE CHANGES**

Record:
- File: drivers/pci/quirks.c — **+1 / −0**
- Function: none changed; one SWITCHTEC_PCI100X_QUIRK(0x1008) entry added next to 0x1001–0x1006
- Scope: single-file, one-line surgical fix

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

Record:
- **Before:** DECLARE_PCI_FIXUP_CLASS_FINAL(PCI_VENDOR_ID_EFAR, 0x1008, PCI_CLASS_BRIDGE_OTHER, 8, quirk_switchtec_ntb_dma_alias) is not registered. A PCI1008 NTB function never runs the quirk.
- **After:** the same FINAL-class fixup used for PCI1001–PCI1006 is registered for 0x1008. Enumeration of a matching device calls quirk_switchtec_ntb_dma_alias(), which reads the NTB proxy-ID tables and calls pci_add_dma_alias().
- Path: PCI enumeration / class fixup FINAL (init), not a hot path.

**Step 2.3: IDENTIFY THE BUG MECHANISM**

Record:
- **Category:** (h) Hardware workaround — PCI ID added to an existing quirk table
- **Mechanism:** Switchtec NTB DMA uses proxy requester IDs. IOMMU groups are built from those aliases. Missing 0x1008 means PCI1008 proxy IDs are not aliased, so IOMMU policy does not match the requester ID on the wire.

**Step 2.4: ASSESS THE FIX QUALITY**

Record:
- Obviously correct: same macro and comment style as PCI1001–PCI1006.
- Minimal: one line, no API or structure change.
- Regression risk: very low. The new fixup only matches vendor EFAR + device 0x1008 + class PCI_CLASS_BRIDGE_OTHER. Other devices are unchanged. quirk_switchtec_ntb_dma_alias() already bounds table_sz (skip 0, reject >512).
- Red flags: none. A pre-existing ep_map + 4 pointer-arithmetic issue in the quirk function was flagged on the list; it is not introduced by this line.

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

**Step 3.1: BLAME THE CHANGED LINES**

Record:
- Surrounding SWITCHTEC_PCI100X_QUIRK entries: a3282f84b2151 (“PCI:
switchtec: Add Microchip PCI100X device IDs”, 2025-01-21). Present in v6.14, not in v6.13.
- Original Switchtec NTB DMA alias quirk: ad281ecf1c7d4 (“PCI: Add DMA alias quirk for Microsemi Switchtec NTB”, 2018-06-29). Present in this tree.
- The 0x1008 line itself is this commit (00a479ba1d012).

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

Record: No Fixes: tag. The omission is the PCI1008 ID never being added when PCI100X support landed in a3282f84b2151 (six SKUs 1001–1006). PCI1008 is a later part.

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

Record:
- Same series (msgid 20260714212010.230606-*, based on v7.2-rc3, applied to pci/switchtec for v7.3):
1. 8b326de3cc02c dmaengine: switchtec-dma: Add PCI1008 device ID

     (`-2`)
  2. `0d8a6306c680e` PCI: switchtec: Add Microchip PCI1008 device ID
     (`-3`)

3. 00a479ba1d012 this patch (-4, submitted as 3/3)
- This patch is standalone. The quirk is a PCI fixup, not a driver ID table. It does not need the switchtec or switchtec-dma ID additions.

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

Record: Logan Gunthorpe is listed maintainer of SWITCHTEC DMA (MAINTAINERS) and a long-time switchtec contributor. Bjorn Helgaas (PCI maintainer) signed off and applied the series.

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

Record:
- Prerequisite in this tree: SWITCHTEC_PCI100X_QUIRK / PCI_VENDOR_ID_EFAR table from a3282f84b2151 — present.
- quirk_switchtec_ntb_dma_alias() and pci_add_dma_alias() — present.
- No other structural dependency. Can apply standalone.

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

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

Record:
- b4 dig -c 00a479ba1d012 →
https://patch.msgid.link/[email protected]
- Subject on list: [PATCH v1 3/3] PCI: Add PCI1008 to switchtec NTB DMA alias quirk
- b4 dig -a: only v1. Cover letter [PATCH v1 0/3] switchtec: add new device IDs.
- Direct lore.kernel.org HTTP fetch returned 403/Anubis; the thread was recovered via b4 dig -m.
- Review: no NAKs. Sashiko noted a pre-existing ep_map + 4 pointer issue; Logan said it is unrelated and should not gate the series.
Bjorn: “Applied to pci/switchtec for v7.3, thanks!”
- No reviewer asked for Cc: stable.

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

Record (b4 dig -w): Logan Gunthorpe, linux-pci, linux-kernel, dmaengine, Vinod Koul, Bjorn Helgaas, Frank Li, Kelvin Cao (Microchip / SWITCHTEC DMA co-maintainer). PCI and dmaengine maintainers were on the original To/Cc.

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

Record: No bugzilla/syzbot link. Cover letter: Logan originally had only the dmaengine ID; Sashiko reminded him to add the management ID and the NTB quirk, then he sent this 3-patch series. Hardware impact is described in the patch, not in a separate user report.

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

Record: Three independent 1-line ID additions (dmaengine, switchtec management, NTB quirk). This quirk patch is self-contained. The other two enable management/NTB userspace and the DMA engine; they are not required for the IOMMU alias.

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

Record: lore.kernel.org/stable search for PCI1008 returned HTTP 403. No stable discussion in the linux-pci mbox. UNVERIFIED whether anyone requested this on stable@ after merge.

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

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

Record: No function body edited. New fixup entry invokes existing quirk_switchtec_ntb_dma_alias().

**Step 5.2: TRACE CALLERS**

Record: Not called in C. Registered with DECLARE_PCI_FIXUP_CLASS_FINAL(PCI_VENDOR_ID_EFAR, 0x1008, PCI_CLASS_BRIDGE_OTHER, 8, ...). PCI core runs class FINAL fixups during device setup, before typical driver probe. Context: boot/hotplug enumeration, not IRQ.

**Step 5.3: TRACE CALLEES**

Record: quirk_switchtec_ntb_dma_alias() uses pci_enable_device, pci_iomap, MMIO reads of NTB partition/proxy tables, pci_add_dma_alias(), then unmap/disable. pci_add_dma_alias() sets dma_alias_mask bits used to program IOMMU source IDs.

**Step 5.4: FOLLOW THE CALL CHAIN**

Record: PCI enumeration → class FINAL fixup → alias programming → IOMMU group creation. Reachable only with PCI1008 hardware present. Unprivileged userspace cannot trigger the quirk directly; a user of that NTB/IOMMU path sees DMA failures if it is missing.

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**

Record: Same pattern as PCI1001–PCI1006 in this file, and as many other pci_add_dma_alias quirks (PLX NTB, Ricoh, Marvell, etc.). Adding 0x1008 is consistent with how every prior Switchtec/PCI100X ID was handled.

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

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

Record: Yes. drivers/pci/quirks.c has SWITCHTEC_PCI100X_QUIRK for 0x1001–0x1006. Without 0x1008, a PCI1008 NTB function would not get aliases. a3282f84b2151 (v6.14) added the table; this tree is 7.3-rc4, so the table is present. git merge-base --is-ancestor 00a479ba1d012 HEAD is true (commit is already in 7.3-rc1); that is not treated as “already selected for stable.”

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**

Record: Expected apply: **clean**. Context is the existing PCI100X quirk block, unchanged except for the new line. No refactor of this table since it was added.

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

Record: No alternate PCI1008 NTB alias fix. Companion IDs in switchtec.c and switchtec_dma.c are the sibling series patches, not substitutes for this quirk.

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

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

Record: [PCI quirks / Switchtec NTB DMA alias] [IMPORTANT] — not core mm/scheduler, but PCI IOMMU correctness for NTB. Affects systems with this Microchip switch and IOMMU enabled.

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**

Record: PCI quirks and switchtec are actively maintained (recent pci/switchtec and pci/virtualization merges on this tree). The quirk function itself has been stable since 2018; PCI100X IDs since v6.14.

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

**Step 8.1: DETERMINE WHO IS AFFECTED**

Record: Driver/hardware-specific: Microchip PCI1008 (vendor EFAR 0x1055, device 0x1008) with NTB and IOMMU. Not universal.

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**

Record: Present whenever that device is enumerated with IOMMU on. Not a race. Not triggerable by an unprivileged syscall on machines without the hardware. Common for any PCI1008 NTB + IOMMU deployment.

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

Record: IOMMU rejects or mis-groups DMA from NTB proxy IDs → DMA failures, IOMMU faults, broken peer NTB DMA. **HIGH** for that hardware; not a generic panic.

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

Record:
- **Benefit:** HIGH for PCI1008+IOMMU users (device works correctly under IOMMU). Classic device-ID/quirk enablement.
- **Risk:** VERY LOW (1 line, existing macro, match is device-specific).
- **Ratio:** strongly favors backporting.

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

**Step 9.1: COMPILE THE EVIDENCE**

FOR:
- PCI ID / hardware quirk on an existing table (stable exception).
- Real IOMMU DMA misdirection without the alias.
- 1 line, obviously correct, same pattern as PCI1001–1006.
- Prerequisite table exists in this 7.3 tree.
- Author is switchtec maintainer; PCI maintainer applied it.
- Standalone; no API change.

AGAINST:
- No Reported-by / production crash log (typical for ID additions).
- Audience is PCI1008 NTB + IOMMU, not all machines.
- Unrelated pre-existing ep_map pointer issue in the quirk function (not caused by this line).
- Stable@ discussion could not be fetched (403).

UNRESOLVED:
- Whether stable@ discussed this after merge (lore.kernel.org/stable 403).
- Whether Logan later sent an ep_map fix (explicitly out of scope).

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

1. Obviously correct and tested? **PASS** — one-line ID, applied by PCI maintainer after list review.
2. Fixes a real bug that affects users? **PASS** — PCI1008 NTB DMA under IOMMU is wrong without the alias.
3. Important issue? **PASS** — IOMMU DMA correctness (faults / misdirected DMA), HIGH for that hardware.
4. Small and contained? **PASS** — +1 line in drivers/pci/quirks.c.
5. No new features or APIs? **PASS** — device ID on an existing quirk; allowed exception.
6. Can apply to the local tree? **PASS** — SWITCHTEC_PCI100X_QUIRK is present; apply is clean.

**Step 9.3: CHECK FOR EXCEPTION CATEGORIES**

Record: **Device ID addition** and **hardware quirk/workaround** (PCI DMA alias quirk). These are listed as YES for stable.

**Step 9.4: MAKE YOUR DECISION**

This tree has the PCI100X quirk table. Adding PCI1008 is the same class of change already used for PCI1001–1006. Without it, PCI1008 NTB DMA can be misdirected under an IOMMU. The patch is one line, applies cleanly, and does not need the rest of the series.

Verification:
- [Phase 1] git describe HEAD → v7.3-rc4-27-gf0100363d8c37; make kernelversion → 7.3.0-rc4. Tags: SOB Logan + Bjorn; Link to patch 3/3; no Fixes/stable/Reported-by.
- [Phase 2] git show 00a479ba1d012: +1 line SWITCHTEC_PCI100X_QUIRK(0x1008) in drivers/pci/quirks.c.
- [Phase 2] Read quirk_switchtec_ntb_dma_alias(): enable, iomap, read proxy IDs, pci_add_dma_alias(), table_sz 0/512 guards.
- [Phase 3] git blame -L 6087,6096: table from a3282f84b2151 (v6.14); 0x1008 from this commit.
- [Phase 3] git merge-base --is-ancestor a3282f84b2151 v6.14 true; not ancestor of v6.13. Original quirk ad281ecf1c7d4 (2018) is in HEAD.
- [Phase 3] git merge-base --is-ancestor 00a479ba1d012 v7.2 false; ancestor of v7.3-rc1/rc4.
- [Phase 3] Series patches 8b326de3cc02c, 0d8a6306c680e are sibling ID adds, not prerequisites of this quirk.
- [Phase 4] b4 dig -c 00a479ba1d012 / -a / -w / -m: v1-only 3-patch series; Bjorn applied for v7.3; Vinod acked 1/3; no NAK; Sashiko ep_map note treated as unrelated.
- [Phase 4] lore.kernel.org HTTP 403/Anubis; thread recovered via b4 mbox. stable@ search 403 — UNVERIFIED.
- [Phase 5] No C callers; DECLARE_PCI_FIXUP_CLASS_FINAL in include/linux/pci.h; pci_add_dma_alias in drivers/pci/pci.c.
- [Phase 6] Local quirks.c has PCI100X table and (in this checkout) the 0x1008 line. Companion IDs exist in switchtec.c:1877 and switchtec_dma.c:1426.
- [Phase 7] PCI subsystem maintainer Bjorn Helgaas; Logan maintains SWITCHTEC DMA.
- [Phase 8] Failure mode: IOMMU DMA misdirection for PCI1008 NTB — HIGH for that hardware; patch risk very low.

The change is a one-line PCI quirk ID. That is the standard stable exception, it is obviously correct, and this tree already has the table it extends.

**YES**

 drivers/pci/quirks.c | 1 +
 1 file changed, 1 insertion(+)
drivers/pci/quirks.c +1 -0
index e8067ff59e2a5..e03a3831bcc00 100644
@@ -6045,6 +6045,7 @@ SWITCHTEC_PCI100X_QUIRK(0x1003);  /* PCI1003XG4 */
 SWITCHTEC_PCI100X_QUIRK(0x1004);  /* PCI1004XG4 */
 SWITCHTEC_PCI100X_QUIRK(0x1005);  /* PCI1005XG4 */
 SWITCHTEC_PCI100X_QUIRK(0x1006);  /* PCI1006XG4 */
+SWITCHTEC_PCI100X_QUIRK(0x1008);  /* PCI1008XG4 */
 
 
 /*
Signature · 1 line
2.53.0
#54 lore raw

Re: [PATCH AUTOSEL 6.18-6.1] PCI: switchtec: Add Microchip PCI1008 to NTB DMA alias quirk

Sashiko has reviewed this patch and found no issues.
Quoted 9 lines

From: Logan Gunthorpe <[email protected]>

[ Upstream commit 00a479ba1d01249d43ca5e453380d1ed60946f8a ]

Add the PCI1008 device ID to the quirk_switchtec_ntb_dma_alias PCI fixup table. Without it, DMA transactions from a PCI1008 switch's NTB function are not given the correct requester ID alias, which can misdirect them under an IOMMU.

Quoted 4 lines

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author maintainer
#55 lore raw

PATCH 1/1 net: stmmac: fix device node reference leaks in stmmac_mtl_setup()

In reply to Sasha Levin

From: Md Rabbani <[email protected]>

[ Upstream commit 317fe168f4c0fc30e5c375c22d9c8911940aea9b ]

In stmmac_mtl_setup(), q_node is shared across the RX and TX queue parsing loops. When the RX queue loop breaks early because the number of parsed queues reaches plat->rx_queues_to_use, q_node retains an acquired reference count. If the error check passes
(queue == plat->rx_queues_to_use), execution proceeds directly to the TX queue loop, where of_get_next_child() immediately overwrites q_node with the first TX child, permanently leaking the retained RX child device node reference.

Switch both loops to for_each_child_of_node_scoped() so child node references are automatically dropped upon loop exit or early break, and remove the now-unnecessary function-scoped q_node variable and its manual of_node_put() at the exit label.

---

LLM Generated explanations, may be completely bogus:

The leak is real in this 6.12 tree: stmmac_mtl_setup() can drop an OF child reference when RX queue parsing breaks early, and in-tree DTs actually hit that path.

## PHASE 1: COMMIT MESSAGE FORENSICS

**Step 1.1: PARSE THE SUBJECT LINE**
- Record: [net: stmmac:] [fix] [OF device-node reference leaks in stmmac_mtl_setup()]

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**
- Record:
- Signed-off-by: Md Rabbani <[email protected]> (author)
- `Link:

    https://patch.msgid.link/[email protected]`
  - `Signed-off-by: Jakub Kicinski <[email protected]>` (netdev
    maintainer; applied to `netdev/net`)
  - No `Fixes:`, `Reported-by:`, `Tested-by:`, `Reviewed-by:`, `Acked-
    by:`, or `Cc: stable` (absence of Fixes/Cc-stable is expected for
    this review)
  - Upstream SHA (from patchwork bot):
    `317fe168f4c0fc30e5c375c22d9c8911940aea9b`

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**
- Record: [Bug] Shared q_node is used by both RX and TX for_each_child_of_node() loops. An early break in the RX loop leaves q_node holding a live OF reference. If queue == plat->rx_queues_to_use, the function continues into the TX loop, which calls of_get_next_child(tx_node, NULL) and overwrites q_node without putting the RX child.
- [Symptom] Permanent device_node refcount leak (kobject/device_node never released).
- [Version info] None in the message. The loops date to 2017 (d976a525c37127, v4.12-rc1).
- [Root cause] Early-break + reused iterator; of_get_next_child(parent, NULL) does not drop the previous pointer.

**Step 1.4: DETECT HIDDEN BUG FIXES**
- Record: Not hidden. Subject/body explicitly describe a refcount leak. The _scoped conversion is the fix mechanism, not a style-only cleanup.

## PHASE 2: DIFF ANALYSIS

**Step 2.1: INVENTORY THE CHANGES**
- Record: Single file drivers/net/ethernet/stmicro/stmmac/stmmac_platform.c. Actual commit is **+2 / -4**. Functions: stmmac_mtl_setup() only. Surgical, single-file.

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**
- Record:
- RX loop: for_each_child_of_node(rx_node, q_node) → for_each_child_of_node_scoped(...). Early break now auto-drops the current child via __free(device_node).
- TX loop: same conversion.
- Function-scope struct device_node *q_node removed; of_node_put(q_node) at out: removed (would not compile with the loop-scoped iterator).
- Probe/DT parse path only; no datapath change.

**Step 2.3: IDENTIFY THE BUG MECHANISM**
- Record: [Category] Reference counting / resource leak.
- [Mechanism] for_each_child_of_node is of_get_next_child(), which gets next and puts prev. break skips the put of the current node. Reusing the same pointer in the TX loop with prev=NULL leaks that RX child. TX extra children were previously dropped by the trailing of_node_put(q_node); RX extra children were not.

**Step 2.4: ASSESS THE FIX QUALITY**
- Record: Obviously correct. for_each_child_of_node_scoped exists in this tree and is already used widely. __free(device_node) is if (_T) of_node_put(_T), so NULL at loop end is safe. Regression risk is very low: no locking, no ABI, no behavior change besides dropping the leaked ref. The _scoped form is stronger than a one-off of_node_put() before the TX loop because it also covers TX early- break without a manual put.

## PHASE 3: GIT HISTORY INVESTIGATION

**Step 3.1: BLAME THE CHANGED LINES**
- Record: Buggy loops introduced by d976a525c37127 ("net: stmmac:
multiple queues dt configuration", Joao Pinto, 2017-03-10), first in **v4.12-rc1**. Present for many years. goto out / extra of_node_put(q_node) added by 2ee2132ffb83e (2018), which still leaves the RX-then-TX overwrite leak.

**Step 3.2: FOLLOW THE FIXES: TAG**
- Record: No Fixes: tag. Introducer is d976a525c37127, and git merge-base --is-ancestor d976a525c37127 HEAD succeeds. That code is in this tree.

**Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES**
- Record: Recent stmmac_platform.c work is unrelated (bus_id, probe error path, IRQ). Historical OF leak fixes in this driver:
a249708bc2aa1, d2ed0a7755fe1, 4613b279bee79. Standalone [PATCH], not X/Y.

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**
- Record: git log --author="Md Rabbani" on this path is empty in this tree (new contributor). Applied by Jakub Kicinski to netdev/net.git (fixes tree), which is a strong maintainer signal.

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS**
- Record: Depends on for_each_child_of_node_scoped / DEFINE_FREE(device_node) (34af4554fb0ce1 / 9448e55d032d99, 2024-02-25). Both are already in this 6.12 tree (git merge-base --is- ancestor succeeded). Can apply standalone. stmmac_platform.c already includes <linux/of.h>, which includes <linux/cleanup.h>.

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**
- Record: b4 dig -c <sha> cannot match because 317fe168f4c0 is not an ancestor of HEAD. Used msgid instead. Lore thread: https://lore.ke rnel.org/netdev/[email protected]/
- Series: single v1 [PATCH] (2 messages: submission + patchwork-bot). Applied to netdev/net.git (main) as https://git.kernel.org/netdev/net/c/317fe168f4c0. No v2, no NAK.

**Step 4.2: CHECK WHO REVIEWED THE PATCH**
- Record: To/Cc included STMMAC maintainers (Torgue, Coquelin, Chevallier), netdev maintainers (Miller, Dumazet, Kicinski, Abeni), netdev@, linux-stm32@, linux-arm-kernel@. No written review comments; Kicinski applied it to the **net fixes** tree.

**Step 4.3: SEARCH FOR THE BUG REPORT**
- Record: No syzbot/bugzilla. Bug is from code inspection. Real in-tree DTs trigger it (see Phase 6/8).

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**
- Record: Standalone. No other patches required.

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**
- Record: lore.kernel.org/stable search for stmmac_mtl_setup shows older stmmac stable backports (probe error-path, MDIO, Tx COE), not this leak. No prior rejection of this fix.

## PHASE 5: CODE SEMANTIC ANALYSIS

**Step 5.1: KEY FUNCTIONS**
- Record: stmmac_mtl_setup() (modified). Helpers:
for_each_child_of_node_scoped, of_get_next_child / __of_get_next_child, of_node_put.

**Step 5.2: TRACE CALLERS**
- Record: Only caller is stmmac_probe_config_dt() in the same file (line 603). That is used via devm_stmmac_probe_config_dt() from many glue drivers: dwmac-rk, dwmac-qcom-ethqos, dwmac-imx, dwmac- stm32, dwmac-sun8i, dwmac-mediatek, dwmac-generic, and others. Probe/init context, not IRQ/hot path.

**Step 5.3: TRACE CALLEES**
- Record: of_parse_phandle, of_property_read_*, of_get_next_child, of_node_put. DT parse only.

**Step 5.4: FOLLOW THE CALL CHAIN**
- Record: Userspace cannot trigger it directly. It runs on every DT- based stmmac probe. Reachable on common ARM/ARM64 SoCs (Rockchip, i.MX, STM32, Qualcomm, MediaTek). Leak fires when the RX config node has more children than snps,rx-queues-to-use.

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**
- Record: Same file still has for_each_child_of_node(np, mdio_node) in stmmac_of_get_mdio() (line 324); not the same shared-iterator bug. In-tree DTs with extra RX children:
arch/arm64/boot/dts/qcom/sa8540p-ride.dts uses snps,rx-queues-to- use = <1> with queue0–queue3 on both ethernet0 and ethernet1.

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

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?**
- Record: Yes. This tree is **6.12.111** (pending-6.12, p-6.12-3-gc504cf0baa3d8). Current code at stmmac_platform.c:177 / :240 still uses unscoped loops and of_node_put(q_node) at :293. 317fe168f4c0 is **not** an ancestor of HEAD. Bug present since v4.12.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**
- Record: Expected difficulty: **minor context conflicts**. Upstream context has later stmmac_axi_blen_to_mask / MTL_MAX_* clamping that 6.12 does not have. The three functional edits (two loop macros, drop q_node + trailing put) match 6.12 1:1. Needs a small context- adjusted backport, not a rewrite.

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**
- Record: No commit with this subject in this tree. Older stmmac of_node_put fixes do not cover this iterator reuse.

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

**Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY**
- Record: [Subsystem] drivers/net/ethernet/stmicro/stmmac (Synopsys DWMAC). [Criticality] **IMPORTANT** — common platform Ethernet on many SoCs, not core mm/VFS, not staging.

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**
- Record: Actively maintained (many recent stmmac fixes on this branch). The leak itself is old (2017), not a new-feature bug.

## PHASE 8: IMPACT AND RISK ASSESSMENT

**Step 8.1: DETERMINE WHO IS AFFECTED**
- Record: Driver/config-specific: CONFIG_STMMAC_ETH + CONFIG_STMMAC_PLATFORM + DT snps,mtl-rx-config with extra child nodes. Confirmed affected in-tree board: Qualcomm SA8540P Ride (sa8540p-ride.dts). Many other boards have matching child counts and do not leak.

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**
- Record: Device probe (and every unbind/rebind). Common on boards whose DT lists more queue children than snps,rx-queues-to-use. Not a userspace syscall; not a race. Extra TX children were already put at out:; extra RX children leak.

**Step 8.3: DETERMINE THE FAILURE MODE SEVERITY**
- Record: [Failure] One device_node ref leak per probe when extra RX children exist. [Severity] **MEDIUM** — not oops/deadlock/corruption, but a real lifetime leak of an OF kobject. Repeatable on module reload. Can pin overlay/node teardown.

**Step 8.4: CALCULATE RISK-BENEFIT RATIO**
- Record: Benefit: medium (fixes a real, DT-triggered leak on a widely used NIC driver, including an in-tree Qualcomm board). Risk: **very low** (2 insertions / 4 deletions, existing helper, probe-only). Ratio favors backport.

## PHASE 9: FINAL SYNTHESIS

**Step 9.1: COMPILE THE EVIDENCE**

FOR:
- Real OF refcount leak, mechanism verified against of_get_next_child() / __of_get_next_child().
- Buggy code is in this 6.12 tree and has been since v4.12.
- In-tree DT sa8540p-ride.dts has 4 RX queue children with rx-queues- to-use = <1> — the leak path is not theoretical.
- Tiny, obviously correct fix; helper already in 6.12.
- Applied to netdev/net (fixes) by Kicinski.
- Same class of bug as prior stmmac of_node_put fixes already in history.
- No new API/feature; no series dependency.

AGAINST:
- Probe-time leak of a single node, not a crash/UAF/security issue.
- Surrounding file context differs slightly from mainline, so git am of the raw mainline diff may need a trivial refresh.
- No user crash report / syzbot.

UNRESOLVED:
- No written mailing-list review beyond maintainer application (v1 accepted as-is).

**Step 9.2: APPLY THE STABLE RULES CHECKLIST**
1. Obviously correct and tested? **PASS** — scoped put on break/exit is the intended helper; applied to netdev/net.
2. Fixes a real bug that affects users? **PASS** — leak on probe; triggered by in-tree Qualcomm DT.
3. Important issue? **PASS** at medium importance — resource leak, not panic, but a genuine lifetime bug in a common Ethernet driver.
4. Small and contained? **PASS** — +2/-4, one function.
5. No new features or APIs? **PASS**
6. Can apply to the local tree? **PASS** — same loops exist; scoped macro exists; minor context tweak only.

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

**Step 9.4: DECISION**
Backport to this 6.12 tree. The bug exists here, the helper exists here, the fix is surgical, and at least one in-tree board hits it.

---

### What the commit solves and why it matters here stmmac_mtl_setup() parses snps,mtl-rx-config / snps,mtl-tx-config at probe. The RX iterator breaks once queue >= plat->rx_queues_to_use, leaving q_node referenced. The TX loop then starts with of_get_next_child(tx_node, NULL), which never puts that RX child. That is a permanent OF node leak. arch/arm64/boot/dts/qcom/sa8540p-ride.dts is written exactly that way (1 queue in use, 4 queue child nodes).

### Stable rules / risk
Meets the rules: small, obviously correct, no new API, real leak, helper already in 6.12. Risk is a possible trivial context conflict around later mainline-only stmmac_platform.c edits; the functional change does not depend on those.

### Verification
- [Phase 1] Parsed tags: author SOB, msgid Link, Kicinski SOB; no Fixes/Reported-by; upstream 317fe168f4c0
- [Phase 2] Diff: +2/-4 in stmmac_mtl_setup(); two loops to _scoped; drop q_node + of_node_put(q_node)
- [Phase 2] __of_get_next_child() does of_node_get(next); of_node_put(prev) (drivers/of/base.c:600-603); prev=NULL does not put the overwritten pointer
- [Phase 3] Blame: loops from d976a525c37127 (v4.12-rc1); ancestor of HEAD
- [Phase 3] 34af4554fb0ce1 / DEFINE_FREE(device_node) are ancestors of HEAD
- [Phase 3] git merge-base --is-ancestor 317fe168f4c0 HEAD failed (fix not in this tree)
- [Phase 4] b4 mbox msgid: 2-message thread; applied to netdev/net; no NAK
- [Phase 4] stable lore search: no discussion of this leak
- [Phase 5] Caller: stmmac_probe_config_dt() → many dwmac-* platform probes
- [Phase 6] git describe HEAD / make kernelversion: 6.12.111 pending-6.12; buggy loops still present at lines 177 and 240
- [Phase 6] sa8540p-ride.dts ethernet0_mtl_rx_setup / ethernet1_mtl_rx_setup: rx-queues-to-use = <1> with queue0–queue3
- [Phase 8] Failure mode: OF device_node leak at probe, severity MEDIUM
- UNVERIFIED: Could not use b4 dig -c against HEAD (commit not in this checkout); lore HTML fetch returned 403, raw/mbox succeeded

**YES**

 drivers/net/ethernet/stmicro/stmmac/stmmac_platform.c | 6 ++----
 1 file changed, 2 insertions(+), 4 deletions(-)
drivers/net/ethernet/stmicro/stmmac/stmmac_platform.c +2 -4
index 0cb51935c4056..ceb913a3a6c69 100644
@@ -131,7 +131,6 @@ static struct stmmac_axi *stmmac_axi_setup(struct platform_device *pdev)
 static int stmmac_mtl_setup(struct platform_device *pdev,
 			    struct plat_stmmacenet_data *plat)
 {
-	struct device_node *q_node;
 	struct device_node *rx_node;
 	struct device_node *tx_node;
 	u8 queue = 0;
@@ -174,7 +173,7 @@ static int stmmac_mtl_setup(struct platform_device *pdev,
 		plat->rx_sched_algorithm = MTL_RX_ALGORITHM_SP;
 
 	/* Processing individual RX queue config */
-	for_each_child_of_node(rx_node, q_node) {
+	for_each_child_of_node_scoped(rx_node, q_node) {
 		if (queue >= plat->rx_queues_to_use)
 			break;
 
@@ -237,7 +236,7 @@ static int stmmac_mtl_setup(struct platform_device *pdev,
 	queue = 0;
 
 	/* Processing individual TX queue config */
-	for_each_child_of_node(tx_node, q_node) {
+	for_each_child_of_node_scoped(tx_node, q_node) {
 		if (queue >= plat->tx_queues_to_use)
 			break;
 
@@ -290,7 +289,6 @@ static int stmmac_mtl_setup(struct platform_device *pdev,
 out:
 	of_node_put(rx_node);
 	of_node_put(tx_node);
-	of_node_put(q_node);
 
 	return ret;
 }
Signature · 1 line
2.53.0
author maintainer
#56 lore raw

PATCH 1/1 drm/amdgpu: Validate ATPX buffer length before use

In reply to Sasha Levin

From: Lijo Lazar <[email protected]>

[ Upstream commit 916867cd75dbbc383aa6cb724556de769912157a ]

Add amdgpu_atpx_buffer_validate() to check that the returned ACPI buffer is of type ACPI_TYPE_BUFFER, is large enough to hold the u16 size field, and that the BIOS-reported size does not exceed the actual allocation length or fall below the minimum required by the caller. Use it in VERIFY_INTERFACE and GET_PX_PARAMETERS callers.

Assisted-by Claude Sonnet (Cursor AI)

---

LLM Generated explanations, may be completely bogus:

I have enough to decide: the 6.18.y tree still has the unvalidated ATPX ACPI path, and the patch is a small, self-contained memory-safety fix.

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

**Step 1.1: PARSE THE SUBJECT LINE**

Record: [drm/amdgpu] [Validate] [Check ACPI ATPX response buffer type and length before reading the BIOS-reported size and memcpy]

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

Record:
- Signed-off-by: Lijo Lazar <[email protected]> (author)
- Assisted-by: Claude Sonnet (Cursor AI)
- Acked-by: Alex Deucher <[email protected]> (amdgpu maintainer)
- Signed-off-by: Alex Deucher <[email protected]>
- (pipeline) Signed-off-by: Sasha Levin — ignored per instructions
- (pipeline) [ Upstream commit 916867cd75dbbc383aa6cb724556de769912157a ] — ignored per instructions
- No Fixes:, Reported-by:, Tested-by:, Link:, or Cc: stable (absence expected)

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

Record:
- Bug: ATPX ACPI responses are used without checking object type, that the allocation is large enough to hold the leading u16 size field, or that the BIOS-reported size is within the real ACPI buffer.
- Symptom/failure mode: out-of-bounds read and/or NULL dereference when firmware returns a short buffer, a claimed size larger than buffer.length, or a non-buffer object.
- Version information: none in the message. History shows the pattern dates to the original amdgpu ATPX code (2015).
- Root cause: callers did size = *(u16 *)info->buffer.pointer then memcpy(..., min(sizeof(output), size)) with only a minimum-size check on the BIOS-reported value, never on ACPI type/buffer.length.

**Step 1.4: DETECT HIDDEN BUG FIXES**

Record: Not hidden. The subject and body describe a memory-safety validation fix. It is not cleanup or a feature.

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

**Step 2.1: INVENTORY THE CHANGES**

Record:
- File: drivers/gpu/drm/amd/amdgpu/amdgpu_atpx_handler.c (+21 / −12)
- Functions: new amdgpu_atpx_buffer_validate(); modified amdgpu_atpx_validate(), amdgpu_atpx_verify_interface()
- Scope: single-file surgical fix

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

Record:
- Hunk 1: add helper that requires non-NULL object, ACPI_TYPE_BUFFER, buffer.length >= 2, buffer.length >= claimed u16 size, and claimed size >= min_size. && short-circuit makes the u16 load safe.
- Hunk 2 (amdgpu_atpx_validate / GET_PX_PARAMETERS): old path zeroed output, loaded claimed size, rejected only size < 10, then memcpy of min(sizeof(output), size). New path validates first, then the same bounded copy. sizeof(struct atpx_px_params) is 10 (u16+u32+u32, packed), so the minimum is unchanged for valid firmware.
- Hunk 3 (amdgpu_atpx_verify_interface): same, replacing hardcoded size < 8 with sizeof(struct atpx_verify_interface) which is also 8.

**Step 2.3: IDENTIFY THE BUG MECHANISM**

Record:
- Category: memory safety — OOB read and possible NULL deref on firmware-controlled ACPI data
- Mechanism:
1. No type check. union acpi_object overlays integer and buffer. An INTEGER 0 makes buffer.length 0 and buffer.pointer NULL → *(u16 *)NULL oops.
2. No buffer.length >= sizeof(u16) check → OOB 2-byte read on empty/short buffers.
3. memcpy used BIOS size capped only by sizeof(output), not by buffer.length. Example: length=4, claimed size=10 → copy 10 bytes from a 4-byte buffer.

**Step 2.4: ASSESS THE FIX QUALITY**

Record:
- Obviously correct; check order is right; min sizes match the old hardcoded 8/10.
- Minimal; no API change.
- Regression risk is low: it only rejects responses that were already type-confused or out of bounds. A BIOS that “worked” only because memcpy read extra heap bytes was already relying on undefined behavior.

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

**Step 3.1: BLAME THE CHANGED LINES**

Record: Buggy loads/memcpy introduced in d38ceaf99ed015 (“drm/amdgpu:
add core driver (v4)”, 2015-06-03), first in v4.2-rc1. Present for the entire life of amdgpu ATPX. printk→pr_err only in 07867a78f88465 (2023).

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

Record: No Fixes: tag (expected). Introducing commit is in this tree (git merge-base --is-ancestor d38ceaf99ed015 HEAD succeeded).

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

Record: Sibling series patch 1/2 is c8373721c3e54 “Validate ATIF buffer length before use” on amdgpu_acpi.c. Independent file. Other recent ATPX commits are unused-function removal and printk conversion, not prerequisites. Standalone.

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

Record: Lijo Lazar is a regular AMD contributor (bounds checks, reset, ACPI). Maintainer Acked-by/SOB from Alex Deucher.

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

Record: Submitted as PATCH 2/2 with ATIF 1/2. No shared symbols or types. ATPX applies alone. radeon still has the old pattern in radeon_atpx_handler.c; that is out of scope, not a dependency.

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

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

Record:
- b4 dig -c 916867cd75db... and local SHA: lore.kernel.org returned errors; no b4 match.
- Fallback: https://www.mail-archive.com/amd-
[email protected]/msg145005.html (PATCH 2/2, 2026-06-14)
- Review: https://www.mail-archive.com/amd-
[email protected]/msg145042.html — Alex Deucher: “Series is:
Acked-by”
- Series: v1 only; no v2/v3; no NAK; no reviewer Cc: stable
- Freedesktop June 2026 index lists the submission and Deucher’s ack only

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

Record: Maintainer Alex Deucher acked the series. Recipients from mail-
archive: amd-gfx. b4 -w failed (lore error).

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

Record: No Reported-by, syzbot, bugzilla, or CVE found. Code-review hardening against malformed ACPI, not a user reproducer.

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

Record: 1/2 ATIF (amdgpu_acpi.c) is the same class of fix. ATIF already had obj->type != ACPI_TYPE_BUFFER; ATPX amdgpu_atpx_call() never checked type. ATPX does not need 1/2.

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

Record: lore.kernel.org/stable search returned 403. Web search did not show a prior stable discussion of this subject. UNVERIFIED whether anyone already requested or rejected it for stable.

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

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

Record: amdgpu_atpx_buffer_validate (new), amdgpu_atpx_validate, amdgpu_atpx_verify_interface

**Step 5.2: TRACE CALLERS**

Record:
- amdgpu_atpx_verify_interface / amdgpu_atpx_validate ← amdgpu_atpx_init() ← amdgpu_atpx_detect() when ATPX exists and there are two VGA-class devices ← amdgpu_register_atpx_handler() ← amdgpu_init() in amdgpu_drv.c (module init)
- Gated by CONFIG_VGA_SWITCHEROO (x86 + ACPI + PCI hybrid-laptop GPU switching)

**Step 5.3: TRACE CALLEES**

Record: amdgpu_atpx_call() → acpi_evaluate_object(..., ACPI_ALLOCATE_BUFFER). On failure other than AE_NOT_FOUND it frees and returns NULL. Success and AE_NOT_FOUND return buffer.pointer with **no type check**. Callers only test if (!info).

**Step 5.4: FOLLOW THE CALL CHAIN**

Record: Reachable on amdgpu module load on hybrid PX laptops. Not a syscall hot path; it is a common boot/probe path for those machines. Unprivileged users do not trigger it directly; a crash still takes down the GPU/driver init (and can oops the kernel).

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**

Record: Identical unvalidated pattern remains in drivers/gpu/drm/radeon/radeon_atpx_handler.c. ATIF now validates type and both sizes. Confirms a systematic ACPI-buffer issue; this patch covers amdgpu ATPX only.

===============================================================
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 = v6.18.53-5049-g0f0bdc2b0dffb; Makefile 6.18.53; branch autosel
- Candidate is **not** in v6.18.53 (merge-base --is-ancestor failed)
- v6.18.53:drivers/gpu/drm/amd/amdgpu/amdgpu_atpx_handler.c still has size = *(u16 *) info->buffer.pointer / size < 10 / size < 8
- git diff v6.18.53 9d367fab451d9^ -- amdgpu_atpx_handler.c is empty:
pre-fix file matches 6.18.53
- Bug introduced v4.2; present in this series

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**

Record: Clean apply. Same file content as the commit’s parent. No refactor since 6.18.53 on these functions.

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

Record: No earlier ATPX buffer-length fix in this file’s history besides the candidate. ATIF sibling is also not in v6.18.53; not required.

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

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

Record: [drm/amdgpu ATPX / vga_switcheroo] [IMPORTANT — common x86 hybrid AMD laptop path, not core mm/vfs, not staging]

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**

Record: amdgpu is actively developed; this ATPX file is mature (2015) with occasional quirks. Long-lived bug, not a recent-feature regression.

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

**Step 8.1: DETERMINE WHO IS AFFECTED**

Record: Driver-specific + config-specific: CONFIG_VGA_SWITCHEROO amdgpu users on hybrid PX systems (two GPUs, ATPX ACPI method). Typical of 2008–2010s and some later A+A laptops. Distro kernels usually enable VGA_SWITCHEROO on x86.

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**

Record: Module init / ATPX detect. Needs ATPX plus a malformed ACPI return (wrong type, length < 2, or claimed size > actual). No evidence an unprivileged user can inject ACPI here; buggy/malicious firmware can. No public reproducer. Severity if it hits is a boot-time oops, not a rare runtime race.

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

Record: NULL deref or OOB read during GPU/hybrid init → kernel oops. Severity HIGH (crash). Not confirmed privilege escalation. Not data corruption.

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

Record:
- Benefit: medium-high for hybrid AMD laptops; prevents oops on bad ATPX data; completes validation the driver already attempted.
- Risk: very low (one helper, two call sites, min sizes unchanged).
- Ratio: favorable.

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

**Step 9.1: COMPILE THE EVIDENCE**

FOR:
- Real OOB read / possible NULL deref on ACPI ATPX responses
- Incomplete size check since 2015, present in 6.18.53
- Small, obviously correct, maintainer-acked
- Applies cleanly; no new API; no series dependency
- Boot path on hybrid laptops, not dead code

AGAINST:
- No user/syzbot report
- Trigger needs bad firmware
- ATPX is a shrinking hybrid-laptop population
- Same bug still in radeon (unrelated)

UNRESOLVED:
- b4/lore 403; no stable-list discussion confirmed
- No known machine that actually returns a short/wrong-type ATPX object

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

1. Obviously correct and tested? **PASS** — helper logic is sound; Acked-by amdgpu maintainer
2. Fixes a real bug that affects users? **PASS** — missing type/length checks; crash if firmware is wrong
3. Important issue? **PASS** — oops/OOB, HIGH; not a feature
4. Small and contained? **PASS** — +21/−12, one file
5. No new features or APIs? **PASS**
6. Can apply to the local tree? **PASS** — v6.18.53 has the buggy code; diff would apply cleanly

**Step 9.3: CHECK FOR EXCEPTION CATEGORIES**

Record: Not a device-ID/quirk/DT/build/docs exception. Standard memory- safety bug fix.

**Step 9.4: MAKE YOUR DECISION**

This belongs on 6.18.y. The tree still trusts BIOS-reported ATPX sizes without checking ACPI object type or real buffer length. That can oops at amdgpu init on hybrid systems. The fix is tiny, matches existing mins, and was acked by the maintainer.

### What the commit solves for this tree

On v6.18.53, amdgpu_atpx_verify_interface() and GET_PX_PARAMETERS still do *(u16 *)info->buffer.pointer and memcpy without confirming ACPI_TYPE_BUFFER or that buffer.length covers the claimed size. Wrong-type INTEGER 0 is a NULL deref; a short buffer or oversized claimed length is an OOB read. Stable 6.18 users of hybrid AMD laptops hit this on module load if firmware is buggy.

### Risk vs benefit

Benefit is avoiding a probe-time oops. Risk is a few lines of stricter validation that valid ATPX responses already satisfy (sizeof 8 and 10). Sibling ATIF patch is not required.

### Concerns

No field report. radeon is still unfixed. Neither blocks backporting this amdgpu change.

Verification:
- [Phase 1] Tags: author SOB, Assisted-by Claude, Acked-by/SOB Alex Deucher; no Fixes/Reported-by/Cc stable
- [Phase 2] Diff: +21/−12 in one file; helper plus two call sites; min 8/10 preserved via sizeof
- [Phase 2] union acpi_object in include/acpi/actypes.h: INTEGER vs BUFFER overlay confirmed
- [Phase 3] blame: d38ceaf99ed015 (v4.2-rc1); in this tree
- [Phase 3] parent is ATIF 1/2 on a different file; ATPX standalone
- [Phase 4] b4 dig failed (lore error); mail-archive PATCH 2/2 + Deucher series ack
- [Phase 4] No stable-list hit (lore 403) — UNVERIFIED
- [Phase 5] Call chain: amdgpu_init → register_atpx_handler → detect → init → verify/validate; CONFIG_VGA_SWITCHEROO
- [Phase 5] amdgpu_atpx_call has no type check (unlike ATIF)
- [Phase 5] Same bug still in radeon_atpx_handler.c
- [Phase 6] git describe HEAD: v6.18.53-5049; candidate not in v6.18.53; buggy code present; empty diff vs parent file
- [Phase 8] Failure mode: oops/OOB on ATPX probe, HIGH; trigger = hybrid PX + bad ACPI
- UNVERIFIED: no concrete BIOS reproducer; no CVE

**YES**

 .../gpu/drm/amd/amdgpu/amdgpu_atpx_handler.c  | 33 ++++++++++++-------
 1 file changed, 21 insertions(+), 12 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_atpx_handler.c +21 -12
index 3893e6fc2f037..e2a4644896ca8 100644
@@ -89,6 +89,15 @@ bool amdgpu_is_atpx_hybrid(void)
 	return amdgpu_atpx_priv.atpx.is_hybrid;
 }
 
+static bool amdgpu_atpx_buffer_validate(const union acpi_object *obj,
+					size_t min_size)
+{
+	return obj && obj->type == ACPI_TYPE_BUFFER &&
+	       obj->buffer.length >= sizeof(u16) &&
+	       obj->buffer.length >= *(u16 *)obj->buffer.pointer &&
+	       *(u16 *)obj->buffer.pointer >= min_size;
+}
+
 /**
  * amdgpu_atpx_call - call an ATPX method
  *
@@ -179,15 +188,15 @@ static int amdgpu_atpx_validate(struct amdgpu_atpx *atpx)
 		if (!info)
 			return -EIO;
 
-		memset(&output, 0, sizeof(output));
-
-		size = *(u16 *) info->buffer.pointer;
-		if (size < 10) {
-			pr_err("ATPX buffer is too small: %zu\n", size);
+		if (!amdgpu_atpx_buffer_validate(info, sizeof(output))) {
+			pr_err("Invalid ATPX GET_PX_PARAMETERS response\n");
 			kfree(info);
 			return -EINVAL;
 		}
-		size = min(sizeof(output), size);
+
+		memset(&output, 0, sizeof(output));
+
+		size = min(sizeof(output), (size_t)*(u16 *)info->buffer.pointer);
 
 		memcpy(&output, info->buffer.pointer, size);
 
@@ -258,15 +267,15 @@ static int amdgpu_atpx_verify_interface(struct amdgpu_atpx *atpx)
 	if (!info)
 		return -EIO;
 
-	memset(&output, 0, sizeof(output));
-
-	size = *(u16 *) info->buffer.pointer;
-	if (size < 8) {
-		pr_err("ATPX buffer is too small: %zu\n", size);
+	if (!amdgpu_atpx_buffer_validate(info, sizeof(output))) {
+		pr_err("Invalid ATPX VERIFY_INTERFACE response\n");
 		err = -EINVAL;
 		goto out;
 	}
-	size = min(sizeof(output), size);
+
+	memset(&output, 0, sizeof(output));
+
+	size = min(sizeof(output), (size_t)*(u16 *)info->buffer.pointer);
 
 	memcpy(&output, info->buffer.pointer, size);
 
Signature · 1 line
2.53.0
author maintainer
#57 lore raw

PATCH 1/1 remoteproc: core: Full attach detach during recovery

In reply to Sasha Levin

From: Tanmay Shah <[email protected]>

[ Upstream commit d93ffd549fb4df18c934ca7a47d4128a18c718cb ]

Current attach on recovery mechanism loads the clean resource table during recovery, but doesn't re-allocate the resources. RPMsg communication will fail after recovery due to this. Fix this incorrect behavior by doing the full detach and attach of remote processor during the recovery. This will load the clean resource table and re-allocate all the resources, which will set up correct vring information in the resource table.

---

LLM Generated explanations, may be completely bogus:

The local tree is **v7.3-rc4** (mainline). The buggy attach-on-recovery path exists here (since v6.1), and the change is a small, real recovery- path fix: after a remoteproc crash, RPMsg stays dead because vrings are not reallocated.

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

Step 1.1: PARSE THE SUBJECT LINE
Record: [remoteproc/core] [fix disguised as “Full attach detach”] [do a full detach+cleanup+attach on crash recovery so resources/vrings are reallocated]

Step 1.2: PARSE ALL COMMIT MESSAGE TAGS
Record:
- Signed-off-by: Tanmay Shah \<[email protected]\> (author)
- Link:
https://lore.kernel.org/r/[email protected]
- Signed-off-by: Mathieu Poirier \<[email protected]\> (remoteproc maintainer)
- No Fixes:, Reported-by, Tested-by, Reviewed-by, Acked-by, or Cc:
stable (absence of Fixes/Cc:stable is expected for this review)
- Message-ID numbering ...-2-... shows this is patch 1/2 of a series (cover is -1, xlnx crash detection is -3)

Step 1.3: ANALYZE THE COMMIT BODY TEXT
Record:
- Bug: attach-on-recovery loads a clean resource table but does **not** re-allocate resources.
- Symptom: **RPMsg communication fails after recovery**.
- Root cause: __rproc_attach() only prepares/attaches/starts subdevices; it does not call rproc_handle_resources() / rproc_alloc_registered_carveouts(), so vring addresses in the resource table stay invalid (0xffffffff after reset).
- Failure mode: IPC to the coprocessor remains broken until Linux is rebooted, even though recovery “succeeded”.
- Version info: none in the message. Feature dates to v6.1 (ba194232edc03).

Step 1.4: DETECT HIDDEN BUG FIXES
Record: This is an explicit functional bug fix, not a disguised cleanup. The extra teardown lines look like “cleanup” but they are the missing half of rproc_detach() so rproc_attach() can rebuild vrings.

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

Step 2.1: INVENTORY THE CHANGES
Record:
- File: drivers/remoteproc/remoteproc_core.c (+14 / -1)
- Function: rproc_attach_recovery() only
- Scope: single-file surgical fix

Step 2.2: UNDERSTAND THE CODE FLOW CHANGE
Record: Before: __rproc_detach() then __rproc_attach(). After:
__rproc_detach(), then the same teardown rproc_detach()/__rproc_shutdown() already use (rproc_resource_cleanup, rproc_unprepare_device, rproc_disable_iommu, free cached_table), then rproc_attach() which re-enables IOMMU, prepares the device, loads the resource table, handles resources, allocates carveouts, and calls __rproc_attach().

Step 2.3: IDENTIFY THE BUG MECHANISM
Record: [Logic / correctness] Incomplete recovery left virtio/RPMsg resources stale. Full resource teardown + rproc_attach() rebuilds vrings. Not UAF/leak/race/overflow.

Step 2.4: ASSESS THE FIX QUALITY
Record: Obviously correct: the new block is copied from rproc_detach() / __rproc_shutdown(). rproc_attach() is static in this file and does **not** take rproc->lock, so calling it from rproc_trigger_recovery() (which already holds the lock) is not a deadlock. Regression risk is low-medium: recovery now unregisters virtio devices and frees carveouts instead of only resetting subdevices; that is the intended repair. No API/data-structure change.

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

Step 3.1: BLAME THE CHANGED LINES
Record: Buggy rproc_attach_recovery() introduced in ba194232edc03 (“remoteproc: Support attach recovery after rproc crash”, Peng Fan, 2022-09-28). First appears in **v6.1-rc1**. Present in this tree (git merge-base --is-ancestor ba194232edc03 HEAD → yes).

Step 3.2: FOLLOW THE FIXES: TAG
Record: No Fixes: tag. The introducing commit is ba194232edc03 (verified by blame and git show). Enabled for hardware by 6eed169c7fefd (imx_rproc, i.MX8QM/QXP).

Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES
Record: Standalone core fix. Same-series follow-up 5ae3dc0788746 (“remoteproc: xlnx: Add crash detection mechanism”) is a **new xlnx feature** and is **not** required for this core change. Later core commits (026a3fada4326, crash/rproc_del races) do not revert or rewrite this recovery path. Earlier attach error-path leak fixes (7692c9fbedd90, bcd241230fdbc) already exist in this tree and make rproc_attach() safer on failure.

Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS
Record: Tanmay Shah is the AMD/Xilinx remoteproc contributor, not the subsystem maintainer. Maintainer Mathieu Poirier merged it. Related work is xlnx attach/detach and crash detection, not a pile of hidden core prerequisites.

Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS
Record: Needs rproc_attach(), rproc_resource_cleanup(), rproc_unprepare_device(), rproc_disable_iommu(), and rproc_attach_recovery() — all present here. Can apply standalone. Does **not** need series patch 2.

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

Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION
Record: b4 dig -c d93ffd549fb4d →
https://patch.msgid.link/[email protected]
Revisions: RFC (2025-10-02) → several v1–v4 shapes → v5 (2026-06-10) → **v6 applied** (2026-06-29).
RFC review (Mathieu Poirier): do not mix __rproc_detach with rproc_attach; resource-table reset already happens in detach. Author replied that __rproc_attach() never calls rproc_handle_resources() / rproc_alloc_registered_carveouts(), so vrings stay unset and RPMsg cannot start. v3 tried public rproc_detach()+rproc_boot() (lock/state mess). v5/v6 inlined rproc_detach()’s cleanup and called rproc_attach() (no extra lock). Mathieu applied v6 with “Applied.” No NAK on the committed version. No reviewer Cc:stable.

Step 4.2: CHECK WHO REVIEWED THE PATCH
Record: To/Cc: Bjorn Andersson, Mathieu Poirier, linux-remoteproc, linux-kernel. Maintainer applied it. No extra Reviewed-by.

Step 4.3: SEARCH FOR THE BUG REPORT
Record: No syzbot/bugzilla. Author hit it on AMD-Xilinx attach-on- recovery. Independent in-tree user: i.MX8QM/QXP (imx_rproc_partition_notify → rproc_report_crash() on partition reboot).

Step 4.4: CHECK FOR RELATED PATCHES AND SERIES
Record: v6 0/2 “remoteproc: xlnx: remote crash recovery”. Patch 2 adds xlnx crash reporting via resource table + mailbox. This patch is self- contained for existing RPROC_FEAT_ATTACH_ON_RECOVERY users.

Step 4.5: CHECK STABLE MAILING LIST HISTORY
Record: No stable-list discussion of this subject found. UNVERIFIED:
lore.kernel.org HTTP fetch returned 403; used b4 dig, mbox, and openwall instead.

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

Step 5.1: IDENTIFY KEY FUNCTIONS IN THE DIFF
Record: rproc_attach_recovery(); callees added:
rproc_resource_cleanup, rproc_unprepare_device, rproc_disable_iommu, rproc_attach.

Step 5.2: TRACE CALLERS
Record:
- rproc_attach_recovery() ← rproc_trigger_recovery() when RPROC_FEAT_ATTACH_ON_RECOVERY is set
- rproc_trigger_recovery() ← rproc_crash_handler_work() (automatic), sysfs recovery, debugfs recovery
- Feature set in imx_rproc.c (i.MX8QM/QXP, not Linux-owned core) and xlnx_r5_remoteproc.c (this series’ patch 2)

Step 5.3: TRACE CALLEES
Record: Teardown matches rproc_detach(). rproc_attach() does IOMMU, prepare, rproc_set_rsc_table, rproc_handle_resources, carveouts, __rproc_attach.

Step 5.4: FOLLOW THE CALL CHAIN
Record: Reachable from userspace (sysfs/debugfs) and from hardware (i.MX SCU reboot IRQ; xlnx mailbox crash report). Not a theoretical-only path.

Step 5.5: SEARCH FOR SIMILAR PATTERNS
Record: Boot recovery still uses rproc_stop() + rproc_start() and keeps existing allocations; attach recovery must rebuild host-side mappings because the remote rebooted itself. No sibling copy-paste bug.

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

Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?
Record: Yes. Tree is **Linux 7.3.0-rc4** (git describe HEAD → v7.3-rc4-27-gf0100363d8c37). rproc_attach_recovery() exists; bug introduced v6.1. Pre-image of this commit is __rproc_detach() + __rproc_attach().

Step 6.2: CHECK FOR BACKPORT COMPLICATIONS
Record: Clean apply on this tree: rproc_attach() is already a same- file static helper; teardown helpers exist. Expected difficulty: clean apply.

Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE
Record: No earlier equivalent fix. This commit is the fix. git merge- base --is-ancestor d93ffd549fb4d HEAD is true because this is mainline that already merged it; that is not used as circular “already selected” reasoning.

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

Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY
Record: [drivers/remoteproc] [IMPORTANT for SoCs with coprocessors using RPMsg; not core mm/VFS]. Affects i.MX8QM/QXP and Xilinx R5 attach-on- recovery.

Step 7.2: ASSESS SUBSYSTEM ACTIVITY
Record: Mature core with ongoing platform work. Attach-on-recovery itself has been in place since v6.1, so this is a long-standing hole, not a brand-new API.

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

Step 8.1: DETERMINE WHO IS AFFECTED
Record: Driver/config-specific: CONFIG_REMOTEPROC platforms with RPROC_FEAT_ATTACH_ON_RECOVERY (i.MX8QM/QXP; Xilinx R5 after patch 2). Not universal.

Step 8.2: DETERMINE THE TRIGGER CONDITIONS
Record: Remote core crash/watchdog + recovery enabled. i.MX: SCU partition reboot IRQ. Also sysfs/debugfs recover. Unprivileged users typically cannot trigger unless debugfs/sysfs is exposed.

Step 8.3: DETERMINE THE FAILURE MODE SEVERITY
Record: Host kernel does not oops. RPMsg/virtio IPC stays dead after “successful” recovery until Linux reboot. Severity: **HIGH** for those SoCs (recovery feature is non-functional), not CRITICAL host crash.

Step 8.4: CALCULATE RISK-BENEFIT RATIO
Record: Benefit: restores the documented attach-on-recovery path (real i.MX and Xilinx users). Risk: ~15 lines, copies existing detach teardown, no new lock. Ratio: favorable.

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

Step 9.1: COMPILE THE EVIDENCE
FOR:
- Real user-visible bug: RPMsg fails after attach-on-recovery (author reproduced; mechanism verified in __rproc_attach() vs rproc_attach()).
- Bug in code since v6.1; i.MX8QM/QXP already uses the feature and reports crash on partition reboot.
- Small, surgical, mirrors rproc_detach() then rproc_attach().
- No deadlock: rproc_attach() does not take rproc->lock.
- Maintainer applied v6 after RFC/v3 locking mistakes were dropped.
- No new APIs; standalone without series patch 2.

AGAINST:
- Not a host oops/UAF/security issue.
- Series also adds xlnx crash detection (feature); this patch is still a core correctness fix.
- Recovery path is not universal.
- Initial maintainer concern about mixing __rproc_detach and rproc_attach; committed form inlines detach cleanup instead of taking the public rproc_detach() lock/state path (the correct choice under rproc_trigger_recovery()’s mutex).

UNRESOLVED:
- lore.kernel.org HTTP 403; discussion recovered via b4/mbox/openwall.
- No public i.MX user report independent of the Xilinx series (code path still real).

Step 9.2: APPLY THE STABLE RULES CHECKLIST
1. Obviously correct and tested? **PASS** — teardown copied from rproc_detach(); author tested RPMsg recovery; maintainer applied v6.
2. Fixes a real bug that affects users? **PASS** — attach-on-recovery leaves RPMsg dead; i.MX8 and Xilinx hit this path.
3. Important issue? **PASS** — recovery is supposed to restore IPC; without this, a coprocessor watchdog forces a Linux reboot. Not a host panic, but a serious functional break on those SoCs.
4. Small and contained? **PASS** — 15 lines, one function.
5. No new features or APIs? **PASS** — repairs existing recovery.
6. Can apply to the local tree? **PASS** — helpers and rproc_attach_recovery() exist in 7.3-rc4.

Step 9.3: CHECK FOR EXCEPTION CATEGORIES
Record: None (not a device ID/quirk/DT/build/doc exception). Qualifies as a normal small bug fix.

Step 9.4: MAKE YOUR DECISION
This tree has the attach-on-recovery bug. The patch is a small, verified repair of that path. It should be backported here.

Verification:
- [Phase 1] Tags: author SOB, maintainer SOB, lore Link 20260630004806.3835488-2; no Fixes/Reported-by/Cc:stable
- [Phase 2] Diff: +14/-1 in rproc_attach_recovery(); __rproc_attach → cleanup + rproc_attach
- [Phase 2] Confirmed rproc_attach() is static and does not take rproc->lock (no deadlock with rproc_trigger_recovery())
- [Phase 2] Cleanup matches rproc_detach() / __rproc_shutdown() in the same file
- [Phase 3] git blame: buggy function from ba194232edc03 (v6.1-rc1)
- [Phase 3] git merge-base --is-ancestor ba194232edc03 HEAD → 0 (present)
- [Phase 3] imx enable: 6eed169c7fefd; crash trigger:
imx_rproc_partition_notify() → rproc_report_crash()
- [Phase 3] Series patch 2 5ae3dc0788746 is xlnx crash detection, not a prerequisite
- [Phase 4] b4 dig -c d93ffd549fb4d: msgid.link for v6 1/2; -a RFC→v6; -w Andersson/Poirier/linux-remoteproc
- [Phase 4] mbox: Mathieu “Applied.” on v6; RFC explained missing rproc_handle_resources()
- [Phase 4] lore.kernel.org fetch: 403; used b4/openwall
- [Phase 4] stable list search: no discussion of this patch
- [Phase 5] Callers: crash work, sysfs, debugfs
- [Phase 6] git describe HEAD: v7.3-rc4-27-gf0100363d8c37; make kernelversion: 7.3.0-rc4
- [Phase 8] Failure mode: RPMsg dead after recovery, not host oops
- UNVERIFIED: full lore HTML thread (403); no independent public i.MX bugzilla report

**YES**

 drivers/remoteproc/remoteproc_core.c | 15 ++++++++++++++-
 1 file changed, 14 insertions(+), 1 deletion(-)
drivers/remoteproc/remoteproc_core.c +14 -1
index bbc781e41a1b8..2336c55eb021d 100644
@@ -1784,7 +1784,20 @@ static int rproc_attach_recovery(struct rproc *rproc)
 	if (ret)
 		return ret;
 
-	return __rproc_attach(rproc);
+	/* clean up all acquired resources */
+	rproc_resource_cleanup(rproc);
+
+	/* release HW resources if needed */
+	rproc_unprepare_device(rproc);
+
+	rproc_disable_iommu(rproc);
+
+	/* Free the copy of the resource table */
+	kfree(rproc->cached_table);
+	rproc->cached_table = NULL;
+	rproc->table_ptr = NULL;
+
+	return rproc_attach(rproc);
 }
 
 static int rproc_boot_recovery(struct rproc *rproc)
Signature · 1 line
2.53.0
author maintainer
#58 lore raw

PATCH 1/1 ksmbd: fix off-by-one rejecting minimal COPYCHUNK query-limits request

In reply to Sasha Levin

From: Gael Blivet <[email protected]>

[ Upstream commit d68d4b3293034f549d55f407a23b4c0a6c90e50a ]

The FSCTL_COPYCHUNK/FSCTL_COPYCHUNK_WRITE input length check uses in_buf_len <= sizeof(struct copychunk_ioctl_req), which rejects a buffer that is exactly sizeof(struct copychunk_ioctl_req) bytes -- the minimal, valid request containing only the fixed header with ChunkCount=0 and no chunk entries, used by clients to query the server's copy limits before issuing a real copychunk.

Since copychunk_ioctl_req ends in a flexible array member, the correct minimum is that the buffer covers the fixed header, so use offsetof(..., Chunks) with '<' instead of '<=' against sizeof(): same value, but the boundary case is now correctly accepted.

Assisted-by Claude:claude-sonnet-5

---

LLM Generated explanations, may be completely bogus:

I have enough to judge this as a one-line protocol check against the 6.12 tree: the buggy <= sizeof test is present, the handler already implements ChunkCount=0, and the patch applies cleanly.

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

**Step 1.1: PARSE THE SUBJECT LINE**
Record: **[ksmbd]** **[fix]** off-by-one that rejects a minimal COPYCHUNK query-limits request (ChunkCount=0, header-only).

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**
Record:
- **Signed-off-by:** Gael Blivet <[email protected]> (author)
- **Signed-off-by:** Namjae Jeon <[email protected]> (ksmbd maintainer)
- **Assisted-by:** Claude:claude-sonnet-5
- **No Fixes:** tag (expected for this review pipeline)
- **No Cc: stable** (expected)
- **No Reported-by / Tested-by / Reviewed-by / Acked-by / Link:** in the committed message
- Ignore any pipeline “Upstream commit” / Sasha Levin SOB (none in the provided message)

Notable: maintainer SOB is a quality signal. No syzbot/KASAN tags.

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**
Record:
- **Bug:** in_buf_len <= sizeof(struct copychunk_ioctl_req) rejects a buffer that is **exactly** the fixed header size.
- **Symptom:** clients sending FSCTL_COPYCHUNK / FSCTL_COPYCHUNK_WRITE with ChunkCount=0 and no chunk entries (the standard “query server copy limits” request) get -EINVAL / STATUS_INVALID_PARAMETER.
- **Root cause:** the struct ends in a flexible array; the minimum valid length is the fixed header. sizeof and offsetof(..., Chunks) are the same numeric value (32); the real change is <= → < so equality is accepted.
- **Version info:** none in the message. The FAM conversion that made sizeof equal the header size is in this tree.

**Step 1.4: DETECT HIDDEN BUG FIXES**
Record: **Not hidden.** Subject/body explicitly describe a protocol off- by-one. Not cleanup/refactor.

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

**Step 2.1: INVENTORY THE CHANGES**
Record:
- **File:** fs/smb/server/smb2pdu.c — 1 line changed (<= sizeof(...) → < offsetof(..., Chunks)).
- **Function:** smb2_ioctl() (FSCTL_SRV_COPYCHUNK / FSCTL_SRV_COPYCHUNK_WRITE cases).
- **Scope:** single-file surgical fix, ~1 line.

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**
Record:
- **Before:** reject when in_buf_len <= 32 → a valid 32-byte header- only request is rejected; goto out with ret = -EINVAL **before** nbytes is set, so the client gets an error response **without** the copychunk limits body.
- **After:** reject only when in_buf_len < 32 → 32-byte request proceeds into fsctl_copychunk().
- **Path:** ioctl input-length check (not a crash path). Downstream fsctl_copychunk() already does if (chunk_count == 0) goto out; after filling max chunk count/size/total in the response.

**Step 2.3: IDENTIFY THE BUG MECHANISM**
Record:
- **Category:** logic / correctness (off-by-one bounds check), protocol interoperability.
- **Mechanism:** <= vs < on a FAM struct whose sizeof is the header size. Valid minimum request was treated as too small.
- **Not:** UAF, leak, race, overflow, deadlock.

Verified safety after the change: if a 32-byte buffer lies with ChunkCount ≠ 0, fsctl_copychunk() still rejects via input_count < struct_size(ci_req, Chunks, chunk_count) before touching Chunks[].

**Step 2.4: ASSESS THE FIX QUALITY**
Record:
- **Obviously correct.** offsetof on a FAM is the idiomatic minimum; verified sizeof == offsetof == 32 with a packed layout compile.
- **Minimal.** No unrelated changes, no API/struct changes.
- **Regression risk: very low.** Only newly accepted case is in_buf_len == 32, which is the documented header-only request. Inner ChunkCount=0 path already exists in this tree.

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

**Step 3.1: BLAME THE CHANGED LINES**
Record:
- Current check is from **8bb04fb2b7e34** (“ksmbd: Replace one-element arrays with flexible-array members”, Thorsten Blum, 2024-08-20; in v6.12).
- That commit changed < sizeof to <= sizeof when converting __u8 Chunks[1] (sizeof **33**) to a FAM (sizeof **32**), preserving “need 33+ bytes” and thus still rejecting the 32-byte query.
- Original ioctl length check: **f7db8fd03a4bc5** (“ksmbd: add validation in smb2_ioctl”, 2021-10-08), in_buf_len < sizeof with the 1-byte dummy array — also rejected 32-byte requests.
- **Bug has been present since ioctl validation was added (5.16-era ksmbd), still present in this 6.12 tree.**

**Step 3.2: FOLLOW THE FIXES: TAG**
Record: **No Fixes: tag.** Buggy behavior traces to f7db8fd / 8bb04fb as above. Both are ancestors of HEAD.

**Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES**
Record:
- **0801c1374ab15** — __counted_by_le on copychunk_ioctl_req (in this tree); inner struct_size check is already correct.
- **8a84ffa455462** — moved copychunk structs to fs/smb/common/smb2pdu.h (in this tree).
- No other local commit already applies this <= → < offsetof change (git log --grep on the path found nothing).
- **Standalone.** Cover letter: “These 7 fixes are independent of each other.”

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**
Record:
- Author Gael Blivet has **no** prior commits in this tree’s fs/smb/.
- Series: macOS/Time Machine work; this patch is explicitly **not** Apple-specific.
- **Namjae Jeon** (maintainer) applied the series (except patch 7, replaced by other ADS copychunk commits).

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS** Record:
- Needs FAM Chunks[] so offsetof(..., Chunks) is valid — **present** (8bb04fb).
- Does **not** need later AAPL full-file-copy (529d203daa00b, not in this tree). In 6.12, ChunkCount=0 already means “return limits and succeed.”
- **Can apply standalone.** git apply --check succeeded at offset −857 lines.

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

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**
Record:
- **b4 dig -c fdf17b206bdc8:** match at
https://patch.msgid.link/[email protected]
- **b4 dig -a:** only **v1**; committed version is that v1 (plus later Assisted-by in the git message).
- Cover: [PATCH 0/7] ksmbd: assorted fixes found while adding macOS/Time Machine support (2026-07-07).
- Author: independent of Apple-specific behavior; this one “affects any client probing server copy limits with a minimal FSCTL_SRV_COPYCHUNK request (ChunkCount=0).” Found and verified in live Time Machine/Finder testing.
- **Namjae Jeon (2026-07-08):** “Applied them to #ksmbd-for-next-next except 0007 patch.” **No NAK.** No reviewer asked for Cc: stable.

**Step 4.2: CHECK WHO REVIEWED THE PATCH**
Record (**b4 dig -w**): To/Cc were Gaël Blivet-Bailly, **Namjae Jeon**, **[email protected]**. Maintainer was the recipient and applied it. No other Named Reviewed-by.

**Step 4.3: SEARCH FOR THE BUG REPORT**
Record: no bugzilla/syzbot. Evidence is live macOS Finder/Time Machine testing described in the cover letter. Linux CIFS client (__smb2_copychunk_range) does **not** send ChunkCount=0; it sends real chunks and learns limits from STATUS_INVALID_PARAMETER + response body. This bug hits clients that probe with a header-only request (macOS Finder, and any similar SMB2 client).

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**
Record: 7 independent patches. This is 1/7. Patch 7 (ADS copychunk) was **not** taken; maintainer used other commits. Later AAPL ChunkCount=0 full-file copy is a **feature**, not required here.

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**
Record: lore.kernel.org/stable search did not turn up discussion of this specific fix (WebSearch results were unrelated). No evidence it was previously rejected for stable.

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

**Step 5.1: IDENTIFY KEY FUNCTIONS**
Record: smb2_ioctl() (length check). Downstream: fsctl_copychunk().

**Step 5.2: TRACE CALLERS**
Record: smb2_ioctl is SMB2_IOCTL_HE in fs/smb/server/smb2ops.c. Reachable from authenticated SMB2/SMB3 clients over the network (not a local syscall). Interrupt/hot-path: no; file-server request path.

**Step 5.3: TRACE CALLEES**
Record: on success, fsctl_copychunk() fills copychunk_ioctl_rsp with ksmbd_server_side_copy_max_{chunk_count,chunk_size,total_size}() (256 chunks, ~2GiB), then if ChunkCount==0 returns 0 without copy I/O.

**Step 5.4: FOLLOW THE CALL CHAIN**
Record: SMB client → SMB2 IOCTL → smb2_ioctl → (currently rejected) / (after fix) fsctl_copychunk. **Reachable from userspace/network** with a writable share. Unprivileged local users cannot hit it unless they are SMB clients of ksmbd.

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**
Record: same FAM conversion also used <= sizeof for smb2_ea_info_req (line 4779). That is a **different** request and not this patch. Other ioctl checks already use in_buf_len < sizeof or offsetof (validate_negotiate, sparse, zero-data, etc.).

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

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?**
Record: **Yes.** Local tree is **6.12.111** (pending-6.12, git describe p-6.12-3-gc504cf0baa3d8). Buggy check is at fs/smb/server/smb2pdu.c:8475. Inner ChunkCount=0 limits path is at 7925–7934. Candidate commit **fdf17b206bdc8 is not** an ancestor of HEAD.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**
Record: **Clean apply** with line-number offset (git apply --check:
hunk succeeded at 8472). Context around the COPYCHUNK cases matches. No conflicting local refactor of this check.

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**
Record: **No.** git log --grep='off-by-one rejecting minimal COPYCHUNK' on fs/smb/server/ is empty. No alternate fix of this comparison.

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

**Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY**
Record: **ksmbd** (fs/smb/server/), in-kernel SMB3 server. **IMPORTANT** (not core mm/VFS; not staging). CONFIG_SMB_SERVER. Network-facing; protocol mistakes affect all clients of that server.

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**
Record: **Active.** Recent 6.12.y ksmbd work is mostly protocol/security/response-size fixes. Mature enough that this ioctl check dates to 2021; still getting interoperability fixes.

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

**Step 8.1: DETERMINE WHO IS AFFECTED**
Record: **Config-specific + client-specific:** ksmbd servers whose clients send a 32-byte COPYCHUNK query-limits request. Linux CIFS does not. macOS Finder does (author’s live testing). Any other SMB2 client using that probe is affected.

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**
Record: Authenticated client, writable share, FSCTL_SRV_COPYCHUNK(_WRITE) with InputCount=32 and ChunkCount=0. **Common for macOS file copy / Time Machine-style copychunk probing.** Not a race. Not triggerable by a random unprivileged local process unless it is an SMB client.

**Step 8.3: DETERMINE THE FAILURE MODE SEVERITY**
Record:
- **Failure:** STATUS_INVALID_PARAMETER and **no** limits payload (smb2_set_err_rsp after -EINVAL with nbytes still 0).
- Server-side copy probe fails; clients that require this query cannot offload copy (fail or fall back to read/write).
- **Not** a panic, UAF, deadlock, or corruption.
- **Severity: MEDIUM** (functional/interop), important for ksmbd+macOS/Finder, not a kernel crash.

**Step 8.4: CALCULATE RISK-BENEFIT RATIO**
Record:
- **Benefit: medium-high for ksmbd users** — restores a path the inner handler already implements; 1-line; live-tested against real clients.
- **Risk: very low** — equality case only; ChunkCount≠0 still size- checked; no locking/API change.
- **Ratio:** strongly favors backport.

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

**Step 9.1: COMPILE THE EVIDENCE**

**FOR:**
- Real protocol bug: valid header-only COPYCHUNK is rejected; inner handler already supports ChunkCount=0 query-limits.
- User-visible: macOS Finder/Time Machine testing; any client using that probe.
- 1-line, obviously correct; sizeof/offsetof verified equal to 32.
- Standalone; maintainer applied it; applies cleanly here.
- Buggy code is in 6.12; candidate is not.
- Downstream access of Chunks[] remains guarded.

**AGAINST:**
- Not a crash/security/corruption/deadlock.
- Linux CIFS does not use this probe (Windows often uses oversized-chunk
+ EINVAL).
- Full Time Machine still needs later AAPL work not in 6.12 — but Finder copychunk probing does not.
- No Fixes:/Cc: stable (expected; not a negative).

**UNRESOLVED:**
- Exact share of Windows versions that send ChunkCount=0 was not verified against MS-SMB2 traces (author’s claim is “any client” using that probe; macOS was live-tested).
- lore.kernel.org HTTP fetch returned 403; discussion recovered via b4 dig -m.

**Step 9.2: APPLY THE STABLE RULES CHECKLIST**
1. Obviously correct and tested? **PASS** — 1-line; maintainer applied; live Finder/TM testing.
2. Fixes a real bug that affects users? **PASS** — valid SMB2 request rejected.
3. Important issue? **PASS** — interoperability for server-side copy (MEDIUM, not panic). For ksmbd this is a real service bug, not cosmetic.
4. Small and contained? **PASS** — 1 line, one function.
5. No new features or APIs? **PASS** — enables an already-implemented handler path.
6. Can apply to the local tree? **PASS** — git apply --check clean.

**Step 9.3: CHECK FOR EXCEPTION CATEGORIES**
Record: None (not a device ID, quirk, DT, build, or docs fix). Qualifies as a normal small bugfix.

**Step 9.4: MAKE YOUR DECISION**
This is a surgical protocol off-by-one in ksmbd’s COPYCHUNK ioctl check. The 6.12 tree still has in_buf_len <= sizeof(...), which rejects the 32-byte query-limits request that fsctl_copychunk() already handles. Benefit is real for ksmbd users with clients that probe that way; risk is negligible. It meets stable rules for this tree.

### What the commit solves and why it matters here
ksmbd currently turns a spec-valid FSCTL_COPYCHUNK with only the 32-byte header (ChunkCount=0) into STATUS_INVALID_PARAMETER and drops the limits body. After the fix, that request reaches the existing ChunkCount=0 path and returns max chunk count/size/total. That is required for server-side copy probing used by macOS Finder (and similar clients). On **this** 6.12 tree the bug is present and the later AAPL full-file-copy feature is not required.

### Risk vs benefit
Benefit: restore working COPYCHUNK limit queries. Risk: one comparison change; non-zero ChunkCount still validated with struct_size. Applies with a line offset only.

Verification:
- [Phase 1] Parsed tags: SOB Gael Blivet + Namjae Jeon; Assisted-by Claude; no Fixes/Cc stable/Reported-by
- [Phase 2] Diff: 1 line in smb2_ioctl COPYCHUNK cases; <= sizeof → < offsetof(..., Chunks)
- [Phase 2] Compile check: packed sizeof=32 and offsetof(Chunks)=32
- [Phase 2] Read fsctl_copychunk: ChunkCount==0 already fills limits and returns 0; non-zero uses struct_size before Chunks[]
- [Phase 2] Read smb2_ioctl out:: -EINVAL → STATUS_INVALID_PARAMETER via smb2_set_err_rsp (no limits body)
- [Phase 3] git blame: check from 8bb04fb2b7e34 (FAM); originally f7db8fd03a4bc5
- [Phase 3] git merge-base --is-ancestor 8bb04fb, f7db8fd, 0801c137:
all in HEAD; fdf17b206bdc8 not in HEAD
- [Phase 3] git log --grep='off-by-one rejecting minimal COPYCHUNK' -- fs/smb/server/: empty
- [Phase 4] b4 dig -c fdf17b206bdc8: lore match 20260707100033.47512-2; cover 0/7; Namjae applied except 0007
- [Phase 4] b4 dig -a: v1 only; b4 dig -w: maintainer + linux-cifs
- [Phase 4] Cover letter: independent of Apple-specific patches; live TM/Finder testing
- [Phase 4] stable@ lore search: no hit for this subject
- [Phase 5] Caller: smb2ops.c SMB2_IOCTL_HE → smb2_ioctl; network SMB path
- [Phase 5] Linux client __smb2_copychunk_range does not send ChunkCount=0
- [Phase 6] git describe HEAD: p-6.12-3-gc504cf0baa3d8; make kernelversion: 6.12.111
- [Phase 6] Buggy line at smb2pdu.c:8475; git apply --check succeeded at 8472
- [Phase 8] Failure: protocol reject of valid COPYCHUNK query, severity MEDIUM; not a crash
- UNVERIFIED: whether every Windows build sends ChunkCount=0 (not used to drive the verdict)

**YES**

 fs/smb/server/smb2pdu.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/smb/server/smb2pdu.c +1 -1
index d64753124dd9a..9bb885fa1ac66 100644
@@ -8576,7 +8576,7 @@ int smb2_ioctl(struct ksmbd_work *work)
 			goto out;
 		}
 
-		if (in_buf_len <= sizeof(struct copychunk_ioctl_req)) {
+		if (in_buf_len < offsetof(struct copychunk_ioctl_req, Chunks)) {
 			ret = -EINVAL;
 			goto out;
 		}
Signature · 1 line
2.53.0
author maintainer
#59 lore raw

PATCH 1/1 drm/amd/pm: Validate legacy hwmgr PP table offsets

In reply to Sasha Levin

From: Yang Wang <[email protected]>

[ Upstream commit 0ceb6bc43e62f0e73b282c9de8f4bc4d5498f281 ]

processpptables.c walks several variable-length PPLIB tables by using offsets from the VBIOS PowerPlay table. Some paths dereference extended headers, state arrays, clock arrays, non-clock arrays, or VCE records before checking that the referenced data is inside the table buffer.

Add local bounds helpers and validate the relevant offsets and entry sizes before dereferencing them. This prevents truncated or malformed legacy PowerPlay tables from driving out-of-bounds reads during hwmgr initialization and table entry lookup.

---

LLM Generated explanations, may be completely bogus:

Hawking’s series review is on file, and the v6.18.53 parser still has the unfixed offset walks. I’ll write up the nine-phase verdict from that evidence.

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

**Step 1.1: PARSE THE SUBJECT LINE**
Record: [drm/amd/pm] [Validate] [bounds-check legacy hwmgr PowerPlay table offsets before dereference]

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**
Record:
- Signed-off-by: Yang Wang <[email protected]> (author, AMD)
- Reviewed-by: Hawking Zhang <[email protected]> (AMD reviewer)
- Signed-off-by: Alex Deucher <[email protected]> (amdgpu maintainer)
- No Fixes: tag (expected)
- No Reported-by: / syzbot / Cc: stable
- No Link: in the committed message
- Ignore pipeline Signed-off-by: Sasha Levin and [Upstream commit 0ceb6bc43e62...]

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**
Record:
- **Bug:** processpptables.c walks variable-length PPLIB tables using VBIOS offsets and dereferences extended headers, state/clock/non-clock arrays, and VCE records without confirming they lie inside the table buffer.
- **Symptom:** out-of-bounds kernel reads during hwmgr init and table entry lookup on truncated or malformed PowerPlay tables.
- **Root cause:** offset/size taken from untrusted table contents; only a weak usTableSize >= sizeof(POWERPLAYTABLE3) check existed for extended headers; array walks used ucNumEntries / ucEntrySize with no remaining-buffer check.
- **Version info:** none in the message. Author date 2026-06-23; upstream commit 2026-07-01 (after v6.18).

**Step 1.4: DETECT HIDDEN BUG FIXES**
Record: Not disguised. Explicit memory-safety fix. Also silently corrects an off-by-one in get_state_entry_v2 (entry_index <= ucNumEntries vs >=) and adds a missing NULL/size check in pp_tables_initialize.

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

**Step 2.1: INVENTORY THE CHANGES**
Record:
- One file: drivers/gpu/drm/amd/pm/powerplay/hwmgr/processpptables.c
- +316 / -130 (446 lines touched); 21 hunks
- New: pp_table_has_space(), get_extended_header()
- Modified: VCE/UVD/SAMU/ACP/PowerTune/SCLK offset helpers, get_state_entry_v2, pp_tables_get_response_times, pp_tables_get_num_of_entries, pp_tables_get_entry, get_vce_state_table_entry, pp_tables_initialize
- Classification: single-file surgical hardening (not cross-subsystem)

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**
Record:
- **Extended-header getters:** previously cast powerplay_table + usExtendendedHeaderOffset after only usTableSize >= sizeof(POWERPLAYTABLE3). Now get_extended_header() also requires the offset and min_size to fit in hwmgr->soft_pp_table_size.
- **VCE/UVD array size helpers:** previously read ucNumEntries and computed size with no bounds check. Now require the count byte and the full computed array to fit; otherwise return 0 so later offset math stops.
- **get_state_entry_v2:** previously walked entry_index steps if entry_index <= ucNumEntries (allows OOB when entry_index == ucNumEntries) and returned the resulting pointer even if it walked off the buffer. Now rejects entry_index >= ucNumEntries and checks each variable-length entry against the buffer.
- **pp_tables_get_entry:** previously used offsets as-is (and entry_index > ucNumEntries, another off-by-one). Now validates state/clock/non-clock array headers, entry sizes, and per-index offsets; returns -1 on failure.
- **pp_tables_initialize:** previously used powerplay_table with no NULL/size check after get_powerplay_table(). Now asserts table present and large enough for the header.
- Paths: init (pptable_init → hwmgr_hw_init) and entry lookup (power-state construction). Error paths become fail-closed instead of OOB.

**Step 2.3: IDENTIFY THE BUG MECHANISM**
Record: **(d) Memory safety — out-of-bounds reads** plus **(g) logic/off-by-one**.
Mechanism: firmware/sysfs PP tables supply offsets and counts; the parser added them to the base pointer without comparing against soft_pp_table_size. The fix is overflow-safe (offset <= table_size && size <= table_size - offset) and rejects truncated entries.

**Step 2.4: ASSESS THE FIX QUALITY**
Record:
- Obviously correct for the paths it covers: fail closed, no new APIs, local static helpers.
- Not complete for the whole file: init_thermal_controller still uses usFanTableOffset, and init_overdrive_limits_V2_1 still uses usExtendendedHeaderOffset, without pp_table_has_space(). Partial hardening is still a real fix.
- Regression risk: well-formed VBIOS inside the ATOM-reported size is unchanged. Malformed tables that previously “worked” by reading past the buffer now fail init (pptable_init error → DPM init error). That is the intended fail-closed behavior.
- No public API / struct layout change.

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

**Step 3.1: BLAME THE CHANGED LINES**
Record: Unfixed get_vce_table_offset at v6.18.53 blames 3bace359149391 (“drm/amd/powerplay: add hardware manager sub- component”, 2015-12-21). Present since the powerplay hwmgr was added. Confirmed ancestor of v6.18.53.

**Step 3.2: FOLLOW THE FIXES: TAG**
Record: No Fixes: tag. Bug is original parser design, not a later regression.

**Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES**
Record: Same author series (standalone files, not compile deps for this patch):
- Validate pp_table header before reading size (sysfs/SMU)
- Use uploaded size for legacy custom PPTable (amd_powerplay.c)
- Validate Tonga PowerPlay state array bounds
- Validate Vega hwmgr PowerPlay table bounds
This commit is **[PATCH 5/5]** and only touches processpptables.c. No prerequisite refactor in this file. No later follow-up on this file after upstream 0ceb6bc43e62.

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**
Record: Yang Wang is an AMD pm contributor with multiple PP-table UAF/bounds fixes (fix pptable use-after-free, header-size validation, custom-table size). Hawking Zhang and Alex Deucher reviewed/merged. Maintainer-backed.

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS**
Record: Applies standalone. Uses existing hwmgr->soft_pp_table_size (in hwmgr.h at v6.18.53). Sibling patch “Use uploaded size…” is **not** required for this to compile; it would make short *custom* uploads match soft_pp_table_size more tightly. This patch still stops offsets past the allocated buffer.

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

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**
Record:
- b4 dig -c 0ceb6bc43e62... → only **v1**, msgid [email protected]
- Series: [PATCH 1/5] ... header before reading size through [PATCH 5/5] Validate legacy hwmgr PP table offsets
- lore.kernel.org fetches returned **403**; thread recovered via https://ratatoskr.run/amd-gfx/2026/06/17163868
- b4 dig -a: only v1 (committed version is the submitted version)
- Merged via Alex Deucher drm-next-7.3 pull (lists.freedesktop.org/archives/amd-gfx/2026-July/148126.html)
- No NAK found. No reviewer Cc: stable found (absence expected).

**Step 4.2: CHECK WHO REVIEWED THE PATCH**
Record: b4 dig -w CC: Yang Wang, amd-gfx, [email protected], [email protected], [email protected]. Hawking replied R-B on the series (RE: [PATCH 1/5] on 2026-06-23); commit carries his Reviewed- by. Alex Deucher signed off.

**Step 4.3: SEARCH FOR THE BUG REPORT**
Record: No syzbot/bugzilla. The 5-patch series is systematic hardening of PP-table parsing after related issues (bound pp_dpm_set_pp_table() memcpy heap overflow, pptable UAF). Severity from code: kernel OOB read.

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**
Record: 5-patch v1 series; this is 5/5, different files. Standalone for this tree.

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**
Record: lore.kernel.org/stable search not usable (403). git log --grep="Validate legacy" on v6.18.53: not present. No evidence it was rejected for stable.

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

**Step 5.1: KEY FUNCTIONS**
Record: pp_table_has_space, get_extended_header, VCE/UVD/SAMU/ACP/PowerTune/SCLK offset helpers, get_state_entry_v2, pp_tables_get_response_times, pp_tables_get_num_of_entries, pp_tables_get_entry, get_vce_state_table_entry, pp_tables_initialize.

**Step 5.2: TRACE CALLERS**
Record:
- pptable_funcs.pptable_init = pp_tables_initialize → hwmgr_hw_init() (GPU DPM init / amd_powerplay_reset after sysfs upload)
- pptable_funcs assigned for:
- SMU7 + PP_TABLE_V0: AMDGPU_FAMILY_CI (Bonaire/Hawaii), CHIP_TOPAZ (Iceland)
- SMU8: AMDGPU_FAMILY_CZ (Carrizo/Stoney)
- SMU10: CHIP_RAVEN (dummy table; initialize returns 0 early)
- pp_tables_get_entry called from smu7_hwmgr.c, smu8_hwmgr.c, smu10_hwmgr.c while building power states.

**Step 5.3: TRACE CALLEES**
Record: get_powerplay_table() fills soft_pp_table / soft_pp_table_size from ATOM PowerPlayInfo or the dummy table. Helpers then index that buffer.

**Step 5.4: FOLLOW THE CALL CHAIN**
Record: Reachable on every boot of CI/CZ/Iceland amdgpu with DPM, and on pp_table sysfs write (S_IWUSR, typically root) which copies a user buffer and calls amd_powerplay_reset() → pptable_init / entry lookup.

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**
Record: Same series adds analogous checks in Tonga (process_pptables_v1_0.c) and Vega parsers. Leftover unguarded usFanTableOffset / overdrive extended-header walks remain in this file.

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

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?**
Record: Local tree is **6.18.53** (git describe HEAD = v6.18.53-5049-g0f0bdc2b0dffb; Makefile VERSION=6 PATCHLEVEL=18 SUBLEVEL=53).
- git merge-base --is-ancestor 0ceb6bc43e62 v6.18.53 → **no** (fix not in 6.18.53)
- git grep pp_table_has_space v6.18.53 -- processpptables.c → **NOT PRESENT**
- Unfixed get_vce_table_offset / get_state_entry_v2 / pp_tables_get_entry confirmed at v6.18.53.
- Bug introduced 2015; present in this series.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**
Record: patch --dry-run of this commit onto the v6.18.53 blob: **EXIT 0, clean apply**. File not refactored between 6.18.53 and the patch context.

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**
Record: No equivalent bounds helper in this file at v6.18.53. 3334985f8b4c7 (bound pp_dpm_set_pp_table() memcpy) is in 6.18.53 and only caps upload size; it does not validate internal offsets.

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

**Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY**
Record: drivers/gpu/drm/amd/pm/powerplay — **IMPORTANT** (legacy AMD GPU powerplay). Not core mm/vfs, but amdgpu DPM init is a common production path (CI/CZ laptops and cards still in use).

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**
Record: Actively maintained; this is late hardening of a 10-year-old parser, not a brand-new subsystem.

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

**Step 8.1: WHO IS AFFECTED**
Record: Driver-specific: amdgpu CI (Bonaire/Hawaii), Iceland/Topaz, Carrizo/Stoney; sysfs pp_table writers on those chips. Not Navi/RDNA swsmu.

**Step 8.2: TRIGGER CONDITIONS**
Record:
- Probe/init: truncated or offset-inconsistent VBIOS PowerPlay table.
- Sysfs: root write of a malformed table ≤ original size (6.18.53 still copies into the VBIOS-sized buffer). Offsets beyond that buffer OOB without this patch.
- Off-by-one: entry_index == ucNumEntries on format rev ≥ 6.
- Unprivileged users cannot write pp_table (S_IWUSR). VBIOS path runs on device init.

**Step 8.3: FAILURE MODE SEVERITY**
Record: Kernel **out-of-bounds read** → KASAN/oops or info leak. **HIGH**. Missing table in pp_tables_initialize was a possible NULL deref (**CRITICAL** if hit).

**Step 8.4: RISK-BENEFIT RATIO**
Record:
- **Benefit: HIGH** — stops OOB reads in DPM init on remaining CI/CZ hardware and custom PP tables.
- **Risk: LOW–MEDIUM** — +316 lines but one file, fail-closed checks, overflow-safe helper, maintainer-reviewed; leftover unguarded fan/overdrive walks are pre-existing, not introduced.
- **Ratio:** benefit outweighs risk.

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

**Step 9.1: COMPILE THE EVIDENCE**

FOR backporting:
- Real OOB reads in a firmware table parser present since 2015 and still in v6.18.53
- Off-by-one in get_state_entry_v2 / pp_tables_get_entry
- Probe-time path plus documented pp_table sysfs upload
- Applies cleanly to this tree
- Reviewed by Hawking Zhang, signed off by Alex Deucher
- No new APIs; overflow-safe helper
- No follow-up fix indicating the patch itself was buggy

AGAINST:
- Larger than a typical 10-line stable patch (+316/−130)
- Incomplete (fan/overdrive offset walks still unchecked)
- No syzbot/CVE/user crash report
- Sibling “uploaded size” patch not in 6.18.53 (custom short tables still keep VBIOS soft_pp_table_size)

UNRESOLVED:
- Full lore thread text (403); ratatoskr + b4 + drm-next pull used instead
- Whether any production VBIOS relies on reading past ATOM size (unverified; fail-closed is still correct)

**Step 9.2: STABLE RULES CHECKLIST**
1. Obviously correct and tested? **PASS** — overflow-safe bounds checks; v1 applied; maintainer R-B/SOB
2. Fixes a real bug that affects users? **PASS** — OOB reads on malformed VBIOS/custom PP tables; CI/CZ still use this parser
3. Important issue? **PASS** — HIGH (OOB read / possible oops); NULL deref on missing table
4. Small and contained? **PASS** — one file, no refactor, no API; large but contained
5. No new features or APIs? **PASS**
6. Can apply to the local tree? **PASS** — clean apply to v6.18.53; buggy code present

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

**Step 9.4: DECISION**
This should be backported to this 6.18.y tree. The parser is in-tree, the bug is old, the patch applies cleanly, and the failure mode is kernel OOB during GPU powerplay init.

Verification:
- [Phase 1] Parsed tags: author Yang Wang; Reviewed-by Hawking Zhang; SOB Alex Deucher; no Fixes/syzbot/stable Cc
- [Phase 2] Diff: +316/−130 in processpptables.c; adds pp_table_has_space/get_extended_header; validates offsets before deref; also fixes entry_index <= ucNumEntries off-by-one
- [Phase 3] git blame at v6.18.53: 3bace359149391 (2015-12-21); git merge-base --is-ancestor 3bace359149391 v6.18.53 = yes
- [Phase 3] No Fixes: tag; series siblings touch other files only
- [Phase 3] No follow-up on this file after 0ceb6bc43e62
- [Phase 4] b4 dig -c 0ceb6bc43e62: v1 only, msgid [email protected]
- [Phase 4] b4 dig -w: amd-gfx + Deucher + Hawking + Kenneth Feng
- [Phase 4] lore WebFetch 403; discussion via ratatoskr 17163868; merged in drm-next-7.3 pull
- [Phase 5] pptable_funcs used by smu7 (PP_TABLE_V0: CI, Topaz), smu8 (CZ), smu10 (Raven dummy); hwmgr_hw_init → pptable_init
- [Phase 5] pp_table sysfs AMDGPU_DEVICE_ATTR_RW with S_IWUSR; write → pp_dpm_set_pp_table → amd_powerplay_reset
- [Phase 6] git describe HEAD = v6.18.53-5049-g0f0bdc2b0dffb; make kernelversion 6.18.53
- [Phase 6] git merge-base --is-ancestor 0ceb6bc43e62 v6.18.53 = no; pp_table_has_space absent at v6.18.53
- [Phase 6] patch dry-run against v6.18.53 blob: EXIT 0
- [Phase 8] Failure mode: OOB read during hwmgr init / entry lookup, severity HIGH
- UNVERIFIED: full lore review body (403); whether any in-field VBIOS depends on reading past table_size

**YES**

 .../amd/pm/powerplay/hwmgr/processpptables.c  | 446 +++++++++++++-----
 1 file changed, 316 insertions(+), 130 deletions(-)
drivers/gpu/drm/amd/pm/powerplay/hwmgr/processpptables.c +316 -130
index f06b29e33ba45..f1009b2973574 100644
@@ -47,26 +47,53 @@
 
 #define NUM_BITS_CLOCK_INFO_ARRAY_INDEX 6
 
+static bool pp_table_has_space(struct pp_hwmgr *hwmgr, size_t offset,
+			       size_t size)
+{
+	size_t table_size = hwmgr->soft_pp_table_size;
+
+	return offset <= table_size && size <= table_size - offset;
+}
+
+static const ATOM_PPLIB_EXTENDEDHEADER *
+get_extended_header(struct pp_hwmgr *hwmgr,
+		    const ATOM_PPLIB_POWERPLAYTABLE *powerplay_table,
+		    size_t min_size)
+{
+	const ATOM_PPLIB_POWERPLAYTABLE3 *powerplay_table3;
+	const ATOM_PPLIB_EXTENDEDHEADER *extended_header;
+	u16 offset;
+
+	if (le16_to_cpu(powerplay_table->usTableSize) <
+	    sizeof(ATOM_PPLIB_POWERPLAYTABLE3) ||
+	    !pp_table_has_space(hwmgr, 0, sizeof(ATOM_PPLIB_POWERPLAYTABLE3)))
+		return NULL;
+
+	powerplay_table3 = (const ATOM_PPLIB_POWERPLAYTABLE3 *)powerplay_table;
+	offset = le16_to_cpu(powerplay_table3->usExtendendedHeaderOffset);
+	if (!offset || !pp_table_has_space(hwmgr, offset,
+					   sizeof(extended_header->usSize)))
+		return NULL;
+
+	extended_header = (const ATOM_PPLIB_EXTENDEDHEADER *)
+		(((unsigned long)powerplay_table) + offset);
+	if (le16_to_cpu(extended_header->usSize) < min_size ||
+	    !pp_table_has_space(hwmgr, offset, min_size))
+		return NULL;
+
+	return extended_header;
+}
+
 static uint16_t get_vce_table_offset(struct pp_hwmgr *hwmgr,
 			const ATOM_PPLIB_POWERPLAYTABLE *powerplay_table)
 {
 	uint16_t vce_table_offset = 0;
+	const ATOM_PPLIB_EXTENDEDHEADER *extended_header;
 
-	if (le16_to_cpu(powerplay_table->usTableSize) >=
-	   sizeof(ATOM_PPLIB_POWERPLAYTABLE3)) {
-		const ATOM_PPLIB_POWERPLAYTABLE3 *powerplay_table3 =
-			(const ATOM_PPLIB_POWERPLAYTABLE3 *)powerplay_table;
-
-		if (powerplay_table3->usExtendendedHeaderOffset > 0) {
-			const ATOM_PPLIB_EXTENDEDHEADER  *extended_header =
-						(const ATOM_PPLIB_EXTENDEDHEADER *)
-						(((unsigned long)powerplay_table3) +
-						le16_to_cpu(powerplay_table3->usExtendendedHeaderOffset));
-			if (le16_to_cpu(extended_header->usSize) >=
-			   SIZE_OF_ATOM_PPLIB_EXTENDEDHEADER_V2)
-				vce_table_offset = le16_to_cpu(extended_header->usVCETableOffset);
-		}
-	}
+	extended_header = get_extended_header(hwmgr, powerplay_table,
+					      SIZE_OF_ATOM_PPLIB_EXTENDEDHEADER_V2);
+	if (extended_header)
+		vce_table_offset = le16_to_cpu(extended_header->usVCETableOffset);
 
 	return vce_table_offset;
 }
@@ -93,7 +120,14 @@ static uint16_t get_vce_clock_info_array_size(struct pp_hwmgr *hwmgr,
 	if (table_offset > 0) {
 		const VCEClockInfoArray *p = (const VCEClockInfoArray *)
 			(((unsigned long) powerplay_table) + table_offset);
-		table_size = sizeof(uint8_t) + p->ucNumEntries * sizeof(VCEClockInfo);
+		size_t size;
+
+		if (!pp_table_has_space(hwmgr, table_offset, sizeof(p->ucNumEntries)))
+			return 0;
+
+		size = sizeof(uint8_t) + p->ucNumEntries * sizeof(VCEClockInfo);
+		if (pp_table_has_space(hwmgr, table_offset, size))
+			table_size = size;
 	}
 
 	return table_size;
@@ -104,10 +138,13 @@ static uint16_t get_vce_clock_voltage_limit_table_offset(struct pp_hwmgr *hwmgr,
 {
 	uint16_t table_offset = get_vce_clock_info_array_offset(hwmgr,
 							powerplay_table);
+	u16 table_size;
 
-	if (table_offset > 0)
-		return table_offset + get_vce_clock_info_array_size(hwmgr,
-							powerplay_table);
+	if (table_offset > 0) {
+		table_size = get_vce_clock_info_array_size(hwmgr, powerplay_table);
+		if (table_size)
+			return table_offset + table_size;
+	}
 
 	return 0;
 }
@@ -121,8 +158,15 @@ static uint16_t get_vce_clock_voltage_limit_table_size(struct pp_hwmgr *hwmgr,
 	if (table_offset > 0) {
 		const ATOM_PPLIB_VCE_Clock_Voltage_Limit_Table *ptable =
 			(const ATOM_PPLIB_VCE_Clock_Voltage_Limit_Table *)(((unsigned long) powerplay_table) + table_offset);
+		size_t size;
 
-		table_size = sizeof(uint8_t) + ptable->numEntries * sizeof(ATOM_PPLIB_VCE_Clock_Voltage_Limit_Record);
+		if (!pp_table_has_space(hwmgr, table_offset, sizeof(ptable->numEntries)))
+			return 0;
+
+		size = sizeof(uint8_t) +
+			ptable->numEntries * sizeof(ATOM_PPLIB_VCE_Clock_Voltage_Limit_Record);
+		if (pp_table_has_space(hwmgr, table_offset, size))
+			table_size = size;
 	}
 	return table_size;
 }
@@ -130,9 +174,13 @@ static uint16_t get_vce_clock_voltage_limit_table_size(struct pp_hwmgr *hwmgr,
 static uint16_t get_vce_state_table_offset(struct pp_hwmgr *hwmgr, const ATOM_PPLIB_POWERPLAYTABLE *powerplay_table)
 {
 	uint16_t table_offset = get_vce_clock_voltage_limit_table_offset(hwmgr, powerplay_table);
+	u16 table_size;
 
-	if (table_offset > 0)
-		return table_offset + get_vce_clock_voltage_limit_table_size(hwmgr, powerplay_table);
+	if (table_offset > 0) {
+		table_size = get_vce_clock_voltage_limit_table_size(hwmgr, powerplay_table);
+		if (table_size)
+			return table_offset + table_size;
+	}
 
 	return 0;
 }
@@ -143,8 +191,12 @@ static const ATOM_PPLIB_VCE_State_Table *get_vce_state_table(
 {
 	uint16_t table_offset = get_vce_state_table_offset(hwmgr, powerplay_table);
 
-	if (table_offset > 0)
-		return (const ATOM_PPLIB_VCE_State_Table *)(((unsigned long) powerplay_table) + table_offset);
+	if (table_offset > 0) {
+		if (pp_table_has_space(hwmgr, table_offset,
+				       sizeof(((ATOM_PPLIB_VCE_State_Table *)0)->numEntries)))
+			return (const ATOM_PPLIB_VCE_State_Table *)
+				(((unsigned long)powerplay_table) + table_offset);
+	}
 
 	return NULL;
 }
@@ -153,21 +205,13 @@ static uint16_t get_uvd_table_offset(struct pp_hwmgr *hwmgr,
 			const ATOM_PPLIB_POWERPLAYTABLE *powerplay_table)
 {
 	uint16_t uvd_table_offset = 0;
+	const ATOM_PPLIB_EXTENDEDHEADER *extended_header;
+
+	extended_header = get_extended_header(hwmgr, powerplay_table,
+					      SIZE_OF_ATOM_PPLIB_EXTENDEDHEADER_V3);
+	if (extended_header)
+		uvd_table_offset = le16_to_cpu(extended_header->usUVDTableOffset);
 
-	if (le16_to_cpu(powerplay_table->usTableSize) >=
-	    sizeof(ATOM_PPLIB_POWERPLAYTABLE3)) {
-		const ATOM_PPLIB_POWERPLAYTABLE3 *powerplay_table3 =
-			(const ATOM_PPLIB_POWERPLAYTABLE3 *)powerplay_table;
-		if (powerplay_table3->usExtendendedHeaderOffset > 0) {
-			const ATOM_PPLIB_EXTENDEDHEADER  *extended_header =
-					(const ATOM_PPLIB_EXTENDEDHEADER *)
-					(((unsigned long)powerplay_table3) +
-				le16_to_cpu(powerplay_table3->usExtendendedHeaderOffset));
-			if (le16_to_cpu(extended_header->usSize) >=
-			    SIZE_OF_ATOM_PPLIB_EXTENDEDHEADER_V3)
-				uvd_table_offset = le16_to_cpu(extended_header->usUVDTableOffset);
-		}
-	}
 	return uvd_table_offset;
 }
 
@@ -193,8 +237,14 @@ static uint16_t get_uvd_clock_info_array_size(struct pp_hwmgr *hwmgr,
 		const UVDClockInfoArray *p = (const UVDClockInfoArray *)
 					(((unsigned long) powerplay_table)
 					+ table_offset);
-		table_size = sizeof(UCHAR) +
-			     p->ucNumEntries * sizeof(UVDClockInfo);
+		size_t size;
+
+		if (!pp_table_has_space(hwmgr, table_offset, sizeof(p->ucNumEntries)))
+			return 0;
+
+		size = sizeof(UCHAR) + p->ucNumEntries * sizeof(UVDClockInfo);
+		if (pp_table_has_space(hwmgr, table_offset, size))
+			table_size = size;
 	}
 
 	return table_size;
@@ -206,10 +256,13 @@ static uint16_t get_uvd_clock_voltage_limit_table_offset(
 {
 	uint16_t table_offset = get_uvd_clock_info_array_offset(hwmgr,
 						     powerplay_table);
+	u16 table_size;
 
-	if (table_offset > 0)
-		return table_offset +
-			get_uvd_clock_info_array_size(hwmgr, powerplay_table);
+	if (table_offset > 0) {
+		table_size = get_uvd_clock_info_array_size(hwmgr, powerplay_table);
+		if (table_size)
+			return table_offset + table_size;
+	}
 
 	return 0;
 }
@@ -218,21 +271,12 @@ static uint16_t get_samu_table_offset(struct pp_hwmgr *hwmgr,
 			const ATOM_PPLIB_POWERPLAYTABLE *powerplay_table)
 {
 	uint16_t samu_table_offset = 0;
+	const ATOM_PPLIB_EXTENDEDHEADER *extended_header;
 
-	if (le16_to_cpu(powerplay_table->usTableSize) >=
-	    sizeof(ATOM_PPLIB_POWERPLAYTABLE3)) {
-		const ATOM_PPLIB_POWERPLAYTABLE3 *powerplay_table3 =
-			(const ATOM_PPLIB_POWERPLAYTABLE3 *)powerplay_table;
-		if (powerplay_table3->usExtendendedHeaderOffset > 0) {
-			const ATOM_PPLIB_EXTENDEDHEADER  *extended_header =
-				(const ATOM_PPLIB_EXTENDEDHEADER *)
-				(((unsigned long)powerplay_table3) +
-				le16_to_cpu(powerplay_table3->usExtendendedHeaderOffset));
-			if (le16_to_cpu(extended_header->usSize) >=
-			    SIZE_OF_ATOM_PPLIB_EXTENDEDHEADER_V4)
-				samu_table_offset = le16_to_cpu(extended_header->usSAMUTableOffset);
-		}
-	}
+	extended_header = get_extended_header(hwmgr, powerplay_table,
+					      SIZE_OF_ATOM_PPLIB_EXTENDEDHEADER_V4);
+	if (extended_header)
+		samu_table_offset = le16_to_cpu(extended_header->usSAMUTableOffset);
 
 	return samu_table_offset;
 }
@@ -254,21 +298,12 @@ static uint16_t get_acp_table_offset(struct pp_hwmgr *hwmgr,
 				const ATOM_PPLIB_POWERPLAYTABLE *powerplay_table)
 {
 	uint16_t acp_table_offset = 0;
+	const ATOM_PPLIB_EXTENDEDHEADER *extended_header;
 
-	if (le16_to_cpu(powerplay_table->usTableSize) >=
-	    sizeof(ATOM_PPLIB_POWERPLAYTABLE3)) {
-		const ATOM_PPLIB_POWERPLAYTABLE3 *powerplay_table3 =
-			(const ATOM_PPLIB_POWERPLAYTABLE3 *)powerplay_table;
-		if (powerplay_table3->usExtendendedHeaderOffset > 0) {
-			const ATOM_PPLIB_EXTENDEDHEADER  *pExtendedHeader =
-				(const ATOM_PPLIB_EXTENDEDHEADER *)
-				(((unsigned long)powerplay_table3) +
-				le16_to_cpu(powerplay_table3->usExtendendedHeaderOffset));
-			if (le16_to_cpu(pExtendedHeader->usSize) >=
-			    SIZE_OF_ATOM_PPLIB_EXTENDEDHEADER_V6)
-				acp_table_offset = le16_to_cpu(pExtendedHeader->usACPTableOffset);
-		}
-	}
+	extended_header = get_extended_header(hwmgr, powerplay_table,
+					      SIZE_OF_ATOM_PPLIB_EXTENDEDHEADER_V6);
+	if (extended_header)
+		acp_table_offset = le16_to_cpu(extended_header->usACPTableOffset);
 
 	return acp_table_offset;
 }
@@ -290,21 +325,12 @@ static uint16_t get_cacp_tdp_table_offset(
 				const ATOM_PPLIB_POWERPLAYTABLE *powerplay_table)
 {
 	uint16_t cacTdpTableOffset = 0;
+	const ATOM_PPLIB_EXTENDEDHEADER *extended_header;
 
-	if (le16_to_cpu(powerplay_table->usTableSize) >=
-	    sizeof(ATOM_PPLIB_POWERPLAYTABLE3)) {
-		const ATOM_PPLIB_POWERPLAYTABLE3 *powerplay_table3 =
-				(const ATOM_PPLIB_POWERPLAYTABLE3 *)powerplay_table;
-		if (powerplay_table3->usExtendendedHeaderOffset > 0) {
-			const ATOM_PPLIB_EXTENDEDHEADER  *pExtendedHeader =
-					(const ATOM_PPLIB_EXTENDEDHEADER *)
-					(((unsigned long)powerplay_table3) +
-				le16_to_cpu(powerplay_table3->usExtendendedHeaderOffset));
-			if (le16_to_cpu(pExtendedHeader->usSize) >=
-			    SIZE_OF_ATOM_PPLIB_EXTENDEDHEADER_V7)
-				cacTdpTableOffset = le16_to_cpu(pExtendedHeader->usPowerTuneTableOffset);
-		}
-	}
+	extended_header = get_extended_header(hwmgr, powerplay_table,
+					      SIZE_OF_ATOM_PPLIB_EXTENDEDHEADER_V7);
+	if (extended_header)
+		cacTdpTableOffset = le16_to_cpu(extended_header->usPowerTuneTableOffset);
 
 	return cacTdpTableOffset;
 }
@@ -341,22 +367,13 @@ static uint16_t get_sclk_vdd_gfx_table_offset(struct pp_hwmgr *hwmgr,
 			const ATOM_PPLIB_POWERPLAYTABLE *powerplay_table)
 {
 	uint16_t sclk_vdd_gfx_table_offset = 0;
+	const ATOM_PPLIB_EXTENDEDHEADER *extended_header;
 
-	if (le16_to_cpu(powerplay_table->usTableSize) >=
-	    sizeof(ATOM_PPLIB_POWERPLAYTABLE3)) {
-		const ATOM_PPLIB_POWERPLAYTABLE3 *powerplay_table3 =
-				(const ATOM_PPLIB_POWERPLAYTABLE3 *)powerplay_table;
-		if (powerplay_table3->usExtendendedHeaderOffset > 0) {
-			const ATOM_PPLIB_EXTENDEDHEADER  *pExtendedHeader =
-				(const ATOM_PPLIB_EXTENDEDHEADER *)
-				(((unsigned long)powerplay_table3) +
-				le16_to_cpu(powerplay_table3->usExtendendedHeaderOffset));
-			if (le16_to_cpu(pExtendedHeader->usSize) >=
-			    SIZE_OF_ATOM_PPLIB_EXTENDEDHEADER_V8)
-				sclk_vdd_gfx_table_offset =
-					le16_to_cpu(pExtendedHeader->usSclkVddgfxTableOffset);
-		}
-	}
+	extended_header = get_extended_header(hwmgr, powerplay_table,
+					      SIZE_OF_ATOM_PPLIB_EXTENDEDHEADER_V8);
+	if (extended_header)
+		sclk_vdd_gfx_table_offset =
+			le16_to_cpu(extended_header->usSclkVddgfxTableOffset);
 
 	return sclk_vdd_gfx_table_offset;
 }
@@ -770,20 +787,37 @@ static ULONG size_of_entry_v2(ULONG num_dpm_levels)
 }
 
 static const ATOM_PPLIB_STATE_V2 *get_state_entry_v2(
+					struct pp_hwmgr *hwmgr,
 					const StateArray * pstate_arrays,
+					u16 state_array_offset,
 							 ULONG entry_index)
 {
 	ULONG i;
 	const ATOM_PPLIB_STATE_V2 *pstate;
+	size_t entry_offset;
+	size_t entry_size;
+
+	if (entry_index >= pstate_arrays->ucNumEntries)
+		return NULL;
 
+	entry_offset = state_array_offset + sizeof(pstate_arrays->ucNumEntries);
 	pstate = pstate_arrays->states;
-	if (entry_index <= pstate_arrays->ucNumEntries) {
-		for (i = 0; i < entry_index; i++)
-			pstate = (ATOM_PPLIB_STATE_V2 *)(
-						  (unsigned long)pstate +
-			     size_of_entry_v2(pstate->ucNumDPMLevels));
+	for (i = 0; i <= entry_index; i++) {
+		if (!pp_table_has_space(hwmgr, entry_offset, sizeof(*pstate)))
+			return NULL;
+
+		entry_size = size_of_entry_v2(pstate->ucNumDPMLevels);
+		if (!pp_table_has_space(hwmgr, entry_offset, entry_size))
+			return NULL;
+
+		if (i == entry_index)
+			return pstate;
+
+		entry_offset += entry_size;
+		pstate = (ATOM_PPLIB_STATE_V2 *)((unsigned long)pstate + entry_size);
 	}
-	return pstate;
+
+	return NULL;
 }
 
 static const unsigned char soft_dummy_pp_table[] = {
@@ -851,6 +885,8 @@ int pp_tables_get_response_times(struct pp_hwmgr *hwmgr,
 
 	PP_ASSERT_WITH_CODE(NULL != powerplay_tab,
 			    "Missing PowerPlay Table!", return -EINVAL);
+	PP_ASSERT_WITH_CODE(pp_table_has_space(hwmgr, 0, sizeof(*powerplay_tab)),
+			    "Invalid PowerPlay Table!", return -EINVAL);
 
 	*vol_rep_time = (uint32_t)le16_to_cpu(powerplay_tab->usVoltageTime);
 	*bb_rep_time = (uint32_t)le16_to_cpu(powerplay_tab->usBackbiasTime);
@@ -863,13 +899,21 @@ int pp_tables_get_num_of_entries(struct pp_hwmgr *hwmgr,
 {
 	const StateArray *pstate_arrays;
 	const ATOM_PPLIB_POWERPLAYTABLE *powerplay_table = get_powerplay_table(hwmgr);
+	u16 state_array_offset;
 
 	if (powerplay_table == NULL)
 		return -1;
+	if (!pp_table_has_space(hwmgr, 0, sizeof(*powerplay_table)))
+		return -1;
 
 	if (powerplay_table->sHeader.ucTableFormatRevision >= 6) {
+		state_array_offset = le16_to_cpu(powerplay_table->usStateArrayOffset);
+		if (!pp_table_has_space(hwmgr, state_array_offset,
+					sizeof(pstate_arrays->ucNumEntries)))
+			return -1;
+
 		pstate_arrays = (StateArray *)(((unsigned long)powerplay_table) +
-					le16_to_cpu(powerplay_table->usStateArrayOffset));
+					state_array_offset);
 
 		*num_of_entries = (unsigned long)(pstate_arrays->ucNumEntries);
 	} else
@@ -896,49 +940,128 @@ int pp_tables_get_entry(struct pp_hwmgr *hwmgr,
 	const NonClockInfoArray *pnon_clock_arrays;
 
 	const ATOM_PPLIB_STATE *pstate_entry;
+	u16 state_array_offset;
+	u16 clock_info_array_offset;
+	u16 non_clock_info_array_offset;
+	size_t clock_info_offset;
+	size_t non_clock_info_offset;
+	size_t state_entry_offset;
 
 	if (powerplay_table == NULL)
 		return -1;
+	if (!pp_table_has_space(hwmgr, 0, sizeof(*powerplay_table)))
+		return -1;
 
 	ps->classification.bios_index = entry_index;
 
 	if (powerplay_table->sHeader.ucTableFormatRevision >= 6) {
+		state_array_offset = le16_to_cpu(powerplay_table->usStateArrayOffset);
+		if (!pp_table_has_space(hwmgr, state_array_offset,
+					sizeof(pstate_arrays->ucNumEntries)))
+			return -1;
+
 		pstate_arrays = (StateArray *)(((unsigned long)powerplay_table) +
-					le16_to_cpu(powerplay_table->usStateArrayOffset));
+					state_array_offset);
+
+		if (entry_index >= pstate_arrays->ucNumEntries)
+			return -1;
 
-		if (entry_index > pstate_arrays->ucNumEntries)
+		pstate_entry_v2 = get_state_entry_v2(hwmgr, pstate_arrays,
+						     state_array_offset,
+						     entry_index);
+		if (!pstate_entry_v2)
+			return -1;
+
+		clock_info_array_offset =
+			le16_to_cpu(powerplay_table->usClockInfoArrayOffset);
+		if (!pp_table_has_space(hwmgr, clock_info_array_offset,
+					sizeof(*pclock_arrays)))
 			return -1;
 
-		pstate_entry_v2 = get_state_entry_v2(pstate_arrays, entry_index);
 		pclock_arrays = (ClockInfoArray *)(((unsigned long)powerplay_table) +
-					le16_to_cpu(powerplay_table->usClockInfoArrayOffset));
+					clock_info_array_offset);
+		if (!pclock_arrays->ucEntrySize)
+			return -1;
+
+		non_clock_info_array_offset =
+			le16_to_cpu(powerplay_table->usNonClockInfoArrayOffset);
+		if (!pp_table_has_space(hwmgr, non_clock_info_array_offset,
+					sizeof(*pnon_clock_arrays)))
+			return -1;
 
 		pnon_clock_arrays = (NonClockInfoArray *)(((unsigned long)powerplay_table) +
-						le16_to_cpu(powerplay_table->usNonClockInfoArrayOffset));
+						non_clock_info_array_offset);
+		if (!pnon_clock_arrays->ucEntrySize ||
+		    pnon_clock_arrays->ucEntrySize < ATOM_PPLIB_NONCLOCKINFO_VER1 ||
+		    (pnon_clock_arrays->ucEntrySize > ATOM_PPLIB_NONCLOCKINFO_VER1 &&
+		     pnon_clock_arrays->ucEntrySize < ATOM_PPLIB_NONCLOCKINFO_VER2) ||
+		    pstate_entry_v2->nonClockInfoIndex >= pnon_clock_arrays->ucNumEntries)
+			return -1;
 
+		non_clock_info_offset = non_clock_info_array_offset +
+			offsetof(NonClockInfoArray, nonClockInfo) +
+			pstate_entry_v2->nonClockInfoIndex * pnon_clock_arrays->ucEntrySize;
+		if (!pp_table_has_space(hwmgr, non_clock_info_offset,
+					pnon_clock_arrays->ucEntrySize))
+			return -1;
 		pnon_clock_info = (ATOM_PPLIB_NONCLOCK_INFO *)((unsigned long)(pnon_clock_arrays->nonClockInfo) +
 					(pstate_entry_v2->nonClockInfoIndex * pnon_clock_arrays->ucEntrySize));
 
 		result = init_non_clock_fields(hwmgr, ps, pnon_clock_arrays->ucEntrySize, pnon_clock_info);
 
 		for (i = 0; i < pstate_entry_v2->ucNumDPMLevels; i++) {
-			const void *pclock_info = (const void *)(
-							(unsigned long)(pclock_arrays->clockInfo) +
-							(pstate_entry_v2->clockInfoIndex[i] * pclock_arrays->ucEntrySize));
+			const void *pclock_info;
+
+			if (pstate_entry_v2->clockInfoIndex[i] >=
+			    pclock_arrays->ucNumEntries)
+				return -1;
+
+			clock_info_offset = clock_info_array_offset +
+				offsetof(ClockInfoArray, clockInfo) +
+				pstate_entry_v2->clockInfoIndex[i] * pclock_arrays->ucEntrySize;
+			if (!pp_table_has_space(hwmgr, clock_info_offset,
+						pclock_arrays->ucEntrySize))
+				return -1;
+
+			pclock_info = (const void *)
+					((unsigned long)(pclock_arrays->clockInfo) +
+					(pstate_entry_v2->clockInfoIndex[i] *
+					 pclock_arrays->ucEntrySize));
 			res = func(hwmgr, &ps->hardware, i, pclock_info);
 			if ((0 == result) && (0 != res))
 				result = res;
 		}
 	} else {
-		if (entry_index > powerplay_table->ucNumStates)
+		if (entry_index >= powerplay_table->ucNumStates ||
+		    !powerplay_table->ucStateEntrySize ||
+		    !powerplay_table->ucNonClockSize ||
+		    powerplay_table->ucNonClockSize < ATOM_PPLIB_NONCLOCKINFO_VER1 ||
+		    (powerplay_table->ucNonClockSize > ATOM_PPLIB_NONCLOCKINFO_VER1 &&
+		     powerplay_table->ucNonClockSize < ATOM_PPLIB_NONCLOCKINFO_VER2) ||
+		    !powerplay_table->ucClockInfoSize)
+			return -1;
+
+		state_array_offset = le16_to_cpu(powerplay_table->usStateArrayOffset);
+		state_entry_offset = state_array_offset +
+			entry_index * powerplay_table->ucStateEntrySize;
+		if (!pp_table_has_space(hwmgr, state_entry_offset,
+					powerplay_table->ucStateEntrySize))
 			return -1;
 
 		pstate_entry = (ATOM_PPLIB_STATE *)((unsigned long)powerplay_table +
-						    le16_to_cpu(powerplay_table->usStateArrayOffset) +
+						    state_array_offset +
 						    entry_index * powerplay_table->ucStateEntrySize);
 
+		non_clock_info_array_offset =
+			le16_to_cpu(powerplay_table->usNonClockInfoArrayOffset);
+		non_clock_info_offset = non_clock_info_array_offset +
+			pstate_entry->ucNonClockStateIndex * powerplay_table->ucNonClockSize;
+		if (!pp_table_has_space(hwmgr, non_clock_info_offset,
+					powerplay_table->ucNonClockSize))
+			return -1;
+
 		pnon_clock_info = (ATOM_PPLIB_NONCLOCK_INFO *)((unsigned long)powerplay_table +
-						le16_to_cpu(powerplay_table->usNonClockInfoArrayOffset) +
+						non_clock_info_array_offset +
 						pstate_entry->ucNonClockStateIndex *
 						powerplay_table->ucNonClockSize);
 
@@ -947,12 +1070,23 @@ int pp_tables_get_entry(struct pp_hwmgr *hwmgr,
 							pnon_clock_info);
 
 		for (i = 0; i < powerplay_table->ucStateEntrySize-1; i++) {
-			const void *pclock_info = (const void *)((unsigned long)powerplay_table +
-						le16_to_cpu(powerplay_table->usClockInfoArrayOffset) +
+			const void *pclock_info;
+
+			clock_info_array_offset =
+				le16_to_cpu(powerplay_table->usClockInfoArrayOffset);
+			clock_info_offset = clock_info_array_offset +
+				pstate_entry->ucClockStateIndices[i] *
+				powerplay_table->ucClockInfoSize;
+			if (!pp_table_has_space(hwmgr, clock_info_offset,
+						powerplay_table->ucClockInfoSize))
+				return -1;
+
+			pclock_info = (const void *)((unsigned long)powerplay_table +
+						clock_info_array_offset +
 						pstate_entry->ucClockStateIndices[i] *
 						powerplay_table->ucClockInfoSize);
 
-			int res = func(hwmgr, &ps->hardware, i, pclock_info);
+			res = func(hwmgr, &ps->hardware, i, pclock_info);
 
 			if ((0 == result) && (0 != res))
 					result = res;
@@ -1667,21 +1801,70 @@ static int get_vce_state_table_entry(struct pp_hwmgr *hwmgr,
 							unsigned long *flag)
 {
 	const ATOM_PPLIB_POWERPLAYTABLE *powerplay_table = get_powerplay_table(hwmgr);
+	const ATOM_PPLIB_VCE_State_Table *vce_state_table;
+	const ATOM_PPLIB_VCE_State_Record *record;
+	const VCEClockInfoArray *vce_clock_info_array;
+	const VCEClockInfo *vce_clock_info;
+	const ClockInfoArray *clock_arrays;
+	u16 vce_state_table_offset;
+	u16 vce_clock_info_array_offset;
+	u16 clock_info_array_offset;
+	unsigned long clockInfoIndex;
+	size_t record_offset;
+	size_t vce_clock_info_offset;
+	size_t clock_info_offset;
+
+	if (!powerplay_table || !pp_table_has_space(hwmgr, 0, sizeof(*powerplay_table)))
+		return -1;
 
-	const ATOM_PPLIB_VCE_State_Table *vce_state_table = get_vce_state_table(hwmgr, powerplay_table);
+	vce_state_table_offset = get_vce_state_table_offset(hwmgr, powerplay_table);
+	vce_state_table = get_vce_state_table(hwmgr, powerplay_table);
+	if (!vce_state_table || i >= vce_state_table->numEntries)
+		return -1;
+
+	record_offset = vce_state_table_offset +
+		offsetof(ATOM_PPLIB_VCE_State_Table, entries) +
+		i * sizeof(*record);
+	if (!pp_table_has_space(hwmgr, record_offset, sizeof(*record)))
+		return -1;
+
+	record = &vce_state_table->entries[i];
+
+	vce_clock_info_array_offset =
+		get_vce_clock_info_array_offset(hwmgr, powerplay_table);
+	if (!pp_table_has_space(hwmgr, vce_clock_info_array_offset,
+				sizeof(vce_clock_info_array->ucNumEntries)))
+		return -1;
 
-	unsigned short vce_clock_info_array_offset = get_vce_clock_info_array_offset(hwmgr, powerplay_table);
+	vce_clock_info_array = (const VCEClockInfoArray *)
+		(((unsigned long)powerplay_table) + vce_clock_info_array_offset);
+	if (record->ucVCEClockInfoIndex >= vce_clock_info_array->ucNumEntries)
+		return -1;
 
-	const VCEClockInfoArray *vce_clock_info_array = (const VCEClockInfoArray *)(((unsigned long) powerplay_table) + vce_clock_info_array_offset);
+	vce_clock_info_offset = vce_clock_info_array_offset +
+		offsetof(VCEClockInfoArray, entries) +
+		record->ucVCEClockInfoIndex * sizeof(*vce_clock_info);
+	if (!pp_table_has_space(hwmgr, vce_clock_info_offset, sizeof(*vce_clock_info)))
+		return -1;
 
-	const ClockInfoArray *clock_arrays = (ClockInfoArray *)(((unsigned long)powerplay_table) +
-								le16_to_cpu(powerplay_table->usClockInfoArrayOffset));
+	vce_clock_info = &vce_clock_info_array->entries[record->ucVCEClockInfoIndex];
 
-	const ATOM_PPLIB_VCE_State_Record *record = &vce_state_table->entries[i];
+	clock_info_array_offset = le16_to_cpu(powerplay_table->usClockInfoArrayOffset);
+	if (!pp_table_has_space(hwmgr, clock_info_array_offset,
+				sizeof(*clock_arrays)))
+		return -1;
 
-	const VCEClockInfo *vce_clock_info = &vce_clock_info_array->entries[record->ucVCEClockInfoIndex];
+	clock_arrays = (ClockInfoArray *)(((unsigned long)powerplay_table) +
+					  clock_info_array_offset);
+	clockInfoIndex = record->ucClockInfoIndex & 0x3F;
+	if (!clock_arrays->ucEntrySize || clockInfoIndex >= clock_arrays->ucNumEntries)
+		return -1;
 
-	unsigned long clockInfoIndex = record->ucClockInfoIndex & 0x3F;
+	clock_info_offset = clock_info_array_offset +
+		offsetof(ClockInfoArray, clockInfo) +
+		clockInfoIndex * clock_arrays->ucEntrySize;
+	if (!pp_table_has_space(hwmgr, clock_info_offset, clock_arrays->ucEntrySize))
+		return -1;
 
 	*flag = (record->ucClockInfoIndex >> NUM_BITS_CLOCK_INFO_ARRAY_INDEX);
 
@@ -1705,6 +1888,10 @@ static int pp_tables_initialize(struct pp_hwmgr *hwmgr)
 	hwmgr->need_pp_table_upload = true;
 
 	powerplay_table = get_powerplay_table(hwmgr);
+	PP_ASSERT_WITH_CODE((powerplay_table),
+			    "Missing PowerPlay Table!", return -1);
+	PP_ASSERT_WITH_CODE(pp_table_has_space(hwmgr, 0, sizeof(*powerplay_table)),
+			    "Invalid PowerPlay Table!", return -1);
 
 	result = init_powerplay_tables(hwmgr, powerplay_table);
 
@@ -1807,4 +1994,3 @@ const struct pp_table_func pptable_funcs = {
 	.pptable_get_vce_state_table_entry =
 						get_vce_state_table_entry,
 };
-
Signature · 1 line
2.53.0
#60 lore raw

Re: [PATCH AUTOSEL 6.18-5.10] drm/amd/pm: Validate legacy hwmgr PP table offsets

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider: - [High] drm/amd/pm: unvalidated subtable offsets in init_clock_voltage_dependency() - [High] drm/amd/pm…

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:
- [High] drm/amd/pm: unvalidated subtable offsets in init_clock_voltage_dependency()
- [High] drm/amd/pm: missing subtable bounds checks in pp_tables_initialize()
- [High] drm/amd/pm: weak clock info size and level checks in pp_tables_get_entry() --

commit c5c1e3659fd69a3025883887b44b7fe3a2082d39
Author: Yang Wang <[email protected]>

drm/amd/pm: Validate legacy hwmgr PP table offsets

This commit adds bounds helpers to drivers/gpu/drm/amd/pm/powerplay/hwmgr/processpptables.c to validate offsets and entry sizes against hwmgr->soft_pp_table_size before dereferencing variable-length PowerPlay subtables during hwmgr initialization and table entry lookup.

Quoted 4 lines
drivers/gpu/drm/amd/pm/powerplay/hwmgr/processpptables.c +0 -0
index f06b29e33ba45..f1009b2973574 100644

[ ... ]

Quoted 17 lines
drivers/gpu/drm/amd/pm/powerplay/hwmgr/processpptables.c +6 -3
@@ -104,10 +138,13 @@ static uint16_t get_vce_clock_voltage_limit_table_offset(struct pp_hwmgr *hwmgr,
 {
 	uint16_t table_offset = get_vce_clock_info_array_offset(hwmgr,
 							powerplay_table);
+	u16 table_size;
 
-	if (table_offset > 0)
-		return table_offset + get_vce_clock_info_array_size(hwmgr,
-							powerplay_table);
+	if (table_offset > 0) {
+		table_size = get_vce_clock_info_array_size(hwmgr, powerplay_table);
+		if (table_size)
+			return table_offset + table_size;
+	}
 
 	return 0;
 }

[ ... ]

Quoted 117 lines
drivers/gpu/drm/amd/pm/powerplay/hwmgr/processpptables.c +22 -58
@@ -206,10 +256,13 @@ static uint16_t get_uvd_clock_voltage_limit_table_offset(
 {
 	uint16_t table_offset = get_uvd_clock_info_array_offset(hwmgr,
 						     powerplay_table);
+	u16 table_size;
 
-	if (table_offset > 0)
-		return table_offset +
-			get_uvd_clock_info_array_size(hwmgr, powerplay_table);
+	if (table_offset > 0) {
+		table_size = get_uvd_clock_info_array_size(hwmgr, powerplay_table);
+		if (table_size)
+			return table_offset + table_size;
+	}
 
 	return 0;
 }
@@ -218,21 +271,12 @@ static uint16_t get_samu_table_offset(struct pp_hwmgr *hwmgr,
 			const ATOM_PPLIB_POWERPLAYTABLE *powerplay_table)
 {
 	uint16_t samu_table_offset = 0;
+	const ATOM_PPLIB_EXTENDEDHEADER *extended_header;
 
-	if (le16_to_cpu(powerplay_table->usTableSize) >=
-	    sizeof(ATOM_PPLIB_POWERPLAYTABLE3)) {
-		const ATOM_PPLIB_POWERPLAYTABLE3 *powerplay_table3 =
-			(const ATOM_PPLIB_POWERPLAYTABLE3 *)powerplay_table;
-		if (powerplay_table3->usExtendendedHeaderOffset > 0) {
-			const ATOM_PPLIB_EXTENDEDHEADER  *extended_header =
-				(const ATOM_PPLIB_EXTENDEDHEADER *)
-				(((unsigned long)powerplay_table3) +
-				le16_to_cpu(powerplay_table3->usExtendendedHeaderOffset));
-			if (le16_to_cpu(extended_header->usSize) >=
-			    SIZE_OF_ATOM_PPLIB_EXTENDEDHEADER_V4)
-				samu_table_offset = le16_to_cpu(extended_header->usSAMUTableOffset);
-		}
-	}
+	extended_header = get_extended_header(hwmgr, powerplay_table,
+					      SIZE_OF_ATOM_PPLIB_EXTENDEDHEADER_V4);
+	if (extended_header)
+		samu_table_offset = le16_to_cpu(extended_header->usSAMUTableOffset);
 
 	return samu_table_offset;
 }
@@ -254,21 +298,12 @@ static uint16_t get_acp_table_offset(struct pp_hwmgr *hwmgr,
 				const ATOM_PPLIB_POWERPLAYTABLE *powerplay_table)
 {
 	uint16_t acp_table_offset = 0;
+	const ATOM_PPLIB_EXTENDEDHEADER *extended_header;
 
-	if (le16_to_cpu(powerplay_table->usTableSize) >=
-	    sizeof(ATOM_PPLIB_POWERPLAYTABLE3)) {
-		const ATOM_PPLIB_POWERPLAYTABLE3 *powerplay_table3 =
-			(const ATOM_PPLIB_POWERPLAYTABLE3 *)powerplay_table;
-		if (powerplay_table3->usExtendendedHeaderOffset > 0) {
-			const ATOM_PPLIB_EXTENDEDHEADER  *pExtendedHeader =
-				(const ATOM_PPLIB_EXTENDEDHEADER *)
-				(((unsigned long)powerplay_table3) +
-				le16_to_cpu(powerplay_table3->usExtendendedHeaderOffset));
-			if (le16_to_cpu(pExtendedHeader->usSize) >=
-			    SIZE_OF_ATOM_PPLIB_EXTENDEDHEADER_V6)
-				acp_table_offset = le16_to_cpu(pExtendedHeader->usACPTableOffset);
-		}
-	}
+	extended_header = get_extended_header(hwmgr, powerplay_table,
+					      SIZE_OF_ATOM_PPLIB_EXTENDEDHEADER_V6);
+	if (extended_header)
+		acp_table_offset = le16_to_cpu(extended_header->usACPTableOffset);
 
 	return acp_table_offset;
 }
@@ -290,21 +325,12 @@ static uint16_t get_cacp_tdp_table_offset(
 				const ATOM_PPLIB_POWERPLAYTABLE *powerplay_table)
 {
 	uint16_t cacTdpTableOffset = 0;
+	const ATOM_PPLIB_EXTENDEDHEADER *extended_header;
 
-	if (le16_to_cpu(powerplay_table->usTableSize) >=
-	    sizeof(ATOM_PPLIB_POWERPLAYTABLE3)) {
-		const ATOM_PPLIB_POWERPLAYTABLE3 *powerplay_table3 =
-				(const ATOM_PPLIB_POWERPLAYTABLE3 *)powerplay_table;
-		if (powerplay_table3->usExtendendedHeaderOffset > 0) {
-			const ATOM_PPLIB_EXTENDEDHEADER  *pExtendedHeader =
-					(const ATOM_PPLIB_EXTENDEDHEADER *)
-					(((unsigned long)powerplay_table3) +
-				le16_to_cpu(powerplay_table3->usExtendendedHeaderOffset));
-			if (le16_to_cpu(pExtendedHeader->usSize) >=
-			    SIZE_OF_ATOM_PPLIB_EXTENDEDHEADER_V7)
-				cacTdpTableOffset = le16_to_cpu(pExtendedHeader->usPowerTuneTableOffset);
-		}
-	}
+	extended_header = get_extended_header(hwmgr, powerplay_table,
+					      SIZE_OF_ATOM_PPLIB_EXTENDEDHEADER_V7);
+	if (extended_header)
+		cacTdpTableOffset = le16_to_cpu(extended_header->usPowerTuneTableOffset);
 
 	return cacTdpTableOffset;
 }
@@ -341,22 +367,13 @@ static uint16_t get_sclk_vdd_gfx_table_offset(struct pp_hwmgr *hwmgr,
 			const ATOM_PPLIB_POWERPLAYTABLE *powerplay_table)
 {
 	uint16_t sclk_vdd_gfx_table_offset = 0;
+	const ATOM_PPLIB_EXTENDEDHEADER *extended_header;
 
-	if (le16_to_cpu(powerplay_table->usTableSize) >=
-	    sizeof(ATOM_PPLIB_POWERPLAYTABLE3)) {
-		const ATOM_PPLIB_POWERPLAYTABLE3 *powerplay_table3 =
-				(const ATOM_PPLIB_POWERPLAYTABLE3 *)powerplay_table;
-		if (powerplay_table3->usExtendendedHeaderOffset > 0) {
-			const ATOM_PPLIB_EXTENDEDHEADER  *pExtendedHeader =
-				(const ATOM_PPLIB_EXTENDEDHEADER *)
-				(((unsigned long)powerplay_table3) +
-				le16_to_cpu(powerplay_table3->usExtendendedHeaderOffset));
-			if (le16_to_cpu(pExtendedHeader->usSize) >=
-			    SIZE_OF_ATOM_PPLIB_EXTENDEDHEADER_V8)
-				sclk_vdd_gfx_table_offset =
-					le16_to_cpu(pExtendedHeader->usSclkVddgfxTableOffset);

drivers/gpu/drm/amd/pm/powerplay/hwmgr/processpptables.c static uint16_t get_sclk_vdd_gfx_table_offset(struct pp_hwmgr *hwmgr, · line 379

Quoted 10 lines
drivers/gpu/drm/amd/pm/powerplay/hwmgr/processpptables.c +5 -2
-		}
-	}
+	extended_header = get_extended_header(hwmgr, powerplay_table,
+					      SIZE_OF_ATOM_PPLIB_EXTENDEDHEADER_V8);
+	if (extended_header)
+		sclk_vdd_gfx_table_offset =
+			le16_to_cpu(extended_header->usSclkVddgfxTableOffset);
 
 	return sclk_vdd_gfx_table_offset;
 }

[Severity: High]
Can init_clock_voltage_dependency() still read past hwmgr->soft_pp_table when using the offsets returned by these helpers?

In get_vce_clock_voltage_limit_table_offset() and get_uvd_clock_voltage_limit_table_offset(), the new check verifies that the preceding VCEClockInfoArray or UVDClockInfoArray fits within hwmgr->soft_pp_table_size, and then returns table_offset + table_size. If that clock info array ends at hwmgr->soft_pp_table_size (or leaves fewer bytes than the voltage limit table requires), the returned offset is non-zero and points at or near the end of soft_pp_table.

When pp_tables_initialize() -> init_clock_voltage_dependency() uses those offsets, it does not call get_vce_clock_voltage_limit_table_size() or pp_table_has_space():

drivers/gpu/drm/amd/pm/powerplay/hwmgr/processpptables.c:init_clock_voltage_dependency() {
	vce_clock_info_array_offset = get_vce_clock_info_array_offset(
						hwmgr, powerplay_table);
	table_offset = get_vce_clock_voltage_limit_table_offset(hwmgr,
						powerplay_table);
	if (vce_clock_info_array_offset > 0 && table_offset > 0) {
		const VCEClockInfoArray *array = (const VCEClockInfoArray *)
				(((unsigned long) powerplay_table) +
				vce_clock_info_array_offset);
		const ATOM_PPLIB_VCE_Clock_Voltage_Limit_Table *table =
				(const ATOM_PPLIB_VCE_Clock_Voltage_Limit_Table *)
				(((unsigned long) powerplay_table) + table_offset);
		result = get_vce_clock_voltage_limit_table(hwmgr,
				&hwmgr->dyn_state.vce_clock_voltage_dependency_table,
				table, array);
	}
}

Then get_vce_clock_voltage_limit_table() and get_uvd_clock_voltage_limit_table() dereference table->numEntries and table->entries[i] without bounds checks, and also index array->entries[table->entries[i].ucVCEClockInfoIndex] and array->entries[table->entries[i].ucUVDClockInfoIndex] without verifying that the index is less than array->ucNumEntries.

Similarly, get_samu_table_offset(), get_acp_table_offset(), get_cacp_tdp_table_offset(), and get_sclk_vdd_gfx_table_offset() now validate the extended header via get_extended_header(), but neither those helpers nor their sole caller init_clock_voltage_dependency() verify that the returned subtable offsets and their entry arrays fit within hwmgr->soft_pp_table_size before dereferencing them.

[ ... ]

Quoted 157 lines
drivers/gpu/drm/amd/pm/powerplay/hwmgr/processpptables.c +101 -13
@@ -896,49 +940,128 @@ int pp_tables_get_entry(struct pp_hwmgr *hwmgr,
 	const NonClockInfoArray *pnon_clock_arrays;
 
 	const ATOM_PPLIB_STATE *pstate_entry;
+	u16 state_array_offset;
+	u16 clock_info_array_offset;
+	u16 non_clock_info_array_offset;
+	size_t clock_info_offset;
+	size_t non_clock_info_offset;
+	size_t state_entry_offset;
 
 	if (powerplay_table == NULL)
 		return -1;
+	if (!pp_table_has_space(hwmgr, 0, sizeof(*powerplay_table)))
+		return -1;
 
 	ps->classification.bios_index = entry_index;
 
 	if (powerplay_table->sHeader.ucTableFormatRevision >= 6) {
+		state_array_offset = le16_to_cpu(powerplay_table->usStateArrayOffset);
+		if (!pp_table_has_space(hwmgr, state_array_offset,
+					sizeof(pstate_arrays->ucNumEntries)))
+			return -1;
+
 		pstate_arrays = (StateArray *)(((unsigned long)powerplay_table) +
-					le16_to_cpu(powerplay_table->usStateArrayOffset));
+					state_array_offset);
+
+		if (entry_index >= pstate_arrays->ucNumEntries)
+			return -1;
 
-		if (entry_index > pstate_arrays->ucNumEntries)
+		pstate_entry_v2 = get_state_entry_v2(hwmgr, pstate_arrays,
+						     state_array_offset,
+						     entry_index);
+		if (!pstate_entry_v2)
+			return -1;
+
+		clock_info_array_offset =
+			le16_to_cpu(powerplay_table->usClockInfoArrayOffset);
+		if (!pp_table_has_space(hwmgr, clock_info_array_offset,
+					sizeof(*pclock_arrays)))
 			return -1;
 
-		pstate_entry_v2 = get_state_entry_v2(pstate_arrays, entry_index);
 		pclock_arrays = (ClockInfoArray *)(((unsigned long)powerplay_table) +
-					le16_to_cpu(powerplay_table->usClockInfoArrayOffset));
+					clock_info_array_offset);
+		if (!pclock_arrays->ucEntrySize)
+			return -1;
+
+		non_clock_info_array_offset =
+			le16_to_cpu(powerplay_table->usNonClockInfoArrayOffset);
+		if (!pp_table_has_space(hwmgr, non_clock_info_array_offset,
+					sizeof(*pnon_clock_arrays)))
+			return -1;
 
 		pnon_clock_arrays = (NonClockInfoArray *)(((unsigned long)powerplay_table) +
-						le16_to_cpu(powerplay_table->usNonClockInfoArrayOffset));
+						non_clock_info_array_offset);
+		if (!pnon_clock_arrays->ucEntrySize ||
+		    pnon_clock_arrays->ucEntrySize < ATOM_PPLIB_NONCLOCKINFO_VER1 ||
+		    (pnon_clock_arrays->ucEntrySize > ATOM_PPLIB_NONCLOCKINFO_VER1 &&
+		     pnon_clock_arrays->ucEntrySize < ATOM_PPLIB_NONCLOCKINFO_VER2) ||
+		    pstate_entry_v2->nonClockInfoIndex >= pnon_clock_arrays->ucNumEntries)
+			return -1;
 
+		non_clock_info_offset = non_clock_info_array_offset +
+			offsetof(NonClockInfoArray, nonClockInfo) +
+			pstate_entry_v2->nonClockInfoIndex * pnon_clock_arrays->ucEntrySize;
+		if (!pp_table_has_space(hwmgr, non_clock_info_offset,
+					pnon_clock_arrays->ucEntrySize))
+			return -1;
 		pnon_clock_info = (ATOM_PPLIB_NONCLOCK_INFO *)((unsigned long)(pnon_clock_arrays->nonClockInfo) +
 					(pstate_entry_v2->nonClockInfoIndex * pnon_clock_arrays->ucEntrySize));
 
 		result = init_non_clock_fields(hwmgr, ps, pnon_clock_arrays->ucEntrySize, pnon_clock_info);
 
 		for (i = 0; i < pstate_entry_v2->ucNumDPMLevels; i++) {
-			const void *pclock_info = (const void *)(
-							(unsigned long)(pclock_arrays->clockInfo) +
-							(pstate_entry_v2->clockInfoIndex[i] * pclock_arrays->ucEntrySize));
+			const void *pclock_info;
+
+			if (pstate_entry_v2->clockInfoIndex[i] >=
+			    pclock_arrays->ucNumEntries)
+				return -1;
+
+			clock_info_offset = clock_info_array_offset +
+				offsetof(ClockInfoArray, clockInfo) +
+				pstate_entry_v2->clockInfoIndex[i] * pclock_arrays->ucEntrySize;
+			if (!pp_table_has_space(hwmgr, clock_info_offset,
+						pclock_arrays->ucEntrySize))
+				return -1;
+
+			pclock_info = (const void *)
+					((unsigned long)(pclock_arrays->clockInfo) +
+					(pstate_entry_v2->clockInfoIndex[i] *
+					 pclock_arrays->ucEntrySize));
 			res = func(hwmgr, &ps->hardware, i, pclock_info);
 			if ((0 == result) && (0 != res))
 				result = res;
 		}
 	} else {
-		if (entry_index > powerplay_table->ucNumStates)
+		if (entry_index >= powerplay_table->ucNumStates ||
+		    !powerplay_table->ucStateEntrySize ||
+		    !powerplay_table->ucNonClockSize ||
+		    powerplay_table->ucNonClockSize < ATOM_PPLIB_NONCLOCKINFO_VER1 ||
+		    (powerplay_table->ucNonClockSize > ATOM_PPLIB_NONCLOCKINFO_VER1 &&
+		     powerplay_table->ucNonClockSize < ATOM_PPLIB_NONCLOCKINFO_VER2) ||
+		    !powerplay_table->ucClockInfoSize)
+			return -1;
+
+		state_array_offset = le16_to_cpu(powerplay_table->usStateArrayOffset);
+		state_entry_offset = state_array_offset +
+			entry_index * powerplay_table->ucStateEntrySize;
+		if (!pp_table_has_space(hwmgr, state_entry_offset,
+					powerplay_table->ucStateEntrySize))
 			return -1;
 
 		pstate_entry = (ATOM_PPLIB_STATE *)((unsigned long)powerplay_table +
-						    le16_to_cpu(powerplay_table->usStateArrayOffset) +
+						    state_array_offset +
 						    entry_index * powerplay_table->ucStateEntrySize);
 
+		non_clock_info_array_offset =
+			le16_to_cpu(powerplay_table->usNonClockInfoArrayOffset);
+		non_clock_info_offset = non_clock_info_array_offset +
+			pstate_entry->ucNonClockStateIndex * powerplay_table->ucNonClockSize;
+		if (!pp_table_has_space(hwmgr, non_clock_info_offset,
+					powerplay_table->ucNonClockSize))
+			return -1;
+
 		pnon_clock_info = (ATOM_PPLIB_NONCLOCK_INFO *)((unsigned long)powerplay_table +
-						le16_to_cpu(powerplay_table->usNonClockInfoArrayOffset) +
+						non_clock_info_array_offset +
 						pstate_entry->ucNonClockStateIndex *
 						powerplay_table->ucNonClockSize);
 
@@ -947,12 +1070,23 @@ int pp_tables_get_entry(struct pp_hwmgr *hwmgr,
 							pnon_clock_info);
 
 		for (i = 0; i < powerplay_table->ucStateEntrySize-1; i++) {
-			const void *pclock_info = (const void *)((unsigned long)powerplay_table +
-						le16_to_cpu(powerplay_table->usClockInfoArrayOffset) +
+			const void *pclock_info;
+
+			clock_info_array_offset =
+				le16_to_cpu(powerplay_table->usClockInfoArrayOffset);
+			clock_info_offset = clock_info_array_offset +
+				pstate_entry->ucClockStateIndices[i] *
+				powerplay_table->ucClockInfoSize;
+			if (!pp_table_has_space(hwmgr, clock_info_offset,
+						powerplay_table->ucClockInfoSize))
+				return -1;
+

drivers/gpu/drm/amd/pm/powerplay/hwmgr/processpptables.c int pp_tables_get_entry(struct pp_hwmgr *hwmgr, · line 1092

Quoted 10 lines
drivers/gpu/drm/amd/pm/powerplay/hwmgr/processpptables.c +3 -1
+			pclock_info = (const void *)((unsigned long)powerplay_table +
+						clock_info_array_offset +
 						pstate_entry->ucClockStateIndices[i] *
 						powerplay_table->ucClockInfoSize);
 
-			int res = func(hwmgr, &ps->hardware, i, pclock_info);
+			res = func(hwmgr, &ps->hardware, i, pclock_info);
 
 			if ((0 == result) && (0 != res))
 					result = res;

[Severity: High]
Are the checks on pclock_arrays->ucEntrySize, powerplay_table->ucClockInfoSize, and the DPM level loop counts in pp_tables_get_entry() sufficient to prevent out-of-bounds accesses in the clock info callbacks?

Unlike pnon_clock_arrays->ucEntrySize and powerplay_table->ucNonClockSize (which are checked against ATOM_PPLIB_NONCLOCKINFO_VER1 and ATOM_PPLIB_NONCLOCKINFO_VER2), pclock_arrays->ucEntrySize and powerplay_table->ucClockInfoSize are only checked to be non-zero. If either field is between 1 and 8 bytes at the end of hwmgr->soft_pp_table, pp_table_has_space() succeeds, and when func is smu7_get_pp_table_entry_callback_func_v0() in drivers/gpu/drm/amd/pm/powerplay/hwmgr/smu7_hwmgr.c:

	const ATOM_PPLIB_CI_CLOCK_INFO *visland_clk_info = clock_info;
	...
	engine_clock = visland_clk_info->ucEngineClockHigh << 16 | visland_clk_info->usEngineClockLow;
	memory_clock = visland_clk_info->ucMemoryClockHigh << 16 | visland_clk_info->usMemoryClockLow;

it casts clock_info to const ATOM_PPLIB_CI_CLOCK_INFO * (9 bytes) and reads up to 8 bytes past hwmgr->soft_pp_table.

In addition, the DPM level loops in pp_tables_get_entry() iterate i up to pstate_entry_v2->ucNumDPMLevels or powerplay_table->ucStateEntrySize - 1 without bounding i against hwmgr->platform_descriptor.hardwareActivityPerformanceLevels. When func is smu8_dpm_get_pp_table_entry_callback() in drivers/gpu/drm/amd/pm/powerplay/hwmgr/smu8_hwmgr.c:

	smu8_ps->levels[index].engineClock = table->entries[clock_info_index].clk;
	smu8_ps->levels[index].vddcIndex = (uint8_t)table->entries[clock_info_index].v;

or smu10_dpm_get_pp_table_entry_callback() in drivers/gpu/drm/amd/pm/powerplay/hwmgr/smu10_hwmgr.c:

	smu10_ps->levels[index].engine_clock = 0;

	smu10_ps->levels[index].vddc_index = 0;
	smu10_ps->level = index + 1;

can an uncapped index overflow smu8_ps->levels[SMU8_MAX_HARDWARE_POWERLEVELS] or smu10_ps->levels[SMU10_MAX_HARDWARE_POWERLEVELS] (both 8 entries)?

[ ... ]

drivers/gpu/drm/amd/pm/powerplay/hwmgr/processpptables.c static int pp_tables_initialize(struct pp_hwmgr *hwmgr) · line 1897

Quoted 11 lines
drivers/gpu/drm/amd/pm/powerplay/hwmgr/processpptables.c +4 -0
@@ -1705,6 +1888,10 @@ static int pp_tables_initialize(struct pp_hwmgr *hwmgr)
 	hwmgr->need_pp_table_upload = true;
 
 	powerplay_table = get_powerplay_table(hwmgr);
+	PP_ASSERT_WITH_CODE((powerplay_table),
+			    "Missing PowerPlay Table!", return -1);
+	PP_ASSERT_WITH_CODE(pp_table_has_space(hwmgr, 0, sizeof(*powerplay_table)),
+			    "Invalid PowerPlay Table!", return -1);
 
 	result = init_powerplay_tables(hwmgr, powerplay_table);
 

[Severity: High]
Does checking only sizeof(*powerplay_table) in pp_tables_initialize() leave the remaining initialization helpers vulnerable to out-of-bounds reads when powerplay_table->usTableSize or subtable offsets exceed hwmgr->soft_pp_table_size?

After verifying pp_table_has_space(hwmgr, 0, sizeof(*powerplay_table)), pp_tables_initialize() calls init_thermal_controller(), init_overdrive_limits(), init_clock_voltage_dependency(), init_dpm2_parameters(), and init_phase_shedding_table(). Those helpers check powerplay_table->usTableSize against sizeof(ATOM_PPLIB_POWERPLAYTABLE3), sizeof(ATOM_PPLIB_POWERPLAYTABLE4), or sizeof(ATOM_PPLIB_POWERPLAYTABLE5) without verifying that hwmgr->soft_pp_table_size is large enough for those structures or their subtables:

1. init_thermal_controller() checks powerplay_table->usTableSize >= sizeof(ATOM_PPLIB_POWERPLAYTABLE3) and dereferences powerplay_table3->usFanTableOffset up to ATOM_PPLIB_FANTABLE5 without calling pp_table_has_space().

2. init_overdrive_limits() -> init_overdrive_limits_V2_1() and init_dpm2_parameters() bypass get_extended_header() and directly dereference usExtendendedHeaderOffset (and usPPMTableOffset in init_dpm2_parameters()) without bounds checks.

3. init_clock_voltage_dependency(), init_dpm2_parameters(), and init_phase_shedding_table() dereference usVddcDependencyOnSCLKOffset, usVddciDependencyOnMCLKOffset, usVddcDependencyOnMCLKOffset, usMaxClockVoltageOnDCOffset, usMvddDependencyOnMCLKOffset, usCACLeakageTableOffset, and usVddcPhaseShedLimitsTableOffset, along with their variable-length entries[] arrays, without checking pp_table_has_space().

!

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author maintainer
#61 lore raw

PATCH 1/1 Bluetooth: hci_event: fix out-of-bounds read in LE PA report reassembly

In reply to Sasha Levin

From: Laxman Acharya <[email protected]>

[ 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().

---

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 <[email protected]> (author)
- Signed-off-by: Luiz Augusto von Dentz <[email protected]> (Bluetooth maintainer applied it)
- No Fixes: tag (expected for this review)
- No Cc: [email protected] (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: [email protected]
- 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 [email protected]: 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(+)
net/bluetooth/hci_event.c +7 -0
index 23fe327a0fcd6..fd823baf64415 100644
@@ -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);
Signature · 1 line
2.53.0
author maintainer
#62 lore raw

PATCH 1/1 drm/amd/display: Fix rounding errors in CalculatePrefetchSchedule

In reply to Sasha Levin

From: Matthew Stewart <[email protected]>

[ Upstream commit fa0300333db07ca4ad56c9879f155faafd3f7079 ]

[why]

Rounding errors were causing mode validation to fail in some cases when it should not. (IE. Increasing fclk from a lower value could lead to validation failure, which should not happen.)

---

LLM Generated explanations, may be completely bogus:

Connection lost, reconnecting to https://agentn.us.api5.cursor.sh
(attempt 1)...
Retry attempt 1...
I have enough to decide: this is a small DCN4 DML prefetch-rounding fix in 7.3-rc4, and the remaining work is to write the phase-by-phase verdict.

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

Step 1.1: PARSE THE SUBJECT LINE
Record: [drm/amd/display] [Fix] [rounding errors in CalculatePrefetchSchedule causing false mode-validation failures]

Step 1.2: PARSE ALL COMMIT MESSAGE TAGS
Record:
- Reviewed-by: Dillon Varone &lt;[email protected]&gt;
- Signed-off-by: Matthew Stewart &lt;[email protected]&gt; (author)
- Signed-off-by: Fangzhi Zuo &lt;[email protected]&gt; (DC series collector)
- Tested-by: Dan Wheeler &lt;[email protected]&gt;
- Signed-off-by: Alex Deucher &lt;[email protected]&gt; (amdgpu maintainer)
- No Fixes: tag (expected)
- No Reported-by, no syzbot, no Link:, no Cc: stable
- Ignore any Sasha Levin SOB / Upstream-commit markers if present in a candidate wrapper; none are in the real commit

Step 1.3: ANALYZE THE COMMIT BODY TEXT
Record:
- Bug: rounding in the DCN4 DML21 prefetch scheduler made mode validation fail for configurations that are actually valid.
- Symptom: increasing fclk (fabric clock) from a working lower value can cause validation to fail. That is non-monotonic and should not happen.
- Failure mode: Display Core rejects a mode (PrefetchSupported / NoTimeForPrefetch), so a modeset or clock bump that should work is refused.
- No stack trace, no CVE, no named kernel version range in the message.
- Root cause (from message + comments in the diff): VM/row prefetch times are later ceiled to quarter-line units, which steals time from the swath (SW) stage. Tsw_est* did not account for that, so the wrong prefetch-bandwidth case was selected.

Step 1.4: DETECT HIDDEN BUG FIXES
Record: Not a disguised cleanup. Subject and body state a real validation bug. The three subtracted LineTime fractions are the actual fix.

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

Step 2.1: INVENTORY THE CHANGES
Record:
- File: drivers/gpu/drm/amd/display/dc/dml2_0/dml21/src/dml2_core/dml2_ core_dcn4_calcs.c
- +6 / -3 (stat of fa0300333db07)
- Function: CalculatePrefetchSchedule
- Scope: single-file surgical change to three assignments

Step 2.2: UNDERSTAND THE CODE FLOW CHANGE
Record:
- Before: Tsw_est1/2/3 = prefetch_sw_bytes / prefetch_bwN (SW time estimated with no rounding slack).
- After:
- Tsw_est1 -= 3/4 LineTime (VM +1/4, two rows +2/4)
- Tsw_est2 -= 1/4 LineTime (VM only)
- Tsw_est3 -= 2/4 LineTime (two rows)
- Affected path: DML mode-support / mode-programming prefetch bandwidth selection, not an error-path or init-only path.
- Those Tsw_est* values feed if (Tsw_estN < min_Lsw_equ * LineTime) which already subtracts 0.75 / 0.25 / 0.5 LineTime when recalculating prefetch_bw1/2/3. The initial estimate is now consistent with that later quarter-line rounding.

Step 2.3: IDENTIFY THE BUG MECHANISM
Record: [Logic / correctness] [DML prefetch time rounding]
- Later in the same function, VM and row times are ceiled to U2.2 quarter-lines:
dst_y_per_vm_vblank = ceil(4 * Tvm / LineTime) / 4 and the same for rows.
- That can consume up to +1/4 line (VM) and +1/4 line × 2 rows. SW then has less time than Tsw_est assumed, so the equalized bandwidth case is wrong and validation fails even though the mode is feasible (including after an fclk increase).
- Category is not UAF/leak/race/NULL; it is display-mode calculator incorrectness.

Step 2.4: ASSESS THE FIX QUALITY
Record:
- Quality: high. The 3/4, 1/4, 2/4 constants match the existing 0.75 / 0.25 / 0.5 LineTime terms and the documented quarter-line clamp.
- Minimal: three expressions plus comments.
- Regression risk: changing DML bandwidth can theoretically accept a mode that underflows, or reject a previously accepted one. Here the change only makes Tsw_est pessimistic so the already-margined recalculation path runs; the author states the old path rejected valid modes. Reviewed and Tested-by AMD display.
- No public API / data-structure change.

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

Step 3.1: BLAME THE CHANGED LINES
Record:
- File added as DCN401 DML21 in 70839da636050 (drm/amd/display: Add new DCN401 sources, 2024-04-26). Present from v6.11 onward.
- Surrounding Tpre_rounded / Tsw_est logic largely from be4e3509314af7 (DML21 Reintegration For Various Fixes, 2024-12-18).
- The three Tsw_est* lines are fa0300333db07 itself (2026-06-19 / committed 2026-07-28).
- Bug has been in DCN4 DML21 since that IP was added, not a last-month regression.

Step 3.2: FOLLOW THE FIXES: TAG
Record: No Fixes: tag. Not applicable. Buggy code is the original DCN4 prefetch estimator, not a one-commit regression.

Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES
Record:
- Recent file commits include DCN6 compile, PMO pstate plumbing, this fix, UCLK pstate, divide-by-zero, HDMI FRL, HostVM units.
- Follow-ups after this fix (9fcd9c7545654, 992694ad28584) do not revert or rework these three lines.
- Standalone mathematically; landed as patch 46/49 of a bulk DC drop, but the hunk has no dependency on 45/47/etc.

Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS
Record: Matthew Stewart is an AMD display engineer (DCN42B enablement, soc_bb, register masks). Not the drm/amd maintainer; Alex Deucher signed it off. Related nearby work is DCN42B, not a prerequisite for this rounding change.

Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS
Record: No extra helpers or struct fields. Can apply standalone wherever this CalculatePrefetchSchedule exists. This tree uses dml2_0/ (rename e6a8a000cfe6a, 2025-10-28); older stables still on dml2/ would only need a path tweak. No missing prerequisites in this checkout.

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

Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION
Record:
- b4 dig -c fa0300333db07 failed: lore.kernel.org returned errors.
- Found on amd-gfx: [PATCH 46/49] in “DC Patches July 20th, 2026”
- Cover: https://lists.freedesktop.org/archives/amd-

    gfx/2026-July/149310.html
  - Patch: https://lists.freedesktop.org/archives/amd-
    gfx/2026-July/149359.html

- Cover letter summary: KUnit expansion, dm refactor, Apple 5K tiled monitor, FRL/DSC, dcn42 fixes. This rounding fix is not called out as a highlight.
- Diff on the list matches the committed change. No v2/v3 of this specific patch.
- No reviewer NAK, no Cc: stable in the mail.

Step 4.2: CHECK WHO REVIEWED THE PATCH
Record: Reviewed-by Dillon Varone (DML/DCN4). Tested-by Dan Wheeler. Collected by Fangzhi Zuo, merged by Alex Deucher. Appropriate AMD display reviewers.

Step 4.3: SEARCH FOR THE BUG REPORT
Record: No user bugzilla/syzbot/lore bug report found. Evidence is AMD
internal: “some cases”, fclk monotonicity example. Severity from the
author: false mode-validation failure, not oops.

Step 4.4: CHECK FOR RELATED PATCHES AND SERIES
Record: Independent of the rest of the 49-patch DC drop (KUnit, refactors, Apple tiled display, etc.). DCN5 dml2_core_dcn5_calcs_dchub.c still uses unadjusted Tsw_est*; this fix is DCN4 DML21 only.

Step 4.5: CHECK STABLE MAILING LIST HISTORY
Record: lore.kernel.org/stable search returned 403. lists.freedesktop.org has no AUTOSEL of this subject. Unverified whether stable@ ever discussed it.

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

Step 5.1: IDENTIFY KEY FUNCTIONS IN THE DIFF
Record: CalculatePrefetchSchedule only (static in dml2_core_dcn4_calcs.c).

Step 5.2: TRACE CALLERS
Record: Two call sites in the same file:
- Mode support (~line 7645): mode_lib->ms.NoTimeForPrefetch[k] = CalculatePrefetchSchedule(...) then PrefetchSupported &= !NoTimeForPrefetch[k]
- Mode programming (~line 11473): mode_lib->mp.NoTimeToPrefetch[k] = CalculatePrefetchSchedule(...)
dml2_core_calcs_mode_support_ex is used from dml2_core_dcn4.c during DC mode validation.

Step 5.3: TRACE CALLEES
Record: Floating-point DML math (math_max2/3, math_ceil2), no alloc/lock/I/O. Pure calculator.

Step 5.4: FOLLOW THE CALL CHAIN
Record: Userspace DRM atomic modeset / DC validate → DML21 mode_support → CalculatePrefetchSchedule. Reachable on DCN4 family (DCN401/42/42B; dcn401_resource.c sets .using_dml21 = true). Not a syscall crash path; it is the normal display-mode path for those GPUs.

Step 5.5: SEARCH FOR SIMILAR PATTERNS
Record: Same unadjusted Tsw_est pattern remains in DCN5 DML21 and older VBA DML (dcn31/32/314). Not a tree-wide systematic fix; DCN4-specific.

===============================================================
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 = v7.3-rc4-27-gf0100363d8c37; make kernelversion = 7.3.0-rc4.
- File and function exist. Current tree already has the fixed Tsw_est* lines (fa0300333db07 is an ancestor of HEAD; also in v7.3-rc1).
- Bug introduced with DCN401 sources (v6.11). This 7.3 codebase includes that IP.

Step 6.2: CHECK FOR BACKPORT COMPLICATIONS
Record: Expected apply on this tree: clean (context matches). No conflicting local changes around those three assignments.

Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE
Record: No earlier alternate fix of these Tsw_est* lines. No revert. DCN5 still unfixed (different file).

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

Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY
Record: [drm/amd/display DML21 DCN4] [IMPORTANT] — not mm/core, but current AMD dGPU/APU display mode library. DCN401 is GC 12.0 (RDNA4-class). Affects all users of that display IP.

Step 7.2: ASSESS SUBSYSTEM ACTIVITY
Record: Very active (DC drops, DCN42B, DCN6). This is a calculator correction in a mature DCN4 path, not a new subsystem.

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

Step 8.1: DETERMINE WHO IS AFFECTED
Record: Driver-specific / DCN4-family AMD display (DCN401/42/42B with DML21). Not universal; not staging.

Step 8.2: DETERMINE THE TRIGGER CONDITIONS
Record: Trigger is DML prefetch scheduling during mode validation, especially near rounding boundaries and when fclk changes. Common for anyone setting modes or changing clocks on those GPUs. Unprivileged userspace can trigger via KMS modeset. Not a rare CONFIG-only path.

Step 8.3: DETERMINE THE FAILURE MODE SEVERITY
Record: [False mode validation failure / non-monotonic fclk] [MEDIUM, user-visible HIGH on affected HW]
- Not panic, UAF, deadlock, or filesystem corruption.
- Result: atomic commit / mode rejected; valid timing or a clock increase can fail. That is a real display functional bug (blank / mode not available / DPM clock bump fails), not cosmetic logging.

Step 8.4: CALCULATE RISK-BENEFIT RATIO
Record:
- Benefit: DCN4 users keep modes that should work; fclk increases remain monotonic. High for that hardware, moderate globally.
- Risk: 3-line DML tweak, internally consistent with existing margins, reviewed/tested. Low.
- Ratio: favorable.

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

Step 9.1: COMPILE THE EVIDENCE
FOR:
- Real user-visible bug: DML falsely fails prefetch/mode validation.
- Concrete symptom: raising fclk can make validation fail.
- Small, obviously correct vs quarter-line VM/row ceils already in this function.
- Reviewed-by Dillon Varone, Tested-by Dan Wheeler, SOB Alex Deucher.
- DCN4 DML21 is in this 7.3-rc4 tree; fix applies cleanly.
- Similar DML prefetch correctness patches have historically been stable material (underflow/clamp fixes).
- Standalone; no new API.

AGAINST:
- Not a crash, security hole, leak, or data-corruption bug.
- No external reporter / syzbot / Fixes: tag.
- Landed inside a 49-patch DC dump, not highlighted as a stable item.
- DML float tweaks can in principle change which modes pass; residual underflow risk is low but non-zero.
- DCN5 sibling calculator left unchanged (DCN4-only).

UNRESOLVED:
- lore.kernel.org (b4 dig and stable list) returned HTTP errors; amd-gfx archive was used instead.
- No public reproducer beyond the author’s fclk example.

Step 9.2: APPLY THE STABLE RULES CHECKLIST
1. Obviously correct and tested? PASS — quarter-line math matches existing 0.75/0.25/0.5 paths; Tested-by + Reviewed-by.
2. Fixes a real bug that affects users? PASS — false mode reject on DCN4 validation, including fclk increase.
3. Important issue? PASS — display mode / clock-validation failure on current AMD DCN4 hardware is a serious functional bug for those users (not a panic, but modeset/DPM can fail).
4. Small and contained? PASS — 6 insertions / 3 deletions, one function.
5. No new features or APIs? PASS.
6. Can apply to the local tree? PASS — file/function present; hunk matches this tree.

Step 9.3: CHECK FOR EXCEPTION CATEGORIES
Record: None of device-ID / quirk / DT / build / docs. Qualifies as a normal small correctness fix.

Step 9.4: MAKE YOUR DECISION
This tree is 7.3.0-rc4 and contains DCN4 DML21. The patch is a small, reviewed correction so prefetch time estimates match the quarter-line rounding the hardware/DML already applies. Without it, valid modes can be rejected and raising fclk can fail validation. That is a real display bug, not a feature or cleanup. Risk is low relative to the benefit for DCN4 users of this codebase.

Verification:
- [Phase 1] Parsed tags: Reviewed-by Dillon Varone; Tested-by Dan Wheeler; SOB Matthew Stewart, Fangzhi Zuo, Alex Deucher; no Fixes:/Reported-by/Cc: stable
- [Phase 2] Diff: 3 Tsw_est* assignments in CalculatePrefetchSchedule; subtract 3/4, 1/4, 2/4 LineTime
- [Phase 2] Confirmed later code ceils VM/row to quarter-lines and already uses 0.75/0.25/0.5 LineTime in the BW-update path
- [Phase 3] git merge-base --is-ancestor fa0300333db07 HEAD → yes (exit 0)
- [Phase 3] File added in 70839da636050; in v6.11+, not in v6.10; fix in v7.3-rc1+
- [Phase 3] blame: original DCN401 DML (Aurabindo Pillai) / DML21 reintegration (Austin Zheng)
- [Phase 4] b4 dig: lore server error (UNVERIFIED via b4)
- [Phase 4] amd-gfx: patch 46/49 of DC July 20 2026 (149310 cover, 149359 patch); no NAK; not Cc: stable
- [Phase 4] lore.kernel.org/stable: 403 (UNVERIFIED)
- [Phase 5] Callers: mode_support and mode_programming in the same file; PrefetchSupported &= !NoTimeForPrefetch
- [Phase 5] dcn401_resource.c .using_dml21 = true
- [Phase 6] git describe HEAD: v7.3-rc4-27-gf0100363d8c37; kernelversion 7.3.0-rc4; buggy/fixed code present
- [Phase 6] DCN5 still has unadjusted Tsw_est (different IP)
- [Phase 8] Failure mode: false DML mode validation fail, not oops
- UNVERIFIED: whether older LTS trees need a dml2/ vs dml2_0/ path tweak (out of scope for this checkout)

**YES**

 .../dc/dml2/dml21/src/dml2_core/dml2_core_dcn4_calcs.c   | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)
drivers/gpu/drm/amd/display/dc/dml2/dml21/src/dml2_core/dml2_core_dcn4_calcs.c +6 -3
index da865bd466c9a..c32b704627085 100644
@@ -5554,7 +5554,8 @@ static bool CalculatePrefetchSchedule(struct dml2_core_internal_scratch *scratch
 				+ 2 * (p->PixelPTEBytesPerRow * p->HostVMInefficiencyFactor + p->meta_row_bytes + tdlut_row_bytes)
 				+ *p->prefetch_sw_bytes)
 				/ (*p->Tpre_rounded - *p->Tno_bw);
-			s->Tsw_est1 = *p->prefetch_sw_bytes / s->prefetch_bw1;
+			/* due to rounding, VM can clamp to +1/4, Row can clamp to +2/4, giving SW less time */
+			s->Tsw_est1 = *p->prefetch_sw_bytes / s->prefetch_bw1 - 3.0 * s->LineTime / 4.0;
 		} else
 			s->prefetch_bw1 = 0;
 
@@ -5578,7 +5579,8 @@ static bool CalculatePrefetchSchedule(struct dml2_core_internal_scratch *scratch
 		if (*p->Tpre_rounded - *p->Tno_bw - 2.0 * s->Tr0_trips_rounded > 0) {
 			s->prefetch_bw2 = (vm_bytes * p->HostVMInefficiencyFactor + *p->prefetch_sw_bytes) /
 			(*p->Tpre_rounded - *p->Tno_bw - 2.0 * s->Tr0_trips_rounded);
-			s->Tsw_est2 = *p->prefetch_sw_bytes / s->prefetch_bw2;
+			/* due to rounding, VM can clamp to +1/4  */
+			s->Tsw_est2 = *p->prefetch_sw_bytes / s->prefetch_bw2 - 1.0 * s->LineTime / 4.0;
 		} else
 			s->prefetch_bw2 = 0;
 
@@ -5592,7 +5594,8 @@ static bool CalculatePrefetchSchedule(struct dml2_core_internal_scratch *scratch
 		if (*p->Tpre_rounded - s->Tvm_trips_rounded > 0) {
 			s->prefetch_bw3 = (2 * (p->PixelPTEBytesPerRow * p->HostVMInefficiencyFactor + p->meta_row_bytes + tdlut_row_bytes) + *p->prefetch_sw_bytes) /
 				(*p->Tpre_rounded - s->Tvm_trips_rounded);
-			s->Tsw_est3 = *p->prefetch_sw_bytes / s->prefetch_bw3;
+			/* due to rounding, Row can clamp to +2/4  */
+			s->Tsw_est3 = *p->prefetch_sw_bytes / s->prefetch_bw3 - 2.0 * s->LineTime / 4.0;
 		} else
 			s->prefetch_bw3 = 0;
 
Signature · 1 line
2.53.0
author maintainer
#63 lore raw

PATCH 1/1 ASoC: Intel: bytcr_rt5651: Add quirk for Chuwi Hi8 with generic DMI strings

In reply to Sasha Levin

From: Jasper Firth <[email protected]>

[ Upstream commit c5a8fc2abe05cf6db71f57ff0177fddc59861a1a ]

Some Chuwi Hi8 tablets with model number CWI513 ship with a BIOS (American Megatrends 5.11, dated 05/21/2016) whose DMI sys_vendor and product_name are both "Default string". The tested unit is labelled just "Hi8", but its model number is the same as the existing "Chuwi Hi8 Pro (CWI513)" entry, and it needs the same quirks. That entry matches on sys_vendor "Hampoo" and product_name "X1D3_C806N", so it never applies to these units.

Without its quirks the internal speaker, whose amplifier has a differential input wired across LOUT left and right, cancels to a faint distorted residual for any centred (L == R) content, and the headphone channels are swapped.

Add an entry matching board_vendor "Hampoo" and board_name "Cherry Trail CR", plus the BIOS date since those two are too generic on their own. drivers/platform/x86/touchscreen_dmi.c already matches the Chuwi HiBook the same way.

The quirks are those of the existing Hi8 Pro entry, except for the over-current detection scale factor: 1.0 instead of the 0.75 from BYT_RT5651_DEFAULT_QUIRKS. With 0.75 and a CTIA headset (inline mic and one button), loud speech into the mic, and headphone playback coupling onto the mic line, were reported as spurious KEY_PLAYPAUSE presses, one of them held for a whole 8 second speech window. With 1.0 the same test gave no spurious events, and 3 real button presses were reported as exactly 3 press/release pairs.

Tested on a unit with the generic DMI strings, with a module built from this patch and no quirk module parameter. The quirks were applied via the new entry, the card components read "cfg-spk:1 cfg-mic:in2 cfg-hp:lrswap", and the following all work: speaker, headphone left/right order, jack and headset-mic detection, headset button, and the internal and headset mics.

The problem was diagnosed with the help of an AI coding assistant, which also drafted this changelog.

---

LLM Generated explanations, may be completely bogus:

I have enough to decide: this is a DMI hardware quirk for a tablet whose audio is already broken without it, and the surrounding driver code is present in this 6.18 tree.

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

Step 1.1: PARSE THE SUBJECT LINE
Record: [ASoC/Intel/bytcr_rt5651] [Add] [DMI quirk so Chuwi Hi8 units with generic BIOS strings get the existing audio workarounds]

Step 1.2: PARSE ALL COMMIT MESSAGE TAGS
Record:
- Assisted-by: Claude Opus 5.5
- Signed-off-by: Jasper Firth \<[email protected]\> (author)
- Link: https://patch.msgid.link/20260925-hi8-quirk-v1-1-
[email protected]
- Signed-off-by: Mark Brown \<[email protected]\> (ASoC maintainer)
- No Fixes: tag (expected)
- No Reported-by / Tested-by / Reviewed-by / Acked-by
- No Cc: [email protected] (expected; not a negative)
- Ignore pipeline-added "[Upstream commit ...]" and Sasha Levin SOB

Step 1.3: ANALYZE THE COMMIT BODY TEXT
Record:
- Bug: Some Chuwi Hi8 CWI513 tablets ship AMI BIOS 5.11 dated 05/21/2016 with DMI sys_vendor and product_name both "Default string". The existing "Chuwi Hi8 Pro (CWI513)" entry matches sys_vendor "Hampoo" + product_name "X1D3_C806N" and never applies.
- Symptom: internal speaker (differential amp across LOUT L/R) cancels to a faint distorted residual for centred (L==R) content; headphone L/R swapped. With default OVCD scale 0.75, loud speech into a CTIA headset mic produced spurious KEY_PLAYPAUSE events (one held for an 8s window).
- Root cause: missing DMI match, so DEFAULT_QUIRKS (stereo path, SF 0.75) are used on hardware that needs mono-speaker mix, HP swap, and OVCD SF 1.0.
- Version info: hardware/BIOS from 2016; no kernel-version restriction stated.
- Author tested on a real unit without the quirk module parameter; card components became "cfg-spk:1 cfg-mic:in2 cfg-hp:lrswap"; speaker, HP order, jack/headset-mic, button, and both mics worked.

Step 1.4: DETECT HIDDEN BUG FIXES
Record: Not a disguised cleanup. It is an explicit hardware-quirk addition. The "add" verb here is the standard form for DMI/quirk table entries that fix broken hardware, not a new feature.

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

Step 2.1: INVENTORY THE CHANGES
Record:
- Files: sound/soc/intel/boards/bytcr_rt5651.c only (+17 / -0)
- Functions: none modified; one new dmi_system_id entry in byt_rt5651_quirk_table[]
- Scope: single-file surgical table addition

Step 2.2: UNDERSTAND THE CODE FLOW CHANGE
Record:
- Before: dmi_check_system(byt_rt5651_quirk_table) in snd_byt_rt5651_mc_probe() never matches these units, so byt_rt5651_quirk stays BYT_RT5651_DEFAULT_QUIRKS | BYT_RT5651_IN2_MAP.
- After: units with board_vendor "Hampoo", board_name "Cherry Trail CR", and BIOS date "05/21/2016" set:
MCLK_EN | JD1_1 | OVCD_TH_2000UA | OVCD_SF_1P0 | IN2_MAP | HP_LR_SWAPPED | MONO_SPEAKER
- That is the existing Hi8 Pro quirk set with OVCD scale 1.0 instead of DEFAULT_QUIRKS' 0.75.
- Path: machine-driver probe / initialization only. Callback byt_rt5651_quirk_cb still just stores driver_data and returns 1.

Step 2.3: IDENTIFY THE BUG MECHANISM
Record:
- Category: (h) hardware workaround / DMI quirk table entry
- Mechanism: without MONO_SPEAKER the stereo DAC feeds a differential mono amp and centred audio cancels (this is the same failure Hans de Goede documented in a0d1d867c262f, "Add mono speaker quirk"). Without HP_LR_SWAPPED, headphone channels are reversed. OVCD_SF_1P0 raises the headset-button over-current scale so coupled mic audio is not reported as KEY_PLAYPAUSE.

Step 2.4: ASSESS THE FIX QUALITY
Record:
- Obviously correct: additive table entry using the same callback and flag bits already used by the Hi8 Pro / Vi8 Plus entries.
- Match is deliberately narrowed with BIOS date after the author noted board_vendor+board_name are too generic; same comment/pattern as Chuwi HiBook in drivers/platform/x86/touchscreen_dmi.c.
- dmi_check_system() stops on first callback returning non-zero. Existing Hi8 Pro entry is earlier in the table, so units with proper "Hampoo"/"X1D3_C806N" strings keep the old flags.
- Residual risk: another Hampoo "Cherry Trail CR" board with BIOS date 05/21/2016 and the RT5651 machine driver could get mono/HP-swap incorrectly. BIOS date plus first-match-wins makes that small. No locking/API/data-structure changes.

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

Step 3.1: BLAME THE CHANGED LINES
Record:
- Quirk table exists since Pierre-Louis Bossart, 2016 (2bd5bd15a51858).
- Existing "Chuwi Hi8 Pro (CWI513)" match (Hampoo / X1D3_C806N) from Hans de Goede, 2018 (55d69c0309acea / 8f250e7009d71).
- MONO_SPEAKER + HP_LR_SWAPPED on that entry from 2018 (a0d1d867c262f4).
- The buggy situation is long-standing: these generic-DMI units have never matched. Introduced with the 2016 BIOS, not by a recent kernel change.

Step 3.2: FOLLOW THE FIXES: TAG
Record: No Fixes: tag. Not applicable. The "bug" is missing DMI coverage, not a regression from a tagged commit.

Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES
Record:
- Recent file history is unrelated (DAPM idle_bias, invalid quirk mapping, DPCM flags, remove() conversion).
- Original Hi8 Pro/Vi8 Plus DMI entries and all flag macros are already in this tree.
- Standalone; not patch X/Y.

Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS
Record: Only this commit by Jasper Firth under sound/soc/intel/boards/. Not a subsystem maintainer. Hans de Goede (historical author of these Chuwi entries) and Intel ASoC maintainers were on the original To/Cc. Mark Brown applied it the same day.

Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS
Record: No extra commits needed. BYT_RT5651_MCLK_EN, JD1_1, OVCD_TH_2000UA, OVCD_SF_1P0, IN2_MAP, HP_LR_SWAPPED, MONO_SPEAKER, byt_rt5651_quirk_cb, and dmi_check_system(byt_rt5651_quirk_table) all exist in v6.18.57. Can apply standalone.

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

Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION
Record:
- b4 dig -c c5a8fc2abe05cf6db71f57ff0177fddc59861a1a matched https://pat
ch.msgid.link/[email protected]
- b4 dig -a: v1 only (2026-09-25)
- Thread has two messages: submission and Mark Brown "Applied to broonie/sound.git for-7.3"
- No NAKs, no requested revisions, no reviewer Cc: stable
- Author note (not in the final commit body): left the existing Hi8 Pro entry unchanged because they do not have an X1D3_C806N unit; that model may still see OVCD_SF_0P75 spurious buttons. This patch does not change that entry.

Step 4.2: CHECK WHO REVIEWED THE PATCH
Record (b4 dig -w): linux-sound, linux-kernel, Mark Brown, Takashi Iwai, Jaroslav Kysela, Hans de Goede, Pierre-Louis Bossart, Liam Girdwood, Cezary Rojewski, Bard Liao, Kai Vehmanen, Peter Ujfalusi. Subsystem maintainer applied it. No extra Reviewed-by.

Step 4.3: SEARCH FOR THE BUG REPORT
Record: No syzbot/bugzilla link. Evidence is the author's hardware test in the changelog (speaker cancellation, swapped HP, spurious KEY_PLAYPAUSE, and post-fix verification).

Step 4.4: CHECK FOR RELATED PATCHES AND SERIES
Record: Single standalone patch, change-id 20260925-hi8-quirk-00ca3a49b32f. No series dependencies.

Step 4.5: CHECK STABLE MAILING LIST HISTORY
Record: Web search of lore.kernel.org/stable for this subject/file found no discussion of this quirk. Nobody requested or rejected it for stable in a thread I could verify.

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

Step 5.1: IDENTIFY KEY FUNCTIONS IN THE DIFF
Record: No function bodies changed. Data consumed by byt_rt5651_quirk_cb() and snd_byt_rt5651_mc_probe().

Step 5.2: TRACE CALLERS
Record:
- byt_rt5651_quirk_cb is only used as .callback in this DMI table.
- dmi_check_system(byt_rt5651_quirk_table) is called once from snd_byt_rt5651_mc_probe() (line 1024).
- That probe is the platform driver bytcr_rt5651 (MODULE_ALIAS("platform:bytcr_rt5651")).
- Context: device probe, not IRQ/hot path. Userspace cannot call it directly; it runs when this Bay Trail / Cherry Trail RT5651 machine driver binds.

Step 5.3: TRACE CALLEES
Record: Callback only assigns byt_rt5651_quirk. Probe later uses those bits for codec device properties, card components (cfg-spk:1, cfg- hp:lrswap), long_name, and jack OVCD settings. No new allocations or locks.

Step 5.4: FOLLOW THE CALL CHAIN
Record: ACPI/platform match → snd_byt_rt5651_mc_probe → dmi_check_system → quirk flags → ALSA card registration / UCM profile selection. Reachable on this tablet at every boot if CONFIG_SND_SOC_INTEL_BYTCR_RT5651_MACH is enabled (recommended in Kconfig for such devices). Not a syscall-triggered crash path.

Step 5.5: SEARCH FOR SIMILAR PATTERNS
Record: Same Hampoo + "Cherry Trail CR" + BIOS-date pattern already used for Chuwi HiBook in touchscreen_dmi.c (BIOS date 05/07/2016, different from 05/21/2016). Sibling Hi8 Pro / Vi8 Plus audio entries already exist in this same table. VIOS LTH17 already uses BYT_RT5651_OVCD_SF_1P0.

===============================================================
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 = v6.18.57-155-gcdf239ca885b2; make kernelversion = 6.18.57.
- File and quirk table exist at v6.18.57. Existing Hi8 Pro entry is present; generic-DMI units still miss it.
- Bug is missing coverage, present for as long as this driver has been used on these 2016 tablets.

Step 6.2: CHECK FOR BACKPORT COMPLICATIONS
Record: Against v6.18.57 the hunk applied with a 1-line offset (Hunk #1 succeeded at 409). Context around the Hi8 Pro entry is identical. Expected difficulty: clean apply / trivial offset. All flag macros exist unchanged.

Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE
Record: git log v6.18..v6.18.57 -- sound/soc/intel/boards/bytcr_rt5651.c is empty; 6.18.y has not already taken a different fix for this. No "generic DMI" match exists without this entry. Existing Hi8 Pro match does not cover "Default string" vendor/product.

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

Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY
Record: [sound/soc/intel/boards – Intel Baytrail/Cherry Trail ASoC machine driver] [PERIPHERAL / driver-specific, but a supported in-tree board driver, not staging]

Step 7.2: ASSESS SUBSYSTEM ACTIVITY
Record: Mature. Quirk table dates to 2016–2018; recent commits are small maintenance. This is a late hardware-coverage add, not a rewrite of new code.

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

Step 8.1: DETERMINE WHO IS AFFECTED
Record: Driver-specific / DMI-specific. Only Chuwi Hi8 CWI513-class units with board_vendor Hampoo, board_name "Cherry Trail CR", BIOS date 05/21/2016, using this RT5651 machine driver. Other users are unchanged unless they share that exact triple (unverified but constrained).

Step 8.2: DETERMINE THE TRIGGER CONDITIONS
Record: Every probe/boot on matching hardware. No race. Unprivileged users do not trigger a kernel bug; they just get broken audio / spurious KEY_PLAYPAUSE until the quirk is applied.

Step 8.3: DETERMINE THE FAILURE MODE SEVERITY
Record:
- Failure: internal speaker effectively unusable for typical centred content; swapped headphones; false headset-button events.
- Severity: MEDIUM for the affected device (real functional break, not a panic). Not CRITICAL in the crash/corruption sense, but it is the class of hardware-quirk issue stable trees routinely take.

Step 8.4: CALCULATE RISK-BENEFIT RATIO
Record:
- Benefit: high for owners of this tablet (speaker/headphones/jack actually work); zero for everyone else if the DMI triple is unique.
- Risk: very low — 17-line table add, existing flags, probe-time only, first-match preserves the older Hi8 Pro entry.
- Ratio: favorable.

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

Step 9.1: COMPILE THE EVIDENCE
FOR:
- Real hardware bug: differential mono speaker cancellation, swapped HP, spurious KEY_PLAYPAUSE
- Author tested on the affected unit; quirks applied without module- parameter override
- Textbook stable exception: DMI/hardware quirk on an existing driver
- Small (+17), contained, no new API
- All consumed flags and the table hook exist in this 6.18.57 tree
- Applies with a trivial offset
- Same matching strategy already used for Chuwi HiBook
- ASoC maintainer applied v1 the same day; Intel ASoC and Hans de Goede were CC'd
- Existing more-specific Hi8 Pro entry remains first and still wins for X1D3_C806N units

AGAINST:
- Niche 2016 tablet, one reporter/tester
- Not a crash, security hole, or data-corruption bug
- Theoretical false match on another Hampoo Cherry Trail CR board with the same BIOS date
- No Fixes:/Cc: stable; Mark Brown queued it for the 7.3 merge window rather than as an urgent fix

UNRESOLVED:
- Could not fetch lore.kernel.org HTML (403); thread reconstructed via b4 dig + Patchew + LKML archive
- Could not prove no other product shares Hampoo + "Cherry Trail CR" + BIOS 05/21/2016
- No stable-list thread found

Step 9.2: APPLY THE STABLE RULES CHECKLIST
1. Obviously correct and tested? PASS — additive DMI entry, author hardware test, maintainer applied
2. Fixes a real bug that affects users? PASS — broken speaker/HP/jack on a shipping tablet
3. Important issue? PASS under the hardware-quirk exception (device unusable audio, not a panic)
4. Small and contained? PASS — +17 lines, one table entry
5. No new features or APIs? PASS — existing quirk flags only
6. Can apply to the local tree? PASS — driver + flags present; hunk applies to v6.18.57

Step 9.3: CHECK FOR EXCEPTION CATEGORIES
Record: Hardware quirk / DMI workaround on an existing driver. This is an allowed stable exception.

Step 9.4: MAKE YOUR DECISION
This is a small, tested DMI quirk that makes existing Chuwi Hi8 hardware work on this 6.18 tree. Benefit is real for those units; regression surface is limited to an already-narrow DMI triple. It should be backported.

Verification:
- [Phase 1] Parsed subject/tags/body from git show 80c7d7ab1fe03 / upstream c5a8fc2abe05; no Fixes:/syzbot/Cc: stable; Link to msgid
- [Phase 2] Diff is +17 lines in byt_rt5651_quirk_table[] only; compared flags to BYT_RT5651_DEFAULT_QUIRKS (diff is OVCD_SF_1P0 vs 0.75)
- [Phase 2] Confirmed dmi_check_system() stops when callback returns non-zero (drivers/firmware/dmi_scan.c)
- [Phase 3] git blame -L 399,423 v6.18.57 -- sound/soc/intel/boards/bytcr_rt5651.c: Hi8 Pro entry from 2018 Hans de Goede
- [Phase 3] git show a0d1d867c262f: MONO_SPEAKER exists because stereo mix on a mono amp garbles centred audio
- [Phase 3] git log --oneline --author='Jasper Firth' -- sound/soc/intel/boards/: only this commit
- [Phase 3] Flag macros present in git show v6.18.57:sound/soc/intel/boards/bytcr_rt5651.c
- [Phase 4] b4 dig -c c5a8fc2abe05... → lore msgid; -a v1 only; -w ASoC/Intel/Hans de Goede CCs; -m two-message thread, Mark Brown applied, no NAK
- [Phase 4] Patchew and LKML copies of the patch and apply mail
- [Phase 4] Stable-list search did not find this subject
- [Phase 5] dmi_check_system call at line 1024 of snd_byt_rt5651_mc_probe; platform driver bytcr_rt5651
- [Phase 5] HiBook analog in touchscreen_dmi.c lines 1197–1204 (Hampoo
+ Cherry Trail CR + BIOS date)
- [Phase 6] git describe HEAD v6.18.57-155-gcdf239ca885b2; make kernelversion 6.18.57
- [Phase 6] git show v6.18.57:... has Hi8 Pro then Vi8 Plus; patch dry-run succeeded at line 409 (offset -1)
- [Phase 6] git log v6.18..v6.18.57 -- sound/soc/intel/boards/bytcr_rt5651.c empty — no prior alternate fix
- [Phase 8] Failure mode from commit text + MONO_SPEAKER history: broken speaker/HP/button, not oops
- UNVERIFIED: uniqueness of the DMI triple across all Hampoo Cherry Trail products; lore.kernel.org HTML (403)

**YES**

 sound/soc/intel/boards/bytcr_rt5651.c | 17 +++++++++++++++++
 1 file changed, 17 insertions(+)
sound/soc/intel/boards/bytcr_rt5651.c +17 -0
index ca540a66f22ce..723acb58e248e 100644
@@ -409,6 +409,23 @@ static const struct dmi_system_id byt_rt5651_quirk_table[] = {
 					BYT_RT5651_HP_LR_SWAPPED |
 					BYT_RT5651_MONO_SPEAKER),
 	},
+	{
+		/* Chuwi Hi8 (CWI513) with a BIOS using generic DMI strings */
+		.callback = byt_rt5651_quirk_cb,
+		.matches = {
+			DMI_MATCH(DMI_BOARD_VENDOR, "Hampoo"),
+			DMI_MATCH(DMI_BOARD_NAME, "Cherry Trail CR"),
+			/* Above matches are too generic, add bios-date match */
+			DMI_MATCH(DMI_BIOS_DATE, "05/21/2016"),
+		},
+		.driver_data = (void *)(BYT_RT5651_MCLK_EN |
+					BYT_RT5651_JD1_1 |
+					BYT_RT5651_OVCD_TH_2000UA |
+					BYT_RT5651_OVCD_SF_1P0 |
+					BYT_RT5651_IN2_MAP |
+					BYT_RT5651_HP_LR_SWAPPED |
+					BYT_RT5651_MONO_SPEAKER),
+	},
 	{
 		/* Chuwi Vi8 Plus (CWI519) */
 		.callback = byt_rt5651_quirk_cb,
Signature · 1 line
2.53.0
author maintainer
#64 lore raw

PATCH 1/1 drm/amdgpu: Validate ATIF buffer length before use

In reply to Sasha Levin

From: Lijo Lazar <[email protected]>

[ Upstream commit b978b7d43963bbb3e2d850288f7c21ac11c3b751 ]

Add a min_size parameter to amdgpu_atif_call() to validate that the returned ACPI buffer is of type ACPI_TYPE_BUFFER, holds at least a u16 size field, does not claim more data than was actually returned, and meets the minimum size required by the calling function. Each caller passes its required minimum via sizeof() or offsetof() of the expected output struct and drops its own size check.

Assisted-by Claude Sonnet (Cursor AI)

---

LLM Generated explanations, may be completely bogus:

This is a firmware-buffer bounds check in amdgpu_atif_call(). On this 6.18.53 tree the buggy path is still present, the patch is small, and it closes a real out-of-bounds read.

## PHASE 1: COMMIT MESSAGE FORENSICS

**Step 1.1: PARSE THE SUBJECT LINE**
Record: [drm/amdgpu] [Validate] Validate ATIF buffer length before use

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**
Record:
- Signed-off-by: Lijo Lazar <[email protected]> (author)
- Assisted-by: Claude Sonnet (Cursor AI)
- Acked-by: Alex Deucher <[email protected]> (amdgpu maintainer)
- Signed-off-by: Alex Deucher <[email protected]>
- No Fixes:, Reported-by:, Tested-by:, Cc: stable, or syzbot tags (absence expected)
- Upstream SHA from the candidate wrapper:
b978b7d43963bbb3e2d850288f7c21ac11c3b751 (ignored as a selection marker; used only to find the original discussion)

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**
Record:
- Bug: ACPI ATIF responses are used without checking that the returned buffer actually contains the u16 size field, that the BIOS-reported size does not exceed the ACPI object length, or that the payload meets the caller’s minimum.
- Symptom/failure mode: out-of-bounds read (and possible oops) when firmware returns a short or lying buffer, then callers memcpy() using the claimed size.
- Version info: none in the message. The pattern dates to d38ceaf99ed0 (“drm/amdgpu: add core driver (v4)”, 2015).
- Root cause: callers trusted *(u16 *)info->buffer.pointer and copied that many bytes without comparing it to obj->buffer.length.

**Step 1.4: DETECT HIDDEN BUG FIXES**
Record: This is an explicit memory-safety fix, not cleanup. Centralizing existing per-caller size < N checks is incidental; the new actual >= sizeof(u16) and actual >= claimed tests are the real fix.

## PHASE 2: DIFF ANALYSIS

**Step 2.1: INVENTORY THE CHANGES**
Record:
- File: drivers/gpu/drm/amd/amdgpu/amdgpu_acpi.c (+34/−34)
- Functions: amdgpu_atif_call, amdgpu_atif_verify_interface, amdgpu_atif_get_notification_params, amdgpu_atif_query_backlight_caps, amdgpu_atif_get_sbios_requests
- Scope: single-file surgical fix

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**
Record (v6.18.53 before → after):
- amdgpu_atif_call(): after confirming ACPI_TYPE_BUFFER, return the object. After: reject length < sizeof(u16), claimed size > actual length, or claimed size < min_size.
- Callers: pass sizeof() / offsetof() as min_size and drop their own size < 12/10/10/0xd checks. memcpy still uses min(sizeof(struct), claimed_size), now only after those checks.

Verified struct sizes in drivers/gpu/drm/amd/include/amd_acpi.h (__packed):
- sizeof(atif_verify_interface) = 12 (replaces size < 12)
- offsetof(atif_system_params, command_code) = 10 (replaces size < 10; the size < 11 command_code path remains)
- offsetof(atif_qbtc_output, data_points) = 10 (replaces size < 10)
- sizeof(atif_sbios_requests) = 13 = 0xd (replaces size < 0xd)

**Step 2.3: IDENTIFY THE BUG MECHANISM**
Record: [Memory safety / OOB] [Firmware-controlled size used as memcpy length]

v6.18.53 callers still do:

```
size = *(u16 *)info->buffer.pointer;
size = min(sizeof(output), size);
memcpy(&output, info->buffer.pointer, size);
```

If obj->buffer.length is 0 or 1, the u16 load is already OOB. If claimed size is 12 and actual length is 4, memcpy copies 12 bytes from a 4-byte ACPI payload (heap OOB read). c9b7c809b89f2 only checked object type, not length; that hole is still in this tree.

**Step 2.4: ASSESS THE FIX QUALITY**
Record: Obviously correct. Rejecting claimed > actual can disable ATIF on a BIOS that lies about size but still returned enough bytes; that is malformed firmware, and the fallback is “ATIF unused” rather than a crash. Error codes change from -EINVAL to -EIO on undersized buffers; callers only test if (ret) / disable the feature. Low regression risk.

## PHASE 3: GIT HISTORY INVESTIGATION

**Step 3.1: BLAME THE CHANGED LINES**
Record: Size-then-memcpy logic is from d38ceaf99ed0 (Alex Deucher, 2015, “drm/amdgpu: add core driver (v4)”). Type check added by c9b7c809b89f2 (2024). NULL-on-AE_NOT_FOUND fixed by 91c9e221fe255 (2024). Length vs claimed size was never checked.

**Step 3.2: FOLLOW THE FIXES: TAG**
Record: No Fixes: tag. The bug is in original ATIF parsing, present since 2015. Both d38ceaf99ed0 and c9b7c809b89f2 are ancestors of v6.18.53.

**Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES**
Record:
- c9b7c809b89f2 “Guard against bad data for ATIF ACPI method” — real oops in amdgpu_atif_query_backlight_caps; later tagged CVE-2024-50117; already in this tree.
- 91c9e221fe255 — NULL deref if ATIF missing; already in this tree.
- Sibling 9d367fab451d9 “Validate ATPX buffer length before use” is patch 2/2 on a different file; not a prerequisite.
- No later commits on this file after the candidate that rework the same logic.

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**
Record: Lijo Lazar is a regular AMD amdgpu contributor (ATPX/ATRM/XCP bounds checks in the same wave). Maintainer Acked-by/SOB from Alex Deucher.

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS**
Record: Standalone. amdgpu_atif_call is static with four local callers, all updated. No new helpers. ATPX 2/2 is independent.

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**
Record:
- b4 dig -c b978b7d43963... failed (lore.kernel.org returned errors).
- Original submission: [PATCH 1/2] drm/amdgpu: Validate ATIF buffer length before use, 14 Jun 2026, https://www.mail-archive.com/amd-
[email protected]/msg145004.html
- Series: 1/2 ATIF, 2/2 ATPX. No v2 found.
- No NAKs found. Merged via Alex Deucher’s drm-next-7.3 pull; Dave Airlie acked the pull.

**Step 4.2: CHECK WHO REVIEWED THE PATCH**
Record: Posted to amd-gfx. Acked/signed by Alex Deucher. Recipients from b4 dig -w could not be retrieved (lore 403).

**Step 4.3: SEARCH FOR THE BUG REPORT**
Record: This commit has no new user report. The related 2024 ATIF bad- data oops (c9b7c809b89f2) was hit on at least one system and became CVE-2024-50117. That earlier fix did not validate lengths.

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**
Record: 1/2 of ATIF+ATPX ACPI buffer validation. ATRM buffer checks in the same author batch. ATIF is self-contained.

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**
Record: lore.kernel.org/stable search returned 403. No verified stable- list discussion. Prior ATIF guard *was* taken into stable (CVE-2024-50117).

## PHASE 5: CODE SEMANTIC ANALYSIS

**Step 5.1: IDENTIFY KEY FUNCTIONS**
Record: amdgpu_atif_call plus the four callers listed above. No semcode tools available.

**Step 5.2: TRACE CALLERS**
Record:
- amdgpu_atif_verify_interface ← amdgpu_atif_pci_probe_handle ← amdgpu_acpi_detect ← amdgpu_drv.c (driver load)
- amdgpu_atif_get_notification_params / amdgpu_atif_query_backlight_caps ← amdgpu_acpi_detect
- amdgpu_atif_get_sbios_requests ← amdgpu_atif_handler ← ACPI notifier (amdgpu_acpi_event) on brightness/hotplug-style events

**Step 5.3: TRACE CALLEES**
Record: acpi_evaluate_object, then memcpy of firmware bytes into stack structs.

**Step 5.4: FOLLOW THE CALL CHAIN**
Record: Reached on every amdgpu load when the GPU’s ACPI node has ATIF (common on AMD laptops/APUs). SBIOS request path runs on ACPI video notifies. Unprivileged userspace cannot call ATIF directly; a guest/VM with a crafted ACPI table can. Firmware bugs have already crashed this path.

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**
Record: Same claimed-size-then-memcpy pattern remains in amdgpu_atcs_call callers in this file and in radeon_acpi.c. This patch does not touch those; not a reason to reject the ATIF fix.

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

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?**
Record: Local tree is **6.18.53** (v6.18.53-5049-g0f0bdc2b0dffb, branch autosel). git merge-base --is-ancestor c8373721c3e54 v6.18.53 is false. v6.18.53:drivers/gpu/drm/amd/amdgpu/amdgpu_acpi.c still has the unvalidated *(u16 *) / memcpy sequence. Bug introduced in 2015 (d38ceaf99ed0).

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**
Record: git diff v6.18.53 c8373721c3e54 -- drivers/gpu/drm/amd/amdgpu/amdgpu_acpi.c is exactly this commit (+34/−34). Mainline noinline_for_stack is not in 6.18; the candidate as it exists here already matches 6.18. Clean apply.

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**
Record: Type/NULL guards (c9b7c809b89f2, 91c9e221fe255) are in 6.18.53. Length validation is not. No alternate fix.

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

**Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY**
Record: [drm/amdgpu ACPI/ATIF] [IMPORTANT] — not core mm/net, but a widely used GPU driver on AMD laptops.

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**
Record: Actively developed; this ATIF parsing has been stable since 2015 aside from the 2024 type/NULL guards.

## PHASE 8: IMPACT AND RISK ASSESSMENT

**Step 8.1: DETERMINE WHO IS AFFECTED**
Record: AMD GPU systems whose ACPI provides ATIF (typical AMD laptop/APU). Config: CONFIG_DRM_AMDGPU.

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**
Record: Driver probe always; ACPI notifies for SBIOS requests. Needs a short or lying ATIF buffer. Unprivileged userspace cannot trigger it on bare metal; firmware/VM ACPI can. Prior ATIF bad-data crashes were seen in the wild.

**Step 8.3: DETERMINE THE FAILURE MODE SEVERITY**
Record: [OOB read → possible oops / info leak] [HIGH] Same class as CVE-2024-50117, remaining hole.

**Step 8.4: CALCULATE RISK-BENEFIT RATIO**
Record: Benefit high (closes firmware OOB on a common driver). Risk low (~30-line single-file change, fail-closed). Ratio favors backport.

## PHASE 9: FINAL SYNTHESIS

**Step 9.1: COMPILE THE EVIDENCE**

FOR:
- Real OOB: claimed ATIF size used as memcpy length without comparing to ACPI buffer length.
- Same subsystem already produced a stable/CVE oops from unvalidated ATIF data (c9b7c809b89f2 / CVE-2024-50117); that patch did not check lengths.
- Buggy code is in this 6.18.53 tree since 2015.
- Small, contained, no new API; maintainer Acked-by.
- Applies cleanly here.
- Failure is crash/OOB, not a feature change.

AGAINST:
- No dedicated report for *this* length mismatch (hardening of a known- bad path).
- Undersized-buffer errno changes -EINVAL → -EIO (callers treat both as failure).
- Sibling ATPX patch is separate and not required.

UNRESOLVED:
- b4 dig / lore.kernel.org returned errors; discussion recovered from mail-archive.
- No stable@ thread found (lore 403).

**Step 9.2: APPLY THE STABLE RULES CHECKLIST**
1. Obviously correct and tested? **PASS** — checks match existing minima; maintainer merged.
2. Fixes a real bug that affects users? **PASS** — OOB on malformed ATIF; ATIF bad data already crashed systems.
3. Important issue? **PASS** — HIGH: OOB read / oops from firmware data.
4. Small and contained? **PASS** — one file, +34/−34.
5. No new features or APIs? **PASS** — static helper only.
6. Can apply to the local tree? **PASS** — identical to v6.18.53 file plus this diff.

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

**Step 9.4: MAKE YOUR DECISION**
Backport. It closes a leftover ATIF buffer-length hole on this 6.18 tree with a small, fail-closed change.

### What the commit solves for stable users
On 6.18, amdgpu_atif_call() only rejects non-buffer ACPI objects. Callers then trust a BIOS u16 size and memcpy that many bytes. A short or inflated ATIF payload over-reads kernel heap and can oops — the same ATIF path that already oopsed in 2024. This patch requires actual length ≥ 2, actual ≥ claimed, and claimed ≥ caller minimum before any copy.

### Risk vs benefit
Benefit is preventing oops/OOB on AMD systems with ATIF. Risk is disabling ATIF on lying firmware instead of crashing. That is the right stable tradeoff.

### Concerns
ATPX 2/2 is not required. ATCS/radeon still have the old pattern; out of scope. No extra 6.18 prerequisites.

Verification:
- [Phase 1] Tags: author SOB, Claude Assisted-by, Alex Deucher Acked- by/SOB; no Fixes/Reported-by/syzbot
- [Phase 2] Diff: +34/−34 in amdgpu_acpi.c; length checks in amdgpu_atif_call; callers pass sizeof/offsetof
- [Phase 2] Struct sizes: 12, offsetof 10, offsetof 10, 13 match old magic constants
- [Phase 3] blame: size/memcpy from d38ceaf99ed0 (2015); type check c9b7c809b89f2 (in 6.18.53)
- [Phase 3] git merge-base --is-ancestor d38ceaf99ed0 v6.18.53 true; c9b7c809b89f2 true; this commit false
- [Phase 3] ATPX sibling 9d367fab451d9 is a different file; not a dependency
- [Phase 4] b4 dig failed (lore error). Thread: mail-archive msg145004, series 1/2. Pulled in drm-next-7.3
- [Phase 4] lore/stable 403; UNVERIFIED whether stable@ discussed this SHA
- [Phase 5] Callers: probe via amdgpu_acpi_detect, ACPI notify via amdgpu_atif_handler
- [Phase 6] git describe HEAD → v6.18.53-5049-g0f0bdc2b0dffb; Makefile 6.18.53
- [Phase 6] git diff v6.18.53 <commit> -- amdgpu_acpi.c equals this patch (clean apply)
- [Phase 8] Failure mode: heap OOB read / oops; severity HIGH
- UNVERIFIED: exact To/Cc list (b4 dig -w unavailable)

**YES**

 drivers/gpu/drm/amd/amdgpu/amdgpu_acpi.c | 68 ++++++++++++------------
 1 file changed, 34 insertions(+), 34 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_acpi.c +34 -34
index 36f429e7f2027..5a04c20a5fd15 100644
@@ -138,13 +138,15 @@ static struct amdgpu_acpi_priv {
  * @atif: atif structure
  * @function: the ATIF function to execute
  * @params: ATIF function params
+ * @min_size: minimum size of the expected output buffer in bytes
  *
  * Executes the requested ATIF function (all asics).
  * Returns a pointer to the acpi output buffer.
  */
 static union acpi_object *amdgpu_atif_call(struct amdgpu_atif *atif,
 					   int function,
-					   struct acpi_buffer *params)
+					   struct acpi_buffer *params,
+					   size_t min_size)
 {
 	acpi_status status;
 	union acpi_object *obj;
@@ -187,6 +189,28 @@ static union acpi_object *amdgpu_atif_call(struct amdgpu_atif *atif,
 		return NULL;
 	}
 
+	if (obj->buffer.length < sizeof(u16)) {
+		DRM_DEBUG_DRIVER("ATIF buffer too small to hold size field: %u\n",
+				 obj->buffer.length);
+		kfree(obj);
+		return NULL;
+	}
+
+	if (obj->buffer.length < *(u16 *)obj->buffer.pointer) {
+		DRM_DEBUG_DRIVER("ATIF buffer length mismatch: reported %u, actual %u\n",
+				 *(u16 *)obj->buffer.pointer,
+				 obj->buffer.length);
+		kfree(obj);
+		return NULL;
+	}
+
+	if (*(u16 *)obj->buffer.pointer < min_size) {
+		DRM_DEBUG_DRIVER("ATIF buffer too small: expected %zu, got %u\n",
+				 min_size, *(u16 *)obj->buffer.pointer);
+		kfree(obj);
+		return NULL;
+	}
+
 	return obj;
 }
 
@@ -248,19 +272,14 @@ static int amdgpu_atif_verify_interface(struct amdgpu_atif *atif)
 	size_t size;
 	int err = 0;
 
-	info = amdgpu_atif_call(atif, ATIF_FUNCTION_VERIFY_INTERFACE, NULL);
+	info = amdgpu_atif_call(atif, ATIF_FUNCTION_VERIFY_INTERFACE, NULL,
+				sizeof(output));
 	if (!info)
 		return -EIO;
 
 	memset(&output, 0, sizeof(output));
 
-	size = *(u16 *) info->buffer.pointer;
-	if (size < 12) {
-		DRM_INFO("ATIF buffer is too small: %zu\n", size);
-		err = -EINVAL;
-		goto out;
-	}
-	size = min(sizeof(output), size);
+	size = min(sizeof(output), (size_t)*(u16 *)info->buffer.pointer);
 
 	memcpy(&output, info->buffer.pointer, size);
 
@@ -270,7 +289,6 @@ static int amdgpu_atif_verify_interface(struct amdgpu_atif *atif)
 	amdgpu_atif_parse_notification(&atif->notifications, output.notification_mask);
 	amdgpu_atif_parse_functions(&atif->functions, output.function_bits);
 
-out:
 	kfree(info);
 	return err;
 }
@@ -295,20 +313,14 @@ static int amdgpu_atif_get_notification_params(struct amdgpu_atif *atif)
 	int err = 0;
 
 	info = amdgpu_atif_call(atif, ATIF_FUNCTION_GET_SYSTEM_PARAMETERS,
-				NULL);
+				NULL, offsetof(struct atif_system_params, command_code));
 	if (!info) {
 		err = -EIO;
 		goto out;
 	}
 
-	size = *(u16 *) info->buffer.pointer;
-	if (size < 10) {
-		err = -EINVAL;
-		goto out;
-	}
-
 	memset(&params, 0, sizeof(params));
-	size = min(sizeof(params), size);
+	size = min(sizeof(params), (size_t)*(u16 *)info->buffer.pointer);
 	memcpy(&params, info->buffer.pointer, size);
 
 	DRM_DEBUG_DRIVER("SYSTEM_PARAMS: mask = %#x, flags = %#x\n",
@@ -371,20 +383,14 @@ static int amdgpu_atif_query_backlight_caps(struct amdgpu_atif *atif)
 
 	info = amdgpu_atif_call(atif,
 		ATIF_FUNCTION_QUERY_BRIGHTNESS_TRANSFER_CHARACTERISTICS,
-		&params);
+		&params, offsetof(struct atif_qbtc_output, data_points));
 	if (!info) {
 		err = -EIO;
 		goto out;
 	}
 
-	size = *(u16 *) info->buffer.pointer;
-	if (size < 10) {
-		err = -EINVAL;
-		goto out;
-	}
-
 	memset(&characteristics, 0, sizeof(characteristics));
-	size = min(sizeof(characteristics), size);
+	size = min(sizeof(characteristics), (size_t)*(u16 *)info->buffer.pointer);
 	memcpy(&characteristics, info->buffer.pointer, size);
 
 	atif->backlight_caps.caps_valid = true;
@@ -422,24 +428,18 @@ static int amdgpu_atif_get_sbios_requests(struct amdgpu_atif *atif,
 	int count = 0;
 
 	info = amdgpu_atif_call(atif, ATIF_FUNCTION_GET_SYSTEM_BIOS_REQUESTS,
-				NULL);
+				NULL, sizeof(*req));
 	if (!info)
 		return -EIO;
 
-	size = *(u16 *)info->buffer.pointer;
-	if (size < 0xd) {
-		count = -EINVAL;
-		goto out;
-	}
 	memset(req, 0, sizeof(*req));
 
-	size = min(sizeof(*req), size);
+	size = min(sizeof(*req), (size_t)*(u16 *)info->buffer.pointer);
 	memcpy(req, info->buffer.pointer, size);
 	DRM_DEBUG_DRIVER("SBIOS pending requests: %#x\n", req->pending);
 
 	count = hweight32(req->pending);
 
-out:
 	kfree(info);
 	return count;
 }
Signature · 1 line
2.53.0
#65 lore raw

Re: [PATCH AUTOSEL 6.18-5.10] drm/amdgpu: Validate ATIF buffer length before use

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] drm/amdgpu: unvalidated number_of_points in amdgpu_atif_query_backlight_caps() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] drm/amdgpu: unvalidated number_of_points in amdgpu_atif_query_backlight_caps() --

commit a73a09a7b2fb3e5ffd26ffc3c59fb52e0414b2a7
Author: Lijo Lazar <[email protected]>

drm/amdgpu: Validate ATIF buffer length before use

This commit adds a min_size parameter to amdgpu_atif_call() to validate that the returned ACPI buffer is of type ACPI_TYPE_BUFFER, holds at least a u16 size field, does not claim more data than was actually returned, and meets the minimum size required by each calling function.

Quoted 4 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_acpi.c +0 -0
index 6c62e27b98002..5be40c781807a 100644

[ ... ]

Quoted 13 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_acpi.c +1 -3
@@ -371,20 +383,14 @@ static int amdgpu_atif_query_backlight_caps(struct amdgpu_atif *atif)
 
 	info = amdgpu_atif_call(atif,
 		ATIF_FUNCTION_QUERY_BRIGHTNESS_TRANSFER_CHARACTERISTICS,
-		&params);
+		&params, offsetof(struct atif_qbtc_output, data_points));
 	if (!info) {
 		err = -EIO;
 		goto out;
 	}
 
-	size = *(u16 *) info->buffer.pointer;
-	if (size < 10) {

drivers/gpu/drm/amd/amdgpu/amdgpu_acpi.c static int amdgpu_atif_query_backlight_caps(struct amdgpu_atif *atif) · line 396

Quoted 10 lines
drivers/gpu/drm/amd/amdgpu/amdgpu_acpi.c +1 -5
-		err = -EINVAL;
-		goto out;
-	}
-
 	memset(&characteristics, 0, sizeof(characteristics));
-	size = min(sizeof(characteristics), size);
+	size = min(sizeof(characteristics), (size_t)*(u16 *)info->buffer.pointer);
 	memcpy(&characteristics, info->buffer.pointer, size);
 
 	atif->backlight_caps.caps_valid = true;

[Severity: High]
Should amdgpu_atif_query_backlight_caps() also validate characteristics.number_of_points against ATIF_QBTC_MAX_DATA_POINTS and the returned buffer size?

Right after this hunk in drivers/gpu/drm/amd/amdgpu/amdgpu_acpi.c, amdgpu_atif_query_backlight_caps() stores characteristics.number_of_points (a u8) directly into atif->backlight_caps.data_points:

	atif->backlight_caps.data_points = characteristics.number_of_points;
	memcpy(atif->backlight_caps.luminance_data,
	       characteristics.data_points,
	       sizeof(atif->backlight_caps.luminance_data));

Because amdgpu_atif_call() only validates that the buffer is at least offsetof(struct atif_qbtc_output, data_points) bytes, a malformed ATIF response can report characteristics.number_of_points greater than ATIF_QBTC_MAX_DATA_POINTS (99), or report more data points than are actually present in the returned buffer size.

When backlight brightness is later updated via:

amdgpu_dm_backlight_update_status() ->

    amdgpu_dm_backlight_set_level() ->
      convert_brightness_from_user() ->
        convert_custom_brightness()

drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm.c:convert_custom_brightness() uses caps->data_points to index caps->luminance_data[MAX_LUMINANCE_DATA_POINTS] without clamping:

	left = 0;
	right = caps->data_points - 1;
	while (left <= right) {
		int mid = left + (right - left) / 2;
		u8 signal = caps->luminance_data[mid].input_signal;

Could this read out of bounds of caps->luminance_data[] when characteristics.number_of_points exceeds ATIF_QBTC_MAX_DATA_POINTS, or read zero-padded entries if size is smaller than
offsetof(struct atif_qbtc_output, data_points) + characteristics.number_of_points * sizeof(struct atif_qbtc_data_point)?

[ ... ]

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author maintainer
#66 lore raw

PATCH 1/1 wifi: iwlwifi: support TTL platform device ID

In reply to Sasha Levin

From: Miri Korenblit <[email protected]>

[ Upstream commit 3bff0d12c36247073fca976498b58a940fca72dc ]

Add support for a new device ID that we will have on TTL (sc2).

---

LLM Generated explanations, may be completely bogus:

Local tree is **7.3.0-rc4** (v7.3-rc4-27-gf0100363d8c37). The change is a one-line PCI ID add for existing iwlwifi Sc/sc2 support. That is the stable device-ID exception, so the rest of this write-up is the forensic checklist behind a **YES**.

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

**Step 1.1: PARSE THE SUBJECT LINE**
Record: **[iwlwifi / wifi] [support] [add PCI device ID for TTL (sc2) platform]**

- Subsystem: wifi: iwlwifi
- Verb: **support** (hardware enablement, not a crash fix)
- Intent: bind iwlwifi to a new Intel platform PCI ID

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**
Record:
- **Reviewed-by:** Johannes Berg <[email protected]> (iwlwifi maintainer)
- **Link:** https://patch.msgid.link/20260714165826.46183446954f.Icc260 831e530c1c92c9be615a7077768b1b9ae30@changeid
- **Signed-off-by:** Miri Korenblit <[email protected]> (author)
- No **Fixes:** tag (expected; this is not a regression fix)
- No **Cc: stable** (expected for this review path)
- No **Reported-by**, **Tested-by**, **Acked-by**, syzbot, or bugzilla tags
- Ignore pipeline **Signed-off-by: Sasha Levin** / **[Upstream commit ...]** (none present on the real commit 3bff0d12c36247)

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**
Record:
- **Bug/problem:** Driver does not claim PCI device 0x9327, so TTL (sc2) Wi-Fi does not bind.
- **Symptom:** iwlwifi never probes; no wireless interface on that SKU.
- **Version info:** none in the message. Author date 2026-07-14; landed as v7.2-rc1-199-g3bff0d12c3624.
- **Root cause (author):** missing PCI ID in iwl_hw_card_ids for hardware “we will have on TTL (sc2).” Same wording as the earlier RZL ID commit (6a1b633fdcd904).

**Step 1.4: DETECT HIDDEN BUG FIXES**
Record: **Not a hidden leak/race/UAF.** It is an explicit new-PCI-ID addition. That is an allowed stable exception, not a disguised memory- safety fix.

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

**Step 2.1: INVENTORY THE CHANGES**
Record:
- File: drivers/net/wireless/intel/iwlwifi/pcie/drv.c (**+1 / -0**)
- Function/data: iwl_hw_card_ids[] (PCI ID table)
- Scope: **single-file surgical**, one table entry

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**
Record:
- **Before:** Sc block lists 0xE440, 0xE340, 0xD340, 0x6E70, 0xD240 with iwl_sc_mac_cfg. 0x9327 does not match; iwl_pci_driver.id_table does not bind.
- **After:** {IWL_PCI_DEVICE(0x9327, PCI_ANY_ID, iwl_sc_mac_cfg)} is added. Probe is iwl_pci_probe() → iwl_pci_gen1_2_probe() with existing Sc MAC config.
- Path affected: **PCI enumeration / driver bind** for that device ID only.

**Step 2.3: IDENTIFY THE BUG MECHANISM**
Record: **[Hardware workaround / device ID addition]**
- Macro expands to Intel vendor, device 0x9327, any subvendor/subdevice, driver_data = iwl_sc_mac_cfg.
- Newer iwlwifi devices are identified from HW RF/MAC registers via iwl_pci_find_dev_info(); Sc IDs are not duplicated as DEVICE(0x…) in iwl_dev_info_table. FM/WH/PE RF entries already exist. Same pattern as 0xD240.
- MODULE_DEVICE_TABLE(pci, iwl_hw_card_ids) updates userspace modalias matching.

**Step 2.4: ASSESS THE FIX QUALITY**
Record:
- **Quality:** Obviously correct; identical to neighboring Sc IDs.
- **Regression risk:** Very low. Only PCI 8086:9327 is affected. Wrong ID would only mis-bind another Intel function using that ID (Intel assigns these IDs).
- No API, locking, or data-structure change.

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

**Step 3.1: BLAME THE CHANGED LINES**
Record:
- Line adding 0x9327: commit **3bff0d12c36247** (Miri Korenblit, 2026-07-14).
- Surrounding Sc IDs: c96a36491003d7 (2025-05-08) and 6a1b633fdcd904 (RZL 0xD240, 2025-06-12).
- iwl_sc_mac_cfg and Sc support are long-lived in this 7.3 tree, not last-month code.

**Step 3.2: FOLLOW THE FIXES: TAG**
Record: **No Fixes: tag.** Not introduced by a buggy prior commit; the ID was simply absent.

**Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES**
Record:
- Related: 6a1b633fdcd904 “support RZL platform device ID” (same one- line pattern).
- 5f88b045d959f “pcie: add two LNL PCI IDs”.
- No later -S 0x9327 follow-up; the ID was not corrected or reverted.
- Nearby series mates (compile-time hcmd check, FCS d3 fix, etc.) do **not** touch this table entry.

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**
Record: Miri Korenblit is a regular iwlwifi author (often applying Intel wireless patches). Johannes Berg reviewed this ID add. Same author wrote the RZL ID add.

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS** Record:
- Needs iwl_sc_mac_cfg and the Sc PCI block — **present** in this tree (cfg/sc.c, iwl-config.h, drv.c).
- sc2 firmware prefixes IWL_SC2_A_FM_C_FW_PRE / IWL_SC2_A_WH_A_FW_PRE and IWL_CFG_MAC_TYPE_SC2 are already here; MAC type is read from CSR at runtime, not from this PCI ID.
- **Standalone:** one line; does not need the other 14 patches from the 07-14-2026 series.

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

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**
Record:
- b4 dig -c 3bff0d12c36247: **[PATCH v2 iwlwifi-next 04/15] wifi:
iwlwifi: support TTL platform device ID**
- URL: https://patch.msgid.link/20260714165826.46183446954f.Icc260831e5 30c1c92c9be615a7077768b1b9ae30@changeid
- b4 dig -a: v2 of “wifi: iwlwifi: updates - 07-14-2026”. Cover
letter: v2 was a resend so -next contained an unrelated compile fix for a sibling patch. **This ID hunk did not change between versions.**
- Thread mbox: **16 messages, all series patches**; no NAKs, no public review replies, no Cc: stable discussion on this patch.
- Cover letter: “Usual fixed, cleanups and **features** from our internal tree.” This ID add is listed under Miri’s patches, not as a CVE/crash fix.
- WebFetch to lore.kernel.org returned **403**; discussion recovered via b4 dig -m.

**Step 4.2: CHECK WHO REVIEWED THE PATCH**
Record (b4 dig -w): To/Cc **Johannes Berg**, **linux- [email protected]**. **Reviewed-by: Johannes Berg** already on the sent patch (internal review). Right maintainer and list.

**Step 4.3: SEARCH FOR THE BUG REPORT**
Record: No Reported-by / bugzilla / syzbot. This is vendor hardware enablement, not a user crash report.

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**
Record: 15-patch **iwlwifi-next** “updates” mix (validations, recovery, LARI v14, UHR DBE). **04/15 is independent.** Other patches are not required for this ID to apply or work.

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**
Record: lore.kernel.org/stable WebFetch **403**. b4 thread has **no** stable-list discussion. **UNVERIFIED** whether anyone later nominated it on stable@.

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

**Step 5.1: IDENTIFY KEY FUNCTIONS**
Record: No function body edited. Data: **iwl_hw_card_ids[]**.
Consumers: MODULE_DEVICE_TABLE, iwl_pci_driver.id_table, probe iwl_pci_probe().

**Step 5.2: TRACE CALLERS**
Record:
- iwl_pci_register_driver() registers iwl_pci_driver with .id_table = iwl_hw_card_ids.
- PCI core calls iwl_pci_probe() on match.
- Context: process/probe, not IRQ. Common path **only if** device 8086:9327 is present.

**Step 5.3: TRACE CALLEES**
Record: Probe enables PCI, maps BAR0, reads CSR_HW_REV, calls iwl_pci_gen1_2_probe(..., iwl_sc_mac_cfg, ...). Device family IWL_DEVICE_FAMILY_SC is already used by other Sc IDs.

**Step 5.4: FOLLOW THE CALL CHAIN**
Record: PCI enumerates → id_table match → iwl_pci_probe → gen1/2 trans/op-mode → firmware via existing sc/sc2 names. **Reachable from userspace** only by having the hardware (or VFIO/passthrough of that ID). Not a syscall fuzz path.

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**
Record: Same one-line Sc ID adds (0xD240 RZL). No extra IWL_DEV_INFO(DEVICE(0x9327)) for other Sc IDs either.

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

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?**
Record: **Yes.** drivers/net/wireless/intel/iwlwifi/pcie/drv.c Sc block and iwl_sc_mac_cfg exist. Without this ID, 0x9327 is unmatched. sc2 (IWL_CFG_MAC_TYPE_SC2 / iwlwifi-sc2-a0-*) already exists. Bug/gap is “missing ID,” not missing subsystem.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**
Record: **Clean apply.** Neighboring lines match the candidate diff. No refactor needed on 7.3-rc4.

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**
Record: No alternate TTL ID fix. 0x9327 appears only from this commit. Prerequisite Sc/sc2 stack is already in 7.3.

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

**Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY**
Record: **drivers/net/wireless/intel/iwlwifi** — **IMPORTANT** (very common laptop/desktop Wi-Fi), not mm/core. Only TTL/sc2 SKUs with this ID.

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**
Record: **Active** (regular Intel iwlwifi-next dumps). ID tables are still the supported way to enable new SKUs; this is not staging.

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

**Step 8.1: DETERMINE WHO IS AFFECTED**
Record: **Driver-specific / hardware-specific.** Users with Intel Wi-Fi PCI 0x9327 (TTL/sc2). Everyone else: no behavior change.

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**
Record: Boot or hotplug of that device. Common **on that platform**, never otherwise. Unprivileged users cannot trigger it without the hardware. **UNVERIFIED** whether TTL has shipped at evaluation time; Intel’s “we will have” language matches prior RZL ID adds.

**Step 8.3: DETERMINE THE FAILURE MODE SEVERITY**
Record: **No oops/UAF/corruption.** Failure is **Wi-Fi never binds** on that SKU. Severity for those users is **HIGH** (device unusable); global severity **LOW**. Stable still takes these ID adds.

**Step 8.4: CALCULATE RISK-BENEFIT RATIO**
Record:
- **Benefit:** Enables existing iwlwifi/Sc/sc2 on TTL platforms that this tree already knows how to drive.
- **Risk:** **Very low** (1 line, existing cfg pointer, isolated PCI match).
- **Ratio:** Benefit/risk favors taking it.

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

**Step 9.1: COMPILE THE EVIDENCE**

FOR:
- Canonical **new PCI ID on an existing driver**
- 1 line, same as other Sc IDs and RZL
- iwl_sc_mac_cfg, sc2 firmware names, RF matching already in this tree
- Maintainer Reviewed-by (Johannes Berg)
- MODULE_DEVICE_TABLE so autoload works
- Standalone; no series dependency
- Zero impact on other devices

AGAINST:
- Not a crash/security/corruption fix; iwlwifi-next “features” series
- Future-tense “we will have”; shipping status unverified
- No stable@ nomination in the thread
- Mixed 15-patch series (this patch itself is still self-contained)

UNRESOLVED:
- lore.kernel.org HTTP 403 (mailbox recovered via b4)
- No stable@ thread found
- Whether TTL silicon is in users’ machines yet

**Step 9.2: APPLY THE STABLE RULES CHECKLIST**
1. Obviously correct and tested? **PASS** — one table row, maintainer Reviewed-by.
2. Fixes a real bug that affects users? **PASS** — missing ID means the driver never attaches (real for that SKU).
3. Important issue (crash, security, corruption, deadlock)? **FAIL** as crash/security; **PASS** under the documented **device-ID exception**.
4. Small and contained? **PASS** — +1 line, one file.
5. No new features or APIs? **PASS** — no new API; only an ID on existing probe/config.
6. Can apply to the local tree? **PASS** — Sc/sc2 and iwl_sc_mac_cfg are here; hunk applies cleanly.

**Step 9.3: CHECK FOR EXCEPTION CATEGORIES**
Record: **NEW DEVICE ID (PCI) to an existing driver.** Driver already exists; only 0x9327 is new. Same class as “drm/i915: Add new device ID for Raptor Lake.”

**Step 9.4: MAKE YOUR DECISION**
This tree already has iwlwifi Sc/sc2. Adding PCI ID 0x9327 is the standard, low-risk way to make TTL hardware work. It should be taken for this tree.

### What it solves and why it matters here
Without the ID, PCI 8086:9327 never matches iwl_pci_driver, so Wi-Fi stays down on TTL (sc2) even though this kernel already has iwl_sc_mac_cfg and sc2 firmware naming. That is exactly the hardware- enablement stable trees routinely accept.

### Stable rules
Small, correct, no new APIs, applies here. Importance is “device works,” via the PCI-ID exception, not a KASAN-class bug.

### Risk vs benefit
Risk is a single ID match. Benefit is working wireless on that Intel SKU. Other machines are unchanged.

### Concerns
None that block a backport here: no missing prerequisites, no extra IWL_DEV_INFO needed (other Sc IDs have none), no follow-up fix to 0x9327. Firmware blobs remain a linux-firmware concern, not a reason to omit the ID.

Verification:
- [Phase 1] Subject/tags: support new ID; Reviewed-by Johannes Berg; Link msgid; no Fixes/stable/syzbot
- [Phase 1] Body: “new device ID that we will have on TTL (sc2)”
- [Phase 2] Diff: +1 line in iwl_hw_card_ids[] under Sc devices:
0x9327 → iwl_sc_mac_cfg
- [Phase 2] IWL_PCI_DEVICE → Intel vendor + MODULE_DEVICE_TABLE + iwl_pci_driver.id_table
- [Phase 2] Other Sc IDs also lack DEVICE(0x…) in iwl_dev_info_table; FM/WH matching already present
- [Phase 3] git describe HEAD / Makefile: **7.3.0-rc4** (v7.3-rc4-27-gf0100363d8c37)
- [Phase 3] git blame: 0x9327 is 3bff0d12c36247; neighbors c96a36491003d7 / 6a1b633fdcd904
- [Phase 3] git merge-base --is-ancestor 3bff0d12c36247 HEAD → yes; git describe 3bff0d12c36247 → v7.2-rc1-199-g3bff0d12c3624
- [Phase 3] git log -S 0x9327 -- drv.c → only this commit (no later correction)
- [Phase 3] RZL analog 6a1b633fdcd904 is the same one-line pattern
- [Phase 4] b4 dig -c/-a/-w/-m: v2 iwlwifi-next 04/15; Johannes + linux-wireless; no NAK; v2 resend unrelated to this hunk
- [Phase 4] Cover letter: mixed fixes/cleanups/features; this ID listed under Miri
- [Phase 4] UNVERIFIED: lore HTTP 403; no stable@ thread retrieved
- [Phase 5] Callers: PCI probe via iwl_pci_probe → iwl_pci_gen1_2_probe; sc2 MAC type from CSR (iwl-drv.c)
- [Phase 6] iwl_sc_mac_cfg in cfg/sc.c; sc2 FW prefixes present; hunk context matches
- [Phase 6] Apply difficulty: clean
- [Phase 7] iwlwifi: important, actively maintained
- [Phase 8] Failure: no driver bind on 0x9327; risk very low
- UNVERIFIED: whether TTL hardware is already shipping

**YES**

 drivers/net/wireless/intel/iwlwifi/pcie/drv.c | 1 +
 1 file changed, 1 insertion(+)
drivers/net/wireless/intel/iwlwifi/pcie/drv.c +1 -0
index 0e8481219839b..4314d95dd12af 100644
@@ -548,6 +548,7 @@ VISIBLE_IF_IWLWIFI_KUNIT const struct pci_device_id iwl_hw_card_ids[] = {
 	{IWL_PCI_DEVICE(0xD340, PCI_ANY_ID, iwl_sc_mac_cfg)},
 	{IWL_PCI_DEVICE(0x6E70, PCI_ANY_ID, iwl_sc_mac_cfg)},
 	{IWL_PCI_DEVICE(0xD240, PCI_ANY_ID, iwl_sc_mac_cfg)},
+	{IWL_PCI_DEVICE(0x9327, PCI_ANY_ID, iwl_sc_mac_cfg)},
 #endif /* CONFIG_IWLMVM || CONFIG_IWLMLD */
 
 	{0}
Signature · 1 line
2.53.0
author maintainer
#67 lore raw

PATCH 1/1 comedi: ni_at_a2150: Fix sanity check in interrupt handler

In reply to Sasha Levin

From: Ian Abbott <[email protected]>

[ Upstream commit e7356cdc7077a4f30fc5232a18e9fc6a4d404581 ]

The driver requests an interrupt handler for the device before it is fully set up.

For safety, the interrupt handler checks the dev->attached flag to ensure the device is fully set up, but it currently does that after dereferencing various pointers which may be NULL if dev->attached is false. Move the check to avoid the possible null pointer dereferences.

---

LLM Generated explanations, may be completely bogus:

## Phase 1: Commit message forensics

**Step 1.1:** Record: [comedi: ni_at_a2150:] [Fix] [Move the dev->attached check in a2150_interrupt() so it runs before pointer dereferences that can be NULL while the device is still attaching.]

**Step 1.2:** Tags in e7356cdc7077a:
- Signed-off-by: Ian Abbott <[email protected]> (author; comedi maintainer)
- `Link:
https://patch.msgid.link/[email protected]`
- Signed-off-by: Greg Kroah-Hartman <[email protected]>
- No Fixes:, Reported-by:, Tested-by:, Reviewed-by:, Acked- by:, or Cc: stable on the committed message (absence is expected here)

Mailbox recipients of the original mail also included H Hartley Sweeten, Jaeyoung Chung, and a malformed Cc that was meant to be `Reported-by:
Sangyun Kim` plus Kyungwook Boo. Those trailers were not copied onto the git commit.

**Step 1.3:** Record:
- Bug: the ISR is registered in a2150_alloc_irq_and_dma() during a2150_attach(), before postconfig sets dev->attached.
- Symptom: NULL pointer dereference in interrupt context if the handler runs while dev->attached is still false.
- Version info: none in the commit body.
- Root cause: the existing if (!dev->attached) guard sits *after* dma->desc[0], s->async, async->cmd, and desc->virt_addr.

Cover letter for the 11-patch series: “Add/fix sanity check in ISA drivers to avoid null-ptr-deref”.

**Step 1.4:** Record: Not a hidden fix. Subject and body are explicit NULL-deref prevention.

## Phase 2: Diff analysis

**Step 2.1:** Record:
- File: drivers/comedi/drivers/ni_at_a2150.c (+9 / −4; 13 lines changed)
- Function: a2150_interrupt()
- Scope: single-file surgical ISR change

**Step 2.2:** Record: Before, locals were initialized with dereferences, then dev->attached was checked. After, desc/async/cmd/buf are declared uninitialized, the attached check runs, then those pointers are filled. Normal attached-and-running IRQ path is unchanged.

**Step 2.3:** Record: [NULL pointer dereference] [ISR used dma, read_subdev, and async before the attached guard; those can still be NULL between request_irq() and dev->attached = true, and dma can already have been freed on detach before free_irq().]

Verified attach/detach order in this tree:
1. comedi_alloc_devpriv() then a2150_alloc_irq_and_dma() → request_irq(a2150_interrupt, …) then DMA alloc, then later comedi_alloc_subdevices() / dev->read_subdev = s.
2. comedi_device_attach() only then calls comedi_device_postconfig(), which sets dev->attached = true.
3. Detach sets dev->attached = false first, then a2150_detach() frees DMA, then comedi_legacy_detach() calls free_irq().

So a premature IRQ during attach hits NULL dma or NULL s/s->async. An IRQ between DMA free and free_irq() hits a freed dma (UAF) in the old code.

Loads that remain before the check (dev->private, devpriv->dma, dev->read_subdev) are pointer loads, not the crashing derefs. private is allocated before request_irq(), and it is still valid until after free_irq().

**Step 2.4:** Record: Obviously correct and minimal. Regression risk is very low: early return already existed; only the check moved. No API/locking/data-structure change. Residual theoretical issue: if attached were true with dma or read_subdev still NULL, later derefs would still fault — that is not the attach/detach window this patch targets, and dev->irq is only kept when DMA alloc succeeded.

## Phase 3: Git history

**Step 3.1:** Record: if (!dev->attached) is old (Frank Mori Hess, 2009). The dangerous pre-check initializers come from 1a97f144e3d3e9 (“staging: comedi: ni_at_a2150: remove depends on ISA_DMA_API limitation”, H Hartley Sweeten, 2015-01-14), first contained in v4.0-rc1. Present in this tree (git merge-base --is-ancestor 1a97f144e3d3e9 HEAD).

**Step 3.2:** Record: No Fixes: tag. Introduced by 1a97f144e3d3e9 (v4.0), which is in this checkout.

**Step 3.3:** Record: This is patch 4/11 of Ian Abbott’s June 2026 series. Neighbor commits are the same class of per-driver ISR guards (dt2811, aio_iiro_16, das6402, pcl711, etc.). Independent; no shared helper or prerequisite refactor. No later follow-up on ni_at_a2150.c.

**Step 3.4:** Record: Ian Abbott is the long-time comedi maintainer. Greg Kroah-Hartman applied the series. Related work: 17221216ae8ce (“comedi: comedi_parport: deal with premature interrupt”) for the same premature-IRQ class, with syzbot + Cc: stable.

**Step 3.5:** Record: No extra commits required. The ISR, dev->attached, request_irq, and comedi_legacy_detach() already exist here. Standalone.

## Phase 4: Mailing list / external research

**Step 4.1:** Record:
- b4 dig -c e7356cdc7077a →
https://patch.msgid.link/[email protected]
- b4 dig -a: v1 only (no v2/v3)
- Cover letter: “comedi: Add/fix sanity check in ISA drivers to avoid null-ptr-deref”
- No NAKs in the saved thread (12 series mails, no review replies)

**Step 4.2:** Record (b4 dig -w): linux-kernel, Greg KH, Hartley Sweeten, Jaeyoung Chung, Sangyun Kim, Kyungwook Boo. Maintainer- authored, applied by Greg.

**Step 4.3:** Record: Original report retrieved with b4 mbox msgid [email protected]:
- Subject: “comedi: KASAN null-ptr-deref in ISA driver IRQ handlers on early IRQ”
- From Jaeyoung Chung; Reported-by Sangyun Kim and Kyungwook Boo
- Failure: handler runs before read_subdev is set → KASAN NULL deref / panic
- Named drivers: das6402, ni_atmio16d, aio_iiro_16, pcmmio, comedi_parport, pcl711
- ni_at_a2150 was not in that list; Ian added it after finding the same request_irq / read_subdev / attached-check ordering

Related: comedi_parport premature IRQ was a syzbot GPF in comedi_get_is_subdevice_running().

**Step 4.4:** Record: 11 independent per-driver patches. This one does not need the others.

**Step 4.5:** Record: UNVERIFIED — lore.kernel.org returned HTTP 403 for /stable/ search. No stable-list discussion confirmed.

## Phase 5: Code semantic analysis

**Step 5.1:** Record: a2150_interrupt() only.

**Step 5.2:** Record: Sole registration is request_irq() in a2150_alloc_irq_and_dma(), called from a2150_attach(). Hardirq context. Userspace can trigger attach/detach via comedi config (COMEDI_NI_AT_A2150).

**Step 5.3:** Record: After the guard: inw(STATUS_REG), comedi_handle_events(), comedi_isadma_disable(), sample copy into the async buffer.

**Step 5.4:** Record: Reachable from the comedi attach ioctl / config path on ISA AT-A2150 (or a crafted I/O base/IRQ). Same class as the KASAN/syzbot premature-IRQ bugs. Not a hot syscall path for typical machines.

**Step 5.5:** Record: Same if (!dev->attached) pattern across many drivers/comedi/drivers/*.c files; this series fixes the ones that checked too late or not at all.

## Phase 6: Local tree (this checkout)

**Step 6.1:** Record:
- make kernelversion / Makefile: **7.3.0-rc4**
- git describe HEAD: v7.3-rc4-27-gf0100363d8c37
- File and ISR exist. Pre-fix ISR confirmed at e7356cdc7077a^. Bug dates to v4.0 (1a97f144e3d3e9). This is mainline, not a 6.x.y stable branch; the driver code the patch targets is present.

**Step 6.2:** Record: Clean apply on the pre-image in this history. No extra backport rework needed for a tree that still has the old ISR.

**Step 6.3:** Record: No earlier ni_at_a2150-specific substitute. comedi_parport got a related premature-IRQ fix; it does not cover this driver.

## Phase 7: Subsystem / maintainer

**Step 7.1:** Record: [drivers/comedi — ISA DAQ] [PERIPHERAL]. Out of staging (8ffdff6a8cfbd). Hardware is old NI AT-A2150 ISA cards (CONFIG_COMEDI_NI_AT_A2150).

**Step 7.2:** Record: Mature, low churn. Ian Abbott still actively fixing ISR attach races in 2026.

## Phase 8: Impact and risk

**Step 8.1:** Record: Driver-specific, CONFIG_COMEDI_NI_AT_A2150. Small user set (legacy ISA DAQ).

**Step 8.2:** Record: Trigger is attach (IRQ registered before attached/read_subdev) or detach (DMA freed before free_irq()). Needs the device (or a spurious/pending IRQ on that line). Not a general unprivileged remote exploit; privileged/local comedi attach is enough if the IRQ fires. Likelihood is low, but the window is real and matches a KASAN report for the same pattern.

**Step 8.3:** Record: [NULL deref / possible UAF in hardirq → oops/panic] [HIGH] (CRITICAL for that machine; not data corruption).

**Step 8.4:** Record: Benefit HIGH for anyone using this driver (avoids IRQ oops on attach/detach). Risk very low (13-line ISR reorder). Ratio favors backport.

## Phase 9: Synthesis

**Evidence FOR:**
- Real NULL deref (and detach UAF) in an interrupt handler
- Same class as a KASAN report and a syzbot GPF on sibling comedi drivers
- Author is the comedi maintainer; Greg applied v1 unchanged
- Small, obviously correct, no new API
- Bug present since v4.0; code exists in this tree
- Independent of the rest of the series

**Evidence AGAINST:**
- Niche obsolete ISA hardware
- Not in the original SNU driver list (Ian’s extra finding)
- Committed message has no Fixes: / Cc: stable (expected for this review)
- No Tested-by on hardware in the thread

**UNRESOLVED:**
- Could not read lore.kernel.org in the browser (403); used b4 mboxes instead
- No confirmed stable@ discussion
- No hardware Tested-by

**Stable rules:**
1. Obviously correct and tested? **PASS** — logic is local and matches core attached semantics; applied by Greg. No extra hardware Tested- by, but the defect is visible in code.
2. Real user-visible bug? **PASS** — KASAN NULL deref / panic for this ISR pattern.
3. Important (crash/security/corruption/deadlock)? **PASS** — hardirq oops/panic.
4. Small and contained? **PASS** — one function, +9/−4.
5. No new features/APIs? **PASS**
6. Can apply to this tree? **PASS** — pre-fix ISR is the historical form of this file; no missing helpers.

**Exception category:** none (ordinary crash fix).

This is a 13-line IRQ-handler NULL-deref (and detach UAF) fix in existing comedi code. It meets the stable rules. The local 7.3.0-rc4 tree has the driver and had the bug since v4.0.

### What it fixes for stable users
If the AT-A2150 ISR runs after request_irq() but before dev->attached (or after DMA is freed on detach), the old handler oopses on NULL/dangling dma/read_subdev/async. Moving the existing guard first prevents that crash.

### Risk vs benefit
Benefit is avoiding a kernel oops; risk is negligible. Other patches in the 11-patch series are not required.

---

Verification:
- [Phase 1] Parsed e7356cdc7077a: Ian Abbott + Greg KH; msgid 20260618102949.26607-5; no Fixes/Cc stable
- [Phase 1] Cover letter from mbox: series is explicitly “avoid null- ptr-deref”
- [Phase 2] Diff: +9/−4 in a2150_interrupt(); moved desc/async/cmd/buf after if (!dev->attached)
- [Phase 2] a2150_attach / a2150_alloc_irq_and_dma / comedi_device_postconfig: request_irq before attached = true
- [Phase 2] comedi_device_detach_locked: attached = false before a2150_free_dma then free_irq
- [Phase 3] git blame on pre-image: check from 2009; early derefs from 1a97f144e3d3e9 (v4.0-rc1)
- [Phase 3] git merge-base --is-ancestor 1a97f144e3d3e9 HEAD and e7356cdc7077a HEAD: both true
- [Phase 3] Series is 11 independent driver patches; no ni_at_a2150 follow-up
- [Phase 4] b4 dig -c/-a/-w: v1 only; recipients include Greg, Hartley Sweeten, SNU reporters
- [Phase 4] b4 mbox of [email protected]:
KASAN null-ptr-deref report
- [Phase 4] Related 17221216ae8ce comedi_parport fix: syzbot GPF + Cc stable
- [Phase 4] lore HTTP 403; UNVERIFIED stable@ archive search
- [Phase 5] a2150_interrupt only used from request_irq in this file
- [Phase 6] Local tree 7.3.0-rc4 (v7.3-rc4-27-gf0100363d8c37); pre-fix ISR confirmed at parent
- [Phase 7] CONFIG_COMEDI_NI_AT_A2150; peripheral ISA DAQ
- [Phase 8] Failure mode: hardirq NULL deref/UAF oops, severity HIGH; backport risk very low
- UNVERIFIED: hardware reproduction on a real AT-A2150; stable mailing- list mentions

**YES**

 drivers/comedi/drivers/ni_at_a2150.c | 13 +++++++++----
 1 file changed, 9 insertions(+), 4 deletions(-)
drivers/comedi/drivers/ni_at_a2150.c +9 -4
index e4e5a0ebd195a..93e9591f5dd4c 100644
@@ -132,11 +132,11 @@ static irqreturn_t a2150_interrupt(int irq, void *d)
 	struct comedi_device *dev = d;
 	struct a2150_private *devpriv = dev->private;
 	struct comedi_isadma *dma = devpriv->dma;
-	struct comedi_isadma_desc *desc = &dma->desc[0];
+	struct comedi_isadma_desc *desc;
 	struct comedi_subdevice *s = dev->read_subdev;
-	struct comedi_async *async = s->async;
-	struct comedi_cmd *cmd = &async->cmd;
-	unsigned short *buf = desc->virt_addr;
+	struct comedi_async *async;
+	struct comedi_cmd *cmd;
+	unsigned short *buf;
 	unsigned int max_points, num_points, residue, leftover;
 	unsigned short dpnt;
 	int status;
@@ -145,6 +145,11 @@ static irqreturn_t a2150_interrupt(int irq, void *d)
 	if (!dev->attached)
 		return IRQ_HANDLED;
 
+	desc = &dma->desc[0];
+	async = s->async;
+	cmd = &async->cmd;
+	buf = desc->virt_addr;
+
 	status = inw(dev->iobase + STATUS_REG);
 	if ((status & INTR_BIT) == 0)
 		return IRQ_NONE;
Signature · 1 line
2.53.0
author maintainer
#68 lore raw

PATCH 1/1 Bluetooth: btrsi: Move set_bt_context after successful HCI registration

In reply to Sasha Levin

From: Chen Changcheng <[email protected]>

[ 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.

---

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 \<[email protected]\> (author)
- Signed-off-by: Luiz Augusto von Dentz \<[email protected]\> (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 kfrees 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
[email protected]
- 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

Quoted 1 line

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 [email protected]; 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(-)
drivers/bluetooth/btrsi.c +2 -1
index 6c1f584c8a337..0e2894e93e82e 100644
@@ -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;
Signature · 1 line
2.53.0
author maintainer
#69 lore raw

PATCH 1/1 fuse: zero the partial EOF page when extending a file

In reply to Sasha Levin

From: Jimmy Zuber <[email protected]>

[ Upstream commit 34b5c4a6e4fb9dbb3f9d87f3b0fb0372105c8302 ]

Extending a fuse file past a non-page-aligned EOF does not zero the tail of the old last page. When that page is cached and has been mmap-dirtied beyond the old EOF, the now in-bounds tail is served to later reads as stale data rather than zeros, which violates POSIX file-extension semantics.

Some file systems get this zeroing automatically at writeback time (block_write_full_folio() / iomap_writeback_handle_eof() zero the tail of the folio straddling i_size). A non-writeback caching fuse file system uses neither path, so it has to zero the tail itself from the size-extending paths, like XFS (xfs_file_write_zero_eof()) and ext4 (ext4_block_zero_eof()) do.

Call truncate_pagecache_range() over the newly-exposed range up front from the three paths that extend a file, before the new size is published:

- a buffered write whose position is past the old EOF (fuse_perform_write());
- a size-extending setattr/truncate (fuse_do_setattr());
- a size-extending fallocate (fuse_file_fallocate()).

This unmaps the stale mappings and zeroes the partial tail of the old EOF folio, so a later read returns zeros. Truncating [old EOF, write start) before a buffered write keeps the dropped range disjoint from the written data, so a write that lands inside the old EOF folio is preserved.

writeback_cache connections are unaffected, as their writes go through iomap_file_buffered_write(), which zeroes post-EOF folios. The bug is observable on a non-writeback_cache server that returns FOPEN_KEEP_CACHE on writable files (without FOPEN_DIRECT_IO), and is caught by the new write_extend_eof fuse selftest.

---

LLM Generated explanations, may be completely bogus:

The local tree is **6.12.111** (pending-6.12). The buggy FUSE size- extend paths are present here; the fix is not. This is a small POSIX/data-integrity fix that belongs in this tree.

---

## PHASE 1: COMMIT MESSAGE FORENSICS

**Step 1.1: PARSE THE SUBJECT LINE**
Record: **[fuse]** **[zero]** zero the partial EOF page when extending a file. “Zero” here is a correctness fix (fill a hole that should read as zeros), not a feature.

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**
Record:
- Signed-off-by: Jimmy Zuber \<[email protected]\> (author)
- Signed-off-by: Miklos Szeredi \<[email protected]\> (FUSE maintainer; applied the patch)
- No Fixes:, Reported-by:, Tested-by:, Reviewed-by:, Link:, or Cc:
stable (absence of Fixes/Cc: stable is expected for this pipeline)
- Ignore any “[Upstream commit …]” / Sasha Levin SOB if present — candidate-prep only

Notable: maintainer SOB. Cover letter (v4 0/2) also names testing under UML plus libfuse passthrough_ll. Recipients included Jan Kara, Joanne Koong, Brian Foster (author of the analogous ext4/XFS EOF-zeroing work).

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**
Record:
- **Bug:** Extending a FUSE file past a non-page-aligned EOF does not zero the tail of the old last page.
- **Symptom:** If that page is cached and mmap-dirtied past the old EOF, later reads of the newly in-bounds tail return stale bytes instead of zeros (POSIX file-extension violation).
- **Root cause:** Writeback-style filesystems get this from block_write_full_folio() / iomap_writeback_handle_eof(). A non- writeback caching FUSE fs uses neither, so it must zero on extend, like XFS/ext4.
- **Fix:** truncate_pagecache_range() over the newly exposed range on write, setattr/truncate, and fallocate, before publishing the new size (write/fallocate; setattr still publishes i_size first, as it already did).
- **Scope note:** writeback_cache writes are claimed unaffected on mainline because they go through iomap_file_buffered_write(). Observable on non-writeback_cache + FOPEN_KEEP_CACHE without FOPEN_DIRECT_IO. Caught by write_extend_eof selftest.
- **Version info:** none in the message. Cover letter base-commit 7d87a5a284bb34edb3f4e7e312ef403b3385a7b7 is post-6.12.

**Step 1.4: DETECT HIDDEN BUG FIXES**
Record: Not hidden. Explicit POSIX/data-integrity bug with a regression test. v1 originally zeroed from fuse_write_update_attr() after the fact; v3/v4 moved zeroing to the extend paths so a write inside the old EOF folio is preserved.

---

## PHASE 2: DIFF ANALYSIS - LINE BY LINE

**Step 2.1: INVENTORY THE CHANGES**
Record:
- fs/fuse/dir.c: +3 in fuse_do_setattr()
- fs/fuse/file.c: +4 in fuse_perform_write(), +5 in fuse_file_fallocate()
- **~12 insertions, 0 deletions.** Single-subsystem surgical fix (FUSE only). Companion selftest (series 2/2) is not part of this commit.

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**
Record:
- **fuse_perform_write():** Snapshot old_size. If pos > old_size, truncate_pagecache_range(inode, old_size, pos-1) before filling pages. Hole [old EOF, write start) is unmapped/zeroed; the write range itself is left intact.
- **fuse_do_setattr():** On size change, if extending, range-truncate [oldsize, newsize-1] then the existing truncate_pagecache() + invalidate_inode_pages2().
- **fuse_file_fallocate():** If not FALLOC_FL_KEEP_SIZE and offset+length > oldsize, range-truncate [oldsize, offset+length-1] before fuse_write_update_attr() publishes the new size. Punch/zero still has its own existing range truncate.

**Step 2.3: IDENTIFY THE BUG MECHANISM**
Record: **Logic/correctness + memory-contents (stale page-cache data).** mmap may dirty the last page past i_size. Extending makes that tail in-bounds. Without zeroing, reads return mmap garbage instead of zeros. truncate_pagecache_range() unmaps full pages in the hole and truncate_inode_partial_folio() / folio_zero_range() zeros the partial old-EOF folio (mm/truncate.c).

**Step 2.4: ASSESS THE FIX QUALITY**
Record: Minimal, matches XFS/ext4. Uses a long-standing helper. v4 dropped a custom fuse_zero_partial_eof_folio() after Miklos/Jan noted folio_mkclean()/folio_mark_dirty() is a buffer-head concern; truncate_pagecache_range() already zeros. Regression risk is low:
extra truncate of a hole that must read as zeros. Failed write after hole-zeroing only clears post-EOF cache, which is still past i_size. Does not add APIs or features.

---

## PHASE 3: GIT HISTORY INVESTIGATION

**Step 3.1: BLAME THE CHANGED LINES**
Record:
- setattr size-change block: 8373200b124d03 (“fuse: Trust kernel i_size only”, 2014) wrapping truncate_pagecache from 7caef26767c172 (2013). Comment around the invalidate goes back to Miklos 2008 (3be5a52b30aa5c).
- fuse_perform_write(): writethrough extend path since at least ea9b9907b82a09 (2008); FUSE_I_SIZE_UNSTABLE from 06a7c3c2781409 (2013).
- fallocate extend: bee6c307800bbb / b0aa7606521790 (2013). Bug is old, long predating 6.12.

**Step 3.2: FOLLOW THE FIXES: TAG**
Record: No Fixes: tag. Introducing commit is “FUSE never zeroed this on extend,” not a recent regression.

**Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES**
Record: Recent 6.12 fuse work is lock leaks, DIO cache, virtiofs UAF — unrelated. This is standalone, not a prep patch. Series 2/2 is a selftest only.

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**
Record: Jimmy Zuber has no other fuse commits in this tree. Applied by Miklos Szeredi (maintainer). Analogous ext4 fix b6ce2dbe984bc (“ext4:
partial zero eof block on unaligned inode size extension”) **is already in this tree**.

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS**
Record: Added calls are only i_size_read() + truncate_pagecache_range(), both present. No new helpers. The mainline hunk context mentions fuse_folios_alloc; this tree still uses fuse_pages_alloc / ap->pages, so the **write hunk may need a trivial context backport**. setattr and fallocate hunks match 6.12. Standalone:
yes.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**
Record: Could not b4 dig -c <sha> (commit not in this checkout). Retrieved thread via msgid [email protected].
- Lore/LWN cover: [PATCH v4 0/2] fuse: zero the partial EOF page when extending a file
- Openwall: https://lists.openwall.net/linux-kernel/2026/08/24/1447
(1/2), 1443 (2/2)
- Revisions: v1 (2026-07-31) zeroed from fuse_write_update_attr() (would clobber in-page extending writes); v2/v3 moved zeroing to extend paths; v4 dropped the helper per Miklos/Jan. Applied version is v4.
- Miklos reply 2026-08-24: **“Applied, thanks.”** No NAK, no stable objection.

**Step 4.2: CHECK WHO REVIEWED THE PATCH**
Record: To: Miklos Szeredi, Shuah Khan. Cc: fuse-devel, linux-kselftest, Jan Kara, Joanne Koong, Brian Foster. Maintainer applied v4 after review-driven simplification.

**Step 4.3: SEARCH FOR THE BUG REPORT**
Record: No syzbot/bugzilla. Author reproduced vs libfuse passthrough_ll and added a selftest that fails without the fix. Same mmap-beyond-EOF pattern as the ext4 case (xfs_io pwrite/mmap/mwrite/truncate).

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**
Record: 2-patch series. 2/2 is write_extend_eof_test.c only. Kernel fix does not depend on it. 6.12 has no tools/testing/selftests/filesystems/fuse/ (no need to backport the test).

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**
Record: **UNVERIFIED** — lore.kernel.org returned 403 (Anubis). Patch is from Aug 2026; no evidence it was rejected for stable. Absence of Cc:
stable is not a negative signal here.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

**Step 5.1: IDENTIFY KEY FUNCTIONS IN THE DIFF**
Record: fuse_perform_write(), fuse_do_setattr(), fuse_file_fallocate(). Helper used: truncate_pagecache_range().

**Step 5.2: TRACE CALLERS**
Record:
- fuse_perform_write() ← fuse_cache_write_iter() (under inode_lock) ← fuse_file_write_iter() (.write_iter). Userspace write/pwrite on cached FUSE files. Direct-IO and DAX do not use this function.
- fuse_do_setattr() ← fuse_setattr() / open O_TRUNC path. Userspace ftruncate/truncate.
- fuse_file_fallocate() ← .fallocate. Userspace fallocate().

**Step 5.3: TRACE CALLEES**
Record: truncate_pagecache_range() → optional unmap_mapping_range() for full pages in the hole → truncate_inode_pages_range() → truncate_inode_partial_folio() / folio_zero_range() for the partial EOF folio. Confirmed in mm/truncate.c in this tree.

**Step 5.4: FOLLOW THE CALL CHAIN**
Record: Reachable from ordinary syscalls on a common FUSE mount. Default no-open flags are FOPEN_KEEP_CACHE (fs/fuse/file.c ~line 151). Non- writeback is the usual libfuse default. Unprivileged apps that mmap then extend trigger it.

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**
Record: Same class as ext4 ext4_zero_partial_blocks() on unaligned extend (already in this tree) and XFS xfs_file_write_zero_eof(). Remaining FUSE holes not covered here: copy_file_range (truncates only the copied range), getattr-driven remote size growth in fuse_change_attributes(). Incomplete coverage is not a reason to skip the three primary paths.

---

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

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?**
Record: **Yes.**
- fuse_do_setattr(): fs/fuse/dir.c ~2061–2065 — size change → truncate_pagecache + invalidate_inode_pages2 only (no hole zero on extend). Dirty mmap pages can survive invalidate.
- fuse_perform_write(): fs/fuse/file.c ~1294–1305 — no truncate_pagecache_range.
- fuse_file_fallocate(): fs/fuse/file.c ~3223–3230 — extend updates i_size only; range truncate is punch/zero only.
Introduced years before 6.12 (2008–2014). git log --grep="zero the partial EOF" on fs/fuse/ is empty here.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**
Record: **Minor context only.** setattr/fallocate match. Write function exists with the same pos / FUSE_I_SIZE_UNSTABLE shape; later in the function 6.12 still uses pages, not folios. No semantic rework required.

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**
Record: This fix is not present. No earlier FUSE EOF-tail zeroing. ext4 analog is present (b6ce2dbe984bc).

Note: the commit’s “writeback_cache uses iomap_file_buffered_write()” is mainline. **6.12 writeback still uses generic_file_write_iter → fuse_write_begin/fuse_write_end.** That does not remove the writethrough bug this patch fixes (fuse_cache_write_iter non-wb path still calls fuse_perform_write()). setattr/fallocate changes still apply to both modes.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

**Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY**
Record: **fs/fuse — IMPORTANT.** Not mm/VFS-core, but FUSE is widely used (sshfs, fuse-overlayfs, ntfs-3g, virtiofs, container/user mounts). Data served from the page cache is wrong.

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**
Record: Actively maintained (Miklos). This is a long-standing hole, not churn from a brand-new API.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

**Step 8.1: DETERMINE WHO IS AFFECTED**
Record: **FUSE users with page cache kept and without writeback_cache** (common). Config-specific (CONFIG_FUSE_FS), not a single obscure driver.

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**
Record: Mid-page EOF + mmap store past EOF (legal on the last page) + extend via pwrite/ftruncate/fallocate. Not every write; well-known and reproducible (selftest + libfuse passthrough). Unprivileged if the user can mmap/write the file.

**Step 8.3: DETERMINE THE FAILURE MODE SEVERITY**
Record: **Stale data returned as file contents / POSIX hole not zero — HIGH (data integrity).** Not a panic. Same class stable already took for ext4.

**Step 8.4: CALCULATE RISK-BENEFIT RATIO**
Record: **Benefit high** (wrong reads on a common FUSE config). **Risk low** (~12 lines, existing helper, maintainer-applied, selftest). Ratio strongly favors backport.

---

## PHASE 9: FINAL SYNTHESIS

**Step 9.1: COMPILE THE EVIDENCE**

For:
- Real POSIX/data-integrity bug; selftest fails without the fix
- Small, surgical, no new API
- Buggy code present in 6.12 for years
- Same pattern as ext4, already backported here
- Maintainer applied v4 after review
- Default FOPEN_KEEP_CACHE; userspace-reachable
- Failed-write side effect is only clearing post-EOF cache

Against:
- Trigger needs mmap-past-EOF then extend (not every I/O)
- Does not cover copy_file_range / getattr size updates
- Write hunk may need a one-line context tweak (pages vs folios)
- No explicit Cc: stable (expected)

Unresolved:
- Exact mainline SHA (not in this tree; git.kernel.org blocked)
- stable@ thread (lore 403)
- Follow-ups after Miklos applied (none seen in the 4-message v4 thread)

**Step 9.2: APPLY THE STABLE RULES CHECKLIST**
1. Obviously correct and tested? **PASS** — helper is standard; UML selftest; maintainer applied
2. Fixes a real bug that affects users? **PASS** — stale reads vs zeros
3. Important (crash/security/corruption/deadlock)? **PASS** — data integrity / POSIX hole semantics
4. Small and contained? **PASS** — 12 lines, two files, three call sites
5. No new features or APIs? **PASS**
6. Can apply to the local tree? **PASS** — logic applies; write hunk may need trivial context

**Step 9.3: CHECK FOR EXCEPTION CATEGORIES**
Record: Not a device-id/quirk/DT/build/docs exception. Qualifies as a normal important bugfix.

**Step 9.4: MAKE YOUR DECISION**
Backport. The bug exists in this 6.12 tree, the fix is small and already the form the maintainer wanted, and the user-visible failure is wrong file data.

---

### What the commit solves for stable users

On cached, non-writeback FUSE, extending a file (write past EOF, ftruncate up, fallocate without KEEP_SIZE) leaves mmap-dirtied bytes in the old last page. Those bytes become part of the file and are returned to read instead of zeros. That is a data-integrity / POSIX violation. 6.12’s three extend paths match the buggy mainline code.

### Risk vs benefit

Benefit is preventing stale data on a common FUSE configuration. Risk is a few truncate_pagecache_range() calls on a hole that must be zeros anyway. Companion selftest is optional and this tree lacks the fuse selftest directory.

---

### Verification
- **[Phase 1]** Tags: author Jimmy Zuber; Miklos Szeredi SOB; no Fixes/Reported-by/Cc: stable
- **[Phase 1]** Cover letter v4: msgid [email protected]; tested UML + libfuse passthrough_ll
- **[Phase 2]** Diff: +3 dir.c setattr, +4 perform_write, +5 fallocate; 12 lines
- **[Phase 2]** truncate_pagecache_range() / truncate_inode_partial_folio() / folio_zero_range() read in mm/truncate.c
- **[Phase 3]** blame: setattr guard 8373200b124d03 (2014); write path ea9b9907b82a09 (2008); fallocate bee6c307800bbb (2013)
- **[Phase 3]** No Fixes: tag; git log --grep="zero the partial EOF" -- fs/fuse/ empty in this tree
- **[Phase 3]** ext4 analog b6ce2dbe984bc is an ancestor of HEAD
- **[Phase 4]** b4 mbox msgid [email protected]: 4 messages; Miklos “Applied, thanks.”
- **[Phase 4]** v1→v4: moved zeroing off fuse_write_update_attr; dropped custom helper
- **[Phase 4]** lore.kernel.org search 403 — UNVERIFIED stable@ discussion
- **[Phase 5]** Callers: fuse_file_write_iter → fuse_cache_write_iter → fuse_perform_write under inode_lock; setattr; .fallocate
- **[Phase 5]** Default FOPEN_KEEP_CACHE at fs/fuse/file.c:151
- **[Phase 6]** git describe HEAD → p-6.12-3-gc504cf0baa3d8; make kernelversion → 6.12.111
- **[Phase 6]** Buggy snippets present at dir.c:2061–2065, file.c:1294–1305, file.c:3223–3230
- **[Phase 6]** 6.12 uses fuse_pages_alloc, not fuse_folios_alloc — minor apply context
- **[Phase 6]** 6.12 writeback_cache uses fuse_write_begin, not iomap_file_buffered_write (commit text is mainline-specific)
- **[Phase 8]** Failure mode: stale page-cache data on read after extend; severity HIGH
- **UNVERIFIED:** exact mainline SHA; post-apply follow-ups beyond the v4 thread; copy_file_range/getattr as extra bugs (not used to vote NO)

**YES**

 fs/fuse/dir.c  | 3 +++
 fs/fuse/file.c | 9 +++++++++
 2 files changed, 12 insertions(+)
fs/fuse/dir.c +3 -0
index a013fad843b2c..9e20bc9dbdac4 100644
@@ -2095,6 +2095,9 @@ int fuse_do_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
 	 */
 	if ((is_truncate || !is_wb) &&
 	    S_ISREG(inode->i_mode) && oldsize != outarg.attr.size) {
+		if (outarg.attr.size > oldsize)
+			truncate_pagecache_range(inode, oldsize,
+						 outarg.attr.size - 1);
 		truncate_pagecache(inode, outarg.attr.size);
 		invalidate_inode_pages2(mapping);
 	}
fs/fuse/file.c +9 -0
index 0812eee881519..a7a3ac5b34f42 100644
@@ -1290,9 +1290,13 @@ static ssize_t fuse_perform_write(struct kiocb *iocb, struct iov_iter *ii)
 	struct fuse_conn *fc = get_fuse_conn(inode);
 	struct fuse_inode *fi = get_fuse_inode(inode);
 	loff_t pos = iocb->ki_pos;
+	loff_t old_size = i_size_read(inode);
 	int err = 0;
 	ssize_t res = 0;
 
+	if (pos > old_size)
+		truncate_pagecache_range(inode, old_size, pos - 1);
+
 	if (inode->i_size < pos + iov_iter_count(ii))
 		set_bit(FUSE_I_SIZE_UNSTABLE, &fi->state);
 
@@ -2952,6 +2956,11 @@ static long fuse_file_fallocate(struct file *file, int mode, loff_t offset,
 
 	/* we could have extended the file */
 	if (!(mode & FALLOC_FL_KEEP_SIZE)) {
+		loff_t oldsize = i_size_read(inode);
+
+		if (offset + length > oldsize)
+			truncate_pagecache_range(inode, oldsize,
+						 offset + length - 1);
 		if (fuse_write_update_attr(inode, offset + length, length))
 			file_update_time(file);
 	}
Signature · 1 line
2.53.0
author maintainer
#70 lore raw

PATCH 1/1 drm/amdgpu: Add checks to vbios fetch through ATRM

In reply to Sasha Levin

From: Lijo Lazar <[email protected]>

[ Upstream commit 8c3fcfc14fc1320a1155acb2dd7656fce7003bc0 ]

Check if a valid buffer object is returned after ATRM call. Also, match the buffer length against requested size before copying.

---

LLM Generated explanations, may be completely bogus:

This 6.18.53 tree still copies an untrusted ATRM ACPI buffer with no type or length check, which is a real heap overflow / NULL-deref during dGPU probe. The patch is a small, self-contained memory-safety fix and belongs in this tree.

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

Step 1.1: PARSE THE SUBJECT LINE
Record: [drm/amdgpu] [Add] [checks on ATRM ACPI return before copying VBIOS data]
Subsystem prefix drm/amdgpu. Verb is “Add checks,” which here means adding missing validation, not a feature.

Step 1.2: PARSE ALL COMMIT MESSAGE TAGS
Record:
- Signed-off-by: Lijo Lazar \<[email protected]\> (author)
- Reviewed-by: Alex Deucher \<[email protected]\> (amdgpu maintainer)
- Signed-off-by: Alex Deucher \<[email protected]\>
- No Fixes:, Reported-by, Tested-by, Link:, or Cc: stable (absence expected)
- Ignore pipeline-added “Upstream commit …” and “Signed-off-by: Sasha Levin”

Notable: maintainer Reviewed-by + SOB. No fuzzer or user crash report.

Step 1.3: ANALYZE THE COMMIT BODY TEXT
Record:
- Bug: ATRM ACPI evaluation result used without checking it is a buffer, and without capping copy size to the requested length.
- Symptom: NULL deref if buffer.pointer is NULL; type-confused access if the object is not ACPI_TYPE_BUFFER; memcpy of firmware- controlled obj->buffer.length into a 4 KiB slot of a 256 KiB kmalloc, i.e. heap overflow especially on the last 4 KiB page.
- Version info: none in the message. Code dates to amdgpu core (v4.2).
- Root cause (author): ATRM can return a non-buffer or oversized buffer; copy must be validated first.

Step 1.4: DETECT HIDDEN BUG FIXES
Record: Yes. “Add checks” is defensive language for a memory-safety bug:
missing type check + unbounded memcpy from ACPI firmware data. Same pattern as this author’s ATIF/ATPX buffer validation commits.

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

Step 2.1: INVENTORY THE CHANGES
Record:
- File: drivers/gpu/drm/amd/amdgpu/amdgpu_bios.c (+8 / -2)
- Function: amdgpu_atrm_call()
- Scope: single-function surgical fix

Step 2.2: UNDERSTAND THE CODE FLOW CHANGE
Record:
Before: after acpi_evaluate_object success, obj = buffer.pointer then memcpy(bios+offset, obj->buffer.pointer, obj->buffer.length) and return obj->buffer.length.
After: reject NULL or non-buffer objects (kfree + -EINVAL); len = min_t(size_t, obj->buffer.length, len); copy that many bytes; return the capped length.
Path: dGPU VBIOS fetch via ATRM during probe (amdgpu_atrm_get_bios → amdgpu_get_bios_dgpu → amdgpu_get_bios).

Step 2.3: IDENTIFY THE BUG MECHANISM
Record:
- Category: memory safety (NULL deref + out-of-bounds write) on an ACPI/firmware path.
- Mechanism: union acpi_object is type-tagged. Using .buffer.length / .buffer.pointer when type is INTEGER/PACKAGE/etc. reads the wrong union members. Even with a real buffer, firmware can return length \> requested 4096. Destination is adev->bios (kmalloc(256*1024)), offset = i * 4096. Last page (i == 63) overflow writes past the allocation.

Step 2.4: ASSESS THE FIX QUALITY
Record:
- Obviously correct: type check is the standard ACPI pattern (ATIF already does obj->type != ACPI_TYPE_BUFFER; nouveau acpi_read_bios already does min(length, obj->buffer.length)).
- Minimal; no unrelated churn; no API change.
- Regression risk low: well-behaved ATRM still copies ≤ requested size. Oversize/wrong-type now fails this chunk; caller already treats ret < ATRM_BIOS_PAGE as end-of-data and then check_atom_bios(). -EINVAL is < 4096, so the loop stops and BIOS validation fails instead of overflowing.
- Remaining gap (not a reason to reject): no check that obj->buffer.pointer is non-NULL when type is BUFFER; ACPI normally provides one. ACPI_FAILURE path still does not kfree (pre-existing).

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

Step 3.1: BLAME THE CHANGED LINES
Record: Unchecked memcpy comes from d38ceaf99ed015 (“drm/amdgpu: add core driver (v4)”, 2015-04-20), first in v4.2-rc1. Present for the entire life of amdgpu, including this 6.18 tree.

Step 3.2: FOLLOW THE FIXES: TAG
Record: No Fixes: tag. Introducer is the original amdgpu core commit, which is in this tree.

Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES
Record: Recent amdgpu_bios.c work is VBIOS source selection (ROM BAR, VFCT, shadow ROM), not ATRM copy logic. ATRM skip for removable devices is 432e664e7c98c. This patch is standalone, not “X/Y”. Sibling hardening (not prerequisites): c8373721c3e54 ATIF buffer validation, 9d367fab451d9 ATPX buffer validation (same author, May 2026). No follow-ups on this file after the candidate.

Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS
Record: Lijo Lazar is a regular AMD amdgpu contributor. Same-era ACPI object validation: ATIF and ATPX. Maintainer Alex Deucher reviewed.

Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS
Record: None. Uses existing acpi_evaluate_object, ACPI_TYPE_BUFFER, min_t, memcpy. git diff v6.18.53 <candidate> -- amdgpu_bios.c is exactly this hunk. Applies standalone.

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

Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION
Record:
- b4 dig -c 8c3fcfc14fc1320a1155acb2dd7656fce7003bc0 →
https://patch.msgid.link/[email protected]
- b4 dig -a: v1 only, 2026-06-15, no later revisions.
- Thread: patch from Lijo Lazar; Alex Deucher Reviewed-by. No NAK, no stable nomination, no risk flags.
- lore.kernel.org WebFetch returned 403; thread recovered via b4 dig -m.

Step 4.2: CHECK WHO REVIEWED THE PATCH
Record (b4 dig -w): To/Cc Lijo Lazar, [email protected], Hawking Zhang, Alexander Deucher, Asad Kamal, Candice Li. Subsystem maintainer reviewed.

Step 4.3: SEARCH FOR THE BUG REPORT
Record: No Reported-by / Link. No public crash report found. Bug is from code inspection of untrusted ACPI length.

Step 4.4: CHECK FOR RELATED PATCHES AND SERIES
Record: Standalone v1. Related ATIF/ATPX validation patches are independent files (amdgpu_acpi.c, amdgpu_atpx_handler.c). radeon radeon_atrm_call() still has the old memcpy (separate driver; not required for this backport).

Step 4.5: CHECK STABLE MAILING LIST HISTORY
Record: lore.kernel.org/stable WebFetch 403. b4 dig showed only amd- gfx. No evidence this was rejected for stable. Absence of prior stable discussion is not a negative.

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

Step 5.1: IDENTIFY KEY FUNCTIONS IN THE DIFF
Record: amdgpu_atrm_call() only.

Step 5.2: TRACE CALLERS
Record:
- amdgpu_atrm_call ← amdgpu_atrm_get_bios (CONFIG_ACPI)
- amdgpu_atrm_get_bios ← amdgpu_get_bios_dgpu
- amdgpu_get_bios_dgpu ← amdgpu_get_bios (non-APU)
- amdgpu_get_bios ← amdgpu_device.c during COMMON IP early_init / device init
Context: process context, driver probe, hybrid/PX dGPU laptops. Not IRQ. Userspace cannot call it directly; it runs when amdgpu binds.

Step 5.3: TRACE CALLEES
Record: acpi_evaluate_object, acpi_format_exception, memcpy, kfree, min_t, DRM_ERROR. ACPI allocates with ACPI_ALLOCATE_BUFFER.

Step 5.4: FOLLOW THE CALL CHAIN
Record: Reachable on boot/module load for discrete AMD GPUs on PX platforms with an ATRM ACPI method (on-platform only; removable devices skipped). Failure of ATRM can make amdgpu_get_bios() fail and probe return -EINVAL unless VBIOS is optional. Heap overflow is reachable whenever ATRM returns a too-large buffer.

Step 5.5: SEARCH FOR SIMILAR PATTERNS
Record: Same unfixed pattern in drivers/gpu/drm/radeon/radeon_bios.c. Nouveau already caps length. ATIF/ATPX in amdgpu already validate type/length. Systematic ACPI-buffer issue; this commit fixes amdgpu ATRM only.

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

Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?
Record: Yes. Local tree is 6.18.53 (git describe HEAD → v6.18.53-5049-g0f0bdc2b0dffb, VERSION=6 PATCHLEVEL=18 SUBLEVEL=53). v6.18.53:drivers/gpu/drm/amd/amdgpu/amdgpu_bios.c still has:

```
memcpy(bios+offset, obj->buffer.pointer, obj->buffer.length);
```

Bug since v4.2 (d38ceaf99ed015).

Step 6.2: CHECK FOR BACKPORT COMPLICATIONS
Record: Clean apply. Diff vs v6.18.53 is only this hunk. Surrounding amdgpu_atrm_call matches the patch context.

Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE
Record: No other ATRM copy-size fix in this tree. ATIF/ATPX validation does not cover ATRM.

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

Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY
Record: [drm/amdgpu VBIOS/ACPI] [IMPORTANT] — not mm/core, but a widely used GPU driver; probe-time heap overflow can oops or corrupt kernel memory.

Step 7.2: ASSESS SUBSYSTEM ACTIVITY
Record: amdgpu is actively developed; this ATRM helper has been unchanged since 2015 aside from log-string tweaks. Long-lived bug, not a new-code issue.

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

Step 8.1: DETERMINE WHO IS AFFECTED
Record: Driver-specific: discrete AMD GPUs on hybrid/PX systems with ATRM (typical laptop mux). CONFIG_ACPI. Not APUs (amdgpu_get_bios_apu does not call ATRM). Still a real, common laptop class.

Step 8.2: DETERMINE THE TRIGGER CONDITIONS
Record: Device probe when ATRM is present. Unprivileged users do not invoke it directly; broken/malicious ACPI (buggy laptop firmware, or attacker-controlled tables in some virt setups) can trigger overflow. Well-behaved 4 KiB ATRM responses are unaffected.

Step 8.3: DETERMINE THE FAILURE MODE SEVERITY
Record: Kernel heap out-of-bounds write and/or NULL deref oops during GPU init. Severity HIGH (crash; potential memory corruption). Not a guaranteed panic on every AMD system.

Step 8.4: CALCULATE RISK-BENEFIT RATIO
Record:
- Benefit: HIGH for ATRM systems — prevents overflow/oops; zero behavior change for correct firmware.
- Risk: VERY LOW — 8 lines, error-path + bounds cap, maintainer- reviewed.
- Ratio: strongly favors backport.

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

Step 9.1: COMPILE THE EVIDENCE
FOR:
- Unbounded memcpy from ACPI-controlled length into a fixed kmalloc (heap OOB).
- Missing type check → type-confused union access / NULL deref.
- Present in this 6.18.y tree since amdgpu introduction (v4.2).
- Small, obviously correct, applies cleanly.
- Maintainer Reviewed-by.
- Same class as ATIF/ATPX ACPI buffer validation.

AGAINST:
- No user/syzbot report; described as “add checks.”
- Only hybrid/PX ATRM path, not all amdgpu users.
- radeon sibling left unfixed (out of scope).

UNRESOLVED:
- Could not fetch lore/stable HTML (403); mbox via b4 was sufficient.
- No public reproducer; overflow depends on ATRM returning a bad object (verified in code, not in a crash log).

Step 9.2: APPLY THE STABLE RULES CHECKLIST
1. Obviously correct and tested? PASS — type check + min length; maintainer review; caller already handles short reads.
2. Fixes a real bug that affects users? PASS — firmware-supplied length used as memcpy size on a real probe path.
3. Important issue? PASS — heap overflow / oops, HIGH.
4. Small and contained? PASS — one function, +8/-2.
5. No new features or APIs? PASS.
6. Can apply to the local tree? PASS — identical context on v6.18.53.

Step 9.3: CHECK FOR EXCEPTION CATEGORIES
Record: None (not a device ID/quirk/DT/build/doc exception). Qualifies as a normal memory-safety bug fix.

Step 9.4: MAKE YOUR DECISION
YES. This tree still has the unchecked ATRM copy. The patch is a contained, high-value memory-safety fix with negligible regression risk.

===============================================================
What the commit solves for this tree
===============================================================

amdgpu_atrm_call() fetches VBIOS in 4 KiB ATRM pages into a 256 KiB buffer. Before this change it memcpy’d obj->buffer.length with no check that ACPI returned a buffer or that length ≤ 4096. Bad firmware (wrong type or oversized buffer) can NULL-deref or smash the heap during amdgpu probe on PX laptops. The fix rejects invalid objects and caps the copy. That matches stable rules: real bug, important, small, no new API, clean apply to 6.18.53.

Risk vs benefit: benefit is preventing overflow/oops; risk is a tighter copy that only changes broken ATRM responses. No prerequisites.

===============================================================
Verification
===============================================================
- [Phase 1] Parsed tags: author Lijo Lazar; Reviewed-by/SOB Alex Deucher; no Fixes/Reported-by/Cc:stable.
- [Phase 2] Diff: amdgpu_atrm_call() +8/-2; type check + min_t before memcpy.
- [Phase 2] Pre-fix at e0d5ff3ff014b^ and at v6.18.53: raw memcpy of obj->buffer.length.
- [Phase 2] union acpi_object in include/acpi/actypes.h: INTEGER vs BUFFER overlay confirms type confusion.
- [Phase 2] Caller loop: ATRM_BIOS_PAGE 4096, size 256*1024; last chunk overflow is past kmalloc.
- [Phase 3] git blame on parent: d38ceaf99ed015 (2015), git describe --contains → v4.2-rc1.
- [Phase 3] No Fixes: tag; introducer is in this tree.
- [Phase 3] ATIF/ATPX validation commits are sibling files, not prerequisites.
- [Phase 3] git log e0d5ff3ff014b..HEAD -- amdgpu_bios.c: no follow- ups.
- [Phase 4] b4 dig -c 8c3fcfc14fc1…: lore msgid [email protected].
- [Phase 4] b4 dig -a: v1 only.
- [Phase 4] b4 dig -w: amd-gfx + Deucher/Zhang/Kamal/Li.
- [Phase 4] mbox: Deucher Reviewed-by; no NAK.
- [Phase 4] WebFetch lore/stable: 403; treated as UNVERIFIED for HTML, covered by b4 mbox.
- [Phase 5] Callers: amdgpu_atrm_get_bios → amdgpu_get_bios_dgpu → amdgpu_get_bios → amdgpu_device.c probe.
- [Phase 5] radeon still unfixed; nouveau already mins length.
- [Phase 6] git describe HEAD: v6.18.53-5049-g0f0bdc2b0dffb; make kernelversion 6.18.53.
- [Phase 6] git diff v6.18.53 <candidate> -- amdgpu_bios.c: this hunk only → clean apply.
- [Phase 8] Failure mode: heap OOB / NULL deref on ATRM probe, HIGH.
- UNVERIFIED: live ATRM firmware that returns oversized buffers (no crash report); stable-list HTML search (403).

**YES**

 drivers/gpu/drm/amd/amdgpu/amdgpu_bios.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
drivers/gpu/drm/amd/amdgpu/amdgpu_bios.c +8 -2
index dec312b0f3b0a..f28dec3630de5 100644
@@ -280,8 +280,14 @@ static int amdgpu_atrm_call(acpi_handle atrm_handle, uint8_t *bios,
 	}
 
 	obj = (union acpi_object *)buffer.pointer;
-	memcpy(bios+offset, obj->buffer.pointer, obj->buffer.length);
-	len = obj->buffer.length;
+	if (!obj || obj->type != ACPI_TYPE_BUFFER) {
+		DRM_ERROR("ATRM returned an invalid object\n");
+		kfree(buffer.pointer);
+		return -EINVAL;
+	}
+
+	len = min_t(size_t, obj->buffer.length, len);
+	memcpy(bios+offset, obj->buffer.pointer, len);
 	kfree(buffer.pointer);
 	return len;
 }
Signature · 1 line
2.53.0
author maintainer
#71 lore raw

PATCH 1/1 comedi: das6402: Add sanity check to interrupt handler

In reply to Sasha Levin

From: Ian Abbott <[email protected]>

[ Upstream commit e90d0550c5b3056c8821f5cd714f80902de0fca6 ]

The driver requests an interrupt handler for the device, after setting device registers to disable interrupt generation. The interrupt handler should not be called prematurely unless the user-configured I/O port base address and/or IRQ number are incorrect or the hardware is bad.

For safety, check the dev->attached flag in the interrupt handler to ensure the device has been fully set up, avoiding a possible null pointer dereference of dev->read_subdev.

---

LLM Generated explanations, may be completely bogus:

## Phase 1: Commit message forensics

**Step 1.1: Subject line**
Record: **[comedi/das6402] [Add] sanity check in the IRQ handler to avoid a NULL deref of dev->read_subdev before attach completes**

**Step 1.2: Tags**
Record:
- Reported-by: Jaeyoung Chung <[email protected]>
- Reported-by: Sangyun Kim <[email protected]>
- Reported-by: Kyungwook Boo <[email protected]>
- `Link: https://lore.kernel.org/lkml/20260610115912.780131-1-
[email protected]/` (original bug report)
- Signed-off-by: Ian Abbott <[email protected]> (author; comedi maintainer)
- `Link:
https://patch.msgid.link/[email protected]`
- Signed-off-by: Greg Kroah-Hartman <[email protected]>
- No Fixes: tag (expected for this review)
- No Cc: stable (expected; not a negative signal)
- No Reviewed-by / Tested-by / Acked-by
- Three independent reporters (SNU) is a strong real-world signal

**Step 1.3: Body**
Record:
- **Bug:** IRQ handler is registered in das6402_attach() before subdevices (and dev->read_subdev) are set up. dev->attached is only set later in core postconfig.
- **Symptom:** NULL pointer dereference of dev->read_subdev / s->async if an IRQ arrives early.
- **Trigger (author):** user-configured I/O base and/or IRQ wrong, or bad hardware. The original report also frames it as any IRQ between request_irq() and read_subdev assignment.
- **Root cause:** handler immediately does s = dev->read_subdev; async = s->async; with no attached/NULL check.
- **Version info:** none in the message. Blame shows the deref pattern since 2014.

**Step 1.4: Hidden bug fix?**
Record: **Not hidden.** It is an explicit NULL-deref guard. Cover
letter: “Add/fix sanity check in ISA drivers to avoid null-ptr-deref.” Original report title: **KASAN null-ptr-deref**.

---

## Phase 2: Diff analysis

**Step 2.1: Inventory**
Record:
- File: drivers/comedi/drivers/das6402.c (+8 / −2)
- Function: das6402_interrupt()
- Scope: **single-file surgical fix**

**Step 2.2: Code flow**
Record: **Before:** on every IRQ, immediately dereference dev->read_subdev and s->async. **After:** if !dev->attached, return IRQ_NONE; only then load async/cmd. Assigning s = dev->read_subdev before the check is a pointer copy, not a deref.

**Step 2.3: Bug mechanism**
Record: **[NULL pointer dereference / memory safety]** in IRQ context. request_irq() runs in das6402_attach() before comedi_alloc_subdevices() and dev->read_subdev = s. Core sets dev->attached = true only in comedi_device_postconfig() after attach returns. On a premature IRQ, read_subdev is still NULL → s->async oops.

Detach also sets attached = false **before** comedi_legacy_detach() → free_irq(), so the same check covers the teardown window.

**Step 2.4: Fix quality**
Record: **Obviously correct** and the established comedi pattern (comedi_parport, ni_660x, many ISA drivers). Minimal. Regression risk is low: returning IRQ_NONE before attach is the intended “not ours yet” behavior. DAS6402_CTRL_INTE is only set in das6402_ai_cmd(), which cannot run until the device is attached, so legitimate acquisition IRQs are unaffected.

This is patch 02/11 of a per-driver series; das6402 did not already have a misplaced attached check (unlike pcl818/dt2811 “Fix sanity check” patches). No follow-up was needed for this file.

---

## Phase 3: Git history

**Step 3.1: Blame**
Record:
- Handler exists since 48f16b6aeafdfb (2009).
- NULL deref of read_subdev introduced by d1d24cb65ee360 (“staging:
comedi: das6402: read analog input samples in interrupt handler”, Hartley Sweeten, 2014-11-13) → **v3.19-rc1**.
- Driver rewrite: 79e5e6addbb18b (v3.15-rc1).
- Comedi left staging: 8ffdff6a8cfbd (around v5.13).
- Long-lived bug, not recent new code.

**Step 3.2: Fixes: tag**
Record: **None.** Introducing commit d1d24cb65ee360 **is** an ancestor of this tree.

**Step 3.3: File history**
Record (recent on this file):
- e90d0550c5b30 this fix
- 2ddb4c5699129 I/O base sanity (independent; not a prerequisite)
- 70f2b28b5243d bit-shift OOB fix

Standalone. Series is 11 independent per-driver IRQ guards.

**Step 3.4: Author**
Record: Ian Abbott is **the comedi maintainer** (118 comedi commits in this tree). Sibling comedi_parport fix 17221216ae8ce is the same class and was explicitly Cc: stable + syzbot.

**Step 3.5: Dependencies**
Record: **None.** Uses existing dev->attached and IRQ_NONE. Applies standalone.

git merge-base --is-ancestor e90d0550c5b30 HEAD → already in this checkout (v7.3-rc4). That is not treated as “already selected for stable.”

---

## Phase 4: Mailing list / external research

**Step 4.1: Original discussion**
Record:
- b4 dig -c e90d0550c5b30 →
https://patch.msgid.link/[email protected]
- Series: **v1 only**, [PATCH 02/11], cover comedi: Add/fix sanity check in ISA drivers to avoid null-ptr-deref
- Bug report (lkml.iu.edu / lore): Jaeyoung Chung, 2026-06-10, **“comedi: KASAN null-ptr-deref in ISA driver IRQ handlers on early IRQ”**. Names das6402_attach / das6402_interrupt first. Failure:
kernel panic / KASAN when IRQ fires after request_irq() and before read_subdev is set.
- Suggested fix matches this patch (guard handler or move request_irq).
- Mbox: cover + 11 patches, **no NAKs, no reviewer objections**. Greg KH applied it.

**Step 4.2: Recipients (b4 dig -w)**
Record: [email protected], Greg Kroah-Hartman, H Hartley Sweeten, the three reporters. Comedi maintainers were on the patch.

**Step 4.3: Bug report**
Record: Static/code-path KASAN NULL deref in several ISA comedi IRQ handlers. Three reporters. das6402 is the exemplar. Sibling parport case was syzbot-reproduced GPF.

**Step 4.4: Series**
Record: 11 independent driver patches. This one does not need the rest.

**Step 4.5: Stable list**
Record: lore.kernel.org/stable fetch returned 403. Unverified whether someone already nominated it on the stable list. The related parport patch **was** Cc: stable.

---

## Phase 5: Code semantic analysis

**Step 5.1: Functions**
Record: das6402_interrupt() only.

**Step 5.2: Callers**
Record: only request_irq(..., das6402_interrupt, ...) in das6402_attach() (drivers/comedi/drivers/das6402.c:579). **Hard IRQ context.**

**Step 5.3: Callees**
Record: inb, das6402_ai_read_sample, comedi_buf_write_samples, das6402_clear_all_interrupts, comedi_handle_events. After the guard, those only run once attached.

**Step 5.4: Reachability**
Record: Yes, from userspace: Comedi COMEDI_DEVCONFIG attach with I/O base + IRQ (it->options[0] / [1]). Typically privileged. Misconfigured port/IRQ or a spurious IRQ during attach/detach oopses the kernel. das6402_reset() runs before request_irq and leaves CTRL_SOFT_TRIG (no DAS6402_CTRL_INTE); device IRQs are enabled later in das6402_ai_cmd(). So a **correct** board is unlikely to interrupt early; wrong I/O/IRQ, leftover IRQ line, or teardown still can.

**Step 5.5: Similar patterns**
Record: Same if (!dev->attached) guard across many comedi ISA drivers. This series adds/fixes it in 11 of them. Established, not experimental.

---

## Phase 6: Local tree

**Step 6.1: Does the buggy code exist here?**
Record:
- Tree: **v7.3-rc4-27-gf0100363d8c37**, VERSION=7 PATCHLEVEL=3 SUBLEVEL=0 EXTRAVERSION=-rc4 (mainline 7.3-rc, not an LTS branch).
- File and handler exist. Pre-fix handler (parent of e90d0550c5b30) dereferenced s->async unconditionally. Bug introduced **v3.19** (d1d24cb65ee360), long before 7.3.
- Current tree already contains the fix (e90d0550c5b30 is an ancestor of HEAD).

**Step 6.2: Backport difficulty**
Record: **Clean apply** to any tree with this das6402_interrupt() shape (stable since 2014). No structural prerequisites.

**Step 6.3: Related fixes already here**
Record: This exact fix is already in HEAD. No alternate das6402 IRQ NULL-deref fix. 2ddb4c5699129 only restricts I/O base; it does not close the IRQ window.

---

## Phase 7: Subsystem context

**Step 7.1**
Record: **comedi / DAS6402 ISA DAQ driver**. Criticality: **PERIPHERAL** (legacy ISA, CONFIG_COMEDI_DAS6402), but the failure is a **kernel oops in IRQ context**, not a cosmetic driver glitch. Comedi is out of staging.

**Step 7.2**
Record: Mature driver (1999/2014). Recent activity is this class of IRQ/I/O sanity fixes, not a rewrite.

---

## Phase 8: Impact and risk

**Step 8.1: Who is affected**
Record: **Driver-specific / config-specific** (CONFIG_COMEDI_DAS6402). Keithley/Computerboards DAS6402-12/16 and compatibles. Small population, but a crash is still a crash for those users and for anyone attaching with a bad IRQ/port.

**Step 8.2: Trigger**
Record: Attach with IRQ configured, then an IRQ before attached (bad I/O/IRQ, spurious line, or the attached=false…free_irq detach window). Not every boot on healthy hardware. Privileged attach, not unprivileged syscall spray like a VFS bug; still a real oops and KASAN- class memory-safety issue.

**Step 8.3: Failure mode**
Record: **NULL deref in hardirq → KASAN / oops / panic**. Severity:
**CRITICAL** (crash), limited blast radius (this driver).

**Step 8.4: Risk-benefit**
Record:
- **Benefit:** prevents IRQ-time oops on a real, reported path; same pattern already used for stable on comedi_parport.
- **Risk:** very low (8 lines, early return, no locking/API change).
- **Ratio:** favorable.

---

## Phase 9: Synthesis

**Step 9.1: Evidence**

FOR:
- KASAN-reported NULL deref in an interrupt handler (oops/panic)
- Three reporters; das6402 is the primary example in the report
- 8-line, obviously correct guard used across comedi
- Maintainer-authored; applied by Greg KH
- Bug present since ~v3.19; no missing prerequisites in this tree
- Sibling parport fix of the same class was Cc: stable

AGAINST:
- Niche ISA DAQ hardware
- Healthy boards with correct I/O/IRQ are unlikely to interrupt before DAS6402_CTRL_INTE is set
- No Fixes: / Cc: stable on this commit (expected; not used as a NO)
- No extra Reviewed-by besides maintainer + Greg

UNRESOLVED:
- Could not search lore.kernel.org/stable (403)
- No C reproducer in the SNU mail (code-path / KASAN analysis, not syzbot)

**Step 9.2: Stable rules**
1. Obviously correct and tested? **PASS** (standard dev->attached guard; applied upstream)
2. Real user-affecting bug? **PASS** (KASAN NULL deref / panic on early IRQ)
3. Important (crash/security/corruption/deadlock)? **PASS** — crash in IRQ handler
4. Small and contained? **PASS** — one function, +8/−2
5. No new features/APIs? **PASS**
6. Can apply to this tree? **PASS** — file and handler exist; patch is already the current code

**Step 9.3: Exception category**
Record: None needed (not a device-ID/quirk/DT/build/doc exception). It is a straightforward crash fix.

**Step 9.4: Decision**
This tree is **Linux 7.3-rc4**. The DAS6402 IRQ handler and the read_subdev deref have been in this lineage since v3.19. The change is a small, standard NULL-deref guard for a KASAN-confirmed oops. It meets stable criteria on technical merit. Niche hardware lowers breadth of impact, not the fact that the failure is a kernel crash.

---

### What it solves for stable users
If das6402 is loaded and attached with an IRQ, the handler can run after request_irq() but before dev->read_subdev is set (and while dev->attached is still false). The old handler immediately did s->async and oopsed. The patch returns IRQ_NONE until attach is complete.

### Risk vs benefit
Benefit is avoiding an IRQ-context oops; risk is an 8-line early return that does not change the post-attach command path (CTRL_INTE only in das6402_ai_cmd()).

### Concerns
No backport rework, no series dependency. Apply is clean on this das6402.c.

---

Verification:
- [Phase 1] Parsed tags: 3× Reported-by (SNU), lore bug Link, Ian Abbott
+ Greg KH SOBs; no Fixes/Cc:stable
- [Phase 2] Diff: +8/−2 in das6402_interrupt(); defer s->async until dev->attached
- [Phase 2] Confirmed DAS6402_CTRL_INTE only in das6402_ai_cmd(); reset uses CTRL_SOFT_TRIG before request_irq
- [Phase 2] Confirmed detach sets attached = false then comedi_legacy_detach() → free_irq()
- [Phase 3] git describe HEAD → v7.3-rc4-27-gf0100363d8c37; Makefile 7.3.0-rc4
- [Phase 3] git blame: deref from d1d24cb65ee360 (v3.19-rc1); handler from 2009/2014
- [Phase 3] git merge-base --is-ancestor d1d24cb65ee360 HEAD → introducing commit in this tree
- [Phase 3] git merge-base --is-ancestor e90d0550c5b30 HEAD → this commit already in HEAD (ignored as “already selected”)
- [Phase 3] Pre-fix handler via git show e90d0550c5b30^:drivers/comedi/drivers/das6402.c matches the candidate diff
- [Phase 3] Ian Abbott: 118 comedi commits; sibling 17221216ae8ce had Cc: stable + syzbot
- [Phase 4] b4 dig -c e90d0550c5b30 → msgid 20260618102949.26607-3; series v1 02/11
- [Phase 4] b4 dig -a: v1 only; b4 dig -w: Greg KH + Hartley Sweeten
+ reporters
- [Phase 4] Mbox: cover letter “null-ptr-deref”; no NAK/review objections
- [Phase 4] Original report fetched from lkml.iu.edu: KASAN null-ptr- deref, das6402 listed first
- [Phase 4] lore.kernel.org WebFetch 403; stable-list search UNVERIFIED
- [Phase 5] das6402_interrupt callers: only request_irq in das6402_attach
- [Phase 6] Current das6402.c already has if (!dev->attached); buggy form exists at parent of this commit
- [Phase 7] CONFIG_COMEDI_DAS6402 in drivers/comedi/Kconfig; peripheral ISA driver, not staging
- [Phase 8] Failure mode: NULL deref in hardirq → oops/panic, severity CRITICAL, population driver-specific
- UNVERIFIED: whether this SHA was discussed on stable@ (lore 403)

The fix is small, surgical, and meets all stable kernel criteria.

**YES**

 drivers/comedi/drivers/das6402.c | 10 ++++++++--
 1 file changed, 8 insertions(+), 2 deletions(-)
drivers/comedi/drivers/das6402.c +8 -2
index 7660487e563c5..f9a778390ac93 100644
@@ -173,10 +173,16 @@ static irqreturn_t das6402_interrupt(int irq, void *d)
 {
 	struct comedi_device *dev = d;
 	struct comedi_subdevice *s = dev->read_subdev;
-	struct comedi_async *async = s->async;
-	struct comedi_cmd *cmd = &async->cmd;
+	struct comedi_async *async;
+	struct comedi_cmd *cmd;
 	unsigned int status;
 
+	if (!dev->attached)
+		return IRQ_NONE;
+
+	async = s->async;
+	cmd = &async->cmd;
+
 	status = inb(dev->iobase + DAS6402_STATUS_REG);
 	if ((status & DAS6402_STATUS_INT) == 0)
 		return IRQ_NONE;
Signature · 1 line
2.53.0
author maintainer
#72 lore raw

PATCH 1/1 ipack: ipoctal: add rwsem to guard against TOCTOU in remove path

In reply to Sasha Levin

From: Pei Xiao <[email protected]>

[ Upstream commit 7d3a708af7f4e2af9e114d731bd60d30c1ec884e ]

The "removed" flag check in each tty op has a TOCTOU race with __ipoctal_remove(): the device could be removed between the flag check and the subsequent access to hardware resources (channel registers via iowrite8, or xmit_buf in write_tty).

Close this race by introducing a read-write semaphore (remove_sem). The tty ops acquire the read lock via guard(rwsem_read) for the full duration of the operation, while __ipoctal_remove() acquires the write lock via scoped_guard(rwsem_write) when setting the removed flag. This ensures that once removed is true, no in-flight tty op can still be accessing resources that are about to be freed by the remove path.

---

LLM Generated explanations, may be completely bogus:

The local tree is **v7.3-rc4** (Makefile 7.3.0-rc4). The buggy removed flag is present here (parent UAF fix b6b5d64cb161a), and this commit closes a real TOCTOU on that flag.

---

## PHASE 1: COMMIT MESSAGE FORENSICS

**Step 1.1: PARSE THE SUBJECT LINE**
Record: **[ipack/ipoctal] [add] [rwsem to close TOCTOU between removed check and hardware access in the remove path]**

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**
Record:
- **Link:** https://patch.msgid.link/fbce75010a0f0a3a3709a5e06fd0ffd19c [email protected]
- **Signed-off-by:** Pei Xiao <[email protected]> (author)
- **Signed-off-by:** Greg Kroah-Hartman (char-misc maintainer; applied the patch)
- No **Fixes:**, **Reported-by:**, **Tested-by:**, **Reviewed-by:**, **Acked-by:**, or **Cc: stable** on *this* commit (absence is expected)
- Parent commit b6b5d64cb161a *does* have Reported-by: Shuangpeng Bai,
Closes: lore KASAN report, Fixes: 05e5027efc9c

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**
Record:
- **Bug:** unlocked removed flag check in tty ops races with __ipoctal_remove().
- **Symptom:** device can be removed between the check and iowrite8 / xmit_buf use → MMIO after iounmap (page fault) or use of a freed transmit buffer.
- **Root cause:** check-then-use without a lock that spans both.
- **Fix:** remove_sem rwsem; tty ops take read lock for the whole op; remove takes write lock while setting removed.
- **Version info:** none in the message. Parent UAF bug dates to the 2012 staging move; this TOCTOU exists only after the parent’s removed flag.

**Step 1.4: DETECT HIDDEN BUG FIXES**
Record: **Not hidden.** Explicit race/TOCTOU fix. “Add rwsem” is the synchronization change that closes the window.

---

## PHASE 2: DIFF ANALYSIS

**Step 2.1: INVENTORY THE CHANGES**
Record:
- **File:** drivers/ipack/devices/ipoctal.c — **+10 / −6** (16 lines)
- **Functions/data:** struct ipoctal (remove_sem); ipoctal_port_activate, ipoctal_write_tty, ipoctal_set_termios, ipoctal_hangup, ipoctal_shutdown; ipoctal_probe (init_rwsem); __ipoctal_remove (scoped_guard around removed = true)
- **Scope:** single-file surgical fix

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**
Record:
- **Before:** each listed tty op reads ipoctal->removed with no lock, then touches MMIO/xmit_buf. Remove stores removed = true then free_irq, tty_port_free_xmit_buf, tty_port_destroy.
- **After:** ops hold down_read for the whole op via guard(rwsem_read). Remove’s down_write waits for in-flight readers, then sets removed. Later readers see removed == true and skip hardware. Then remove frees resources.
- **Path:** device-remove vs concurrent tty ops (write, termios, hangup, shutdown, port activate).

**Step 2.3: IDENTIFY THE BUG MECHANISM**
Record: **[Synchronization / race — TOCTOU]** Flag check without a lock that covers the subsequent access. Writer waits for readers, then publishes removed; new readers bail out. Category (c) not involved (no get/put change here). Complements parent kref/removed UAF fix.

**Step 2.4: ASSESS THE FIX QUALITY**
Record:
- **Quality:** classic rwsem lifetime barrier; guard/scoped_guard make unlock-on-return automatic. Write lock is only held while storing the flag, which is enough because later readers observe removed.
- **Verified non-nesting:** ipoctal_hangup → tty_port_hangup → tty_port_shutdown calls **tty_port_operations.shutdown**, which this driver does **not** set. tty_operations.shutdown (ipoctal_shutdown) runs from release_tty(), a different path. No recursive down_read on the same task.
- **tty_unregister_device** only does device_destroy/cdev_del; it does not take tty_lock. Write lock is dropped before unregister, so hangup’s tty_lock → read lock vs remove’s write lock → unregister is not a held-lock inversion.
- **Regression risk:** low. down_read in write_tty is legal (tty write may sleep). IRQ handler does not take the rwsem; remove still free_irq after publishing removed, which waits out in-flight IRQs.
- **Incompleteness (not a reason to reject):** write_room / chars_in_buffer / get_icount still unlocked; they only touch channel fields kept alive by the parent kref, not MMIO/xmit_buf.

---

## PHASE 3: GIT HISTORY INVESTIGATION

**Step 3.1: BLAME THE CHANGED LINES**
Record:
- removed and kref: **b6b5d64cb161a** (Pei Xiao, 2026-07-17, “fix UAF, null-ptr-deref, and use-after-free in cleanup on remove”).
- remove_sem: **this commit 7d3a708af7f4e**.
- Driver core (struct ipoctal): 2012 (ba4dc61fe8c545 staging).
- **The TOCTOU is in code added by the immediate parent**, not in ancient unlocked MMIO.

**Step 3.2: FOLLOW THE FIXES: TAG**
Record: **No Fixes: tag on this commit.** Parent b6b5d64cb161a has Fixes: 05e5027efc9c (“Staging: ipack: move out of staging”, 2012-11-16). git merge-base --is-ancestor confirms 05e5027efc9c, b6b5d64cb161a, and 7d3a708af7f4e are all ancestors of HEAD.

**Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES** Record:
- Direct parent of this commit **is** b6b5d64cb161a. Same author, consecutive timestamps (10:01:09 / 10:01:10).
- Mailing-list subject: **[PATCH 2/2]**. Patch 1 is the UAF/kref/removed flag; patch 2 is this rwsem.
- No later commits on this file after 7d3a708af7f4e.
- **Standalone for this tree: yes**, because patch 1 is already here. Not standalone on a tree that lacks b6b5d64cb161a.

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**
Record: Pei Xiao is **not** the ipack maintainer; only these two ipack commits. Greg KH applied both. Reporter Shuangpeng Bai iterated on the series.

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS** Record:
- **Hard dependency:** removed, the flag checks, kref_init context in probe. All from b6b5d64cb161a, **present in this tree**.
- guard(rwsem_read) / scoped_guard(rwsem_write):
DEFINE_LOCK_GUARD_1 in include/linux/rwsem.h (includes cleanup.h) — **present here**.
- Can apply standalone **on this tree: yes**.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**
Record:
- **b4 dig -c 7d3a708af7f4e:** matched series; lore msgid fbce75010a0f0 [email protected] (and committed link with .1782870760).
- **b4 dig -a:** evolved RFC → PATCH → **PATCH 1/2 + 2/2**. This commit is 2/2.
- Thread started as **[BUG] KASAN: slab-use-after-free in ipoctal_write_tty** (Shuangpeng Bai, 14 Jun 2026), QEMU TPCI200/IP- Octal, repro: open tty then /sys/bus/pci/drivers/tpci200/unbind.
- Incomplete earlier versions produced: NULL deref in write, page fault in ipoctal_set_termios → iowrite8, UAF in ipoctal_cleanup.
- **Shuangpeng on the 1/2+2/2 series (30 Jun 2026): “I tried this patch on my side and no bug is triggered.”**
- **No NAKs.** No reviewer asked for Cc: stable. Greg applied the series.

**Step 4.2: CHECK WHO REVIEWED THE PATCH**
Record: **b4 dig -w:** To/Cc were Pei Xiao, [email protected], linux-kernel@. Not a dedicated ipack list. Greg KH (subsystem maintainer) applied it after Pei asked him to look at cover.1782870760.

**Step 4.3: SEARCH FOR THE BUG REPORT**
Record:
- KASAN slab-UAF in ipoctal_write_tty via n_tty_write / ksys_write, freed from tpci200_pci_remove → unbind_store.
- Repro gist referenced in-thread. **Root-only sysfs unbind**, QEMU not physical hardware.
- Greg (15–16 Jun 2026): unbind is a testing path; **“As it's not a real issue for drivers like this, it's a very low priority”**, but he would review patches. He still merged the series.

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**
Record: **2-patch series.** Patch 1: kref, carrier_owner cache, removed flag, NULL xmit_buf check. Patch 2 (this): rwsem around that flag. Both in this tree. Tester signed off on the combination.

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**
Record: **UNVERIFIED** for lore.kernel.org/stable (HTTP 403). No `Cc:
stable` in the thread mbox. No evidence of a prior stable NAK.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

**Step 5.1: IDENTIFY KEY FUNCTIONS IN THE DIFF**
Record: ipoctal_port_activate, ipoctal_write_tty, ipoctal_set_termios, ipoctal_hangup, ipoctal_shutdown, ipoctal_probe, __ipoctal_remove; field ipoctal.remove_sem.

**Step 5.2: TRACE CALLERS**
Record:
- ipoctal_write_tty ← tty_operations.write ← userspace write() on the tty.
- ipoctal_set_termios ← tty ioctl (reporter: tty_mode_ioctl).
- ipoctal_port_activate ← tty_port_operations.activate ← ipoctal_open → tty_port_open.
- ipoctal_hangup ← tty_operations.hangup ← __tty_hangup.
- ipoctal_shutdown ← tty_operations.shutdown ← release_tty().
- __ipoctal_remove ← ipoctal_remove ← ipack_driver_ops.remove (unbind / PCI remove / module teardown).
- **Reachable from userspace tty ops + admin device removal.**

**Step 5.3: TRACE CALLEES**
Record: iowrite8 / ipoctal_reset_channel, ipoctal_copy_write_buffer (xmit_buf), tty_port_hangup / tty_port_set_initialized, free_irq via bus ops, tty_port_free_xmit_buf.

**Step 5.4: FOLLOW THE CALL CHAIN**
Record: Open /dev/tty* on IP-OCTAL, keep fd, remove carrier (unbind, rmmod, PCI remove). **Yes, userspace-reachable.** Unprivileged write/ioctl; removal needs privileges or hotplug. Failure is kernel oops/UAF, not just ENODEV.

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**
Record: Same unlocked if (ipoctal->removed) was in all hardware- touching tty ops from patch 1; this patch wraps all of them. No sibling ipack device driver with the same pattern.

---

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

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?**
Record: **Yes.** HEAD is v7.3-rc4-27-gf0100363d8c37, version **7.3.0-rc4**. struct ipoctal has removed from b6b5d64cb161a (in 7.3-rc1 char-misc merge). Without this commit, those checks are unlocked. Bug introduced **in this 7.3 cycle** by patch 1, not after this tree branched.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**
Record: **Clean apply on this tree** (same file layout, guard/scoped_guard/kref_init present). Context uses kzalloc_obj from a treewide change; this hunk only adds init_rwsem next to kref_init from patch 1.

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**
Record: Parent UAF fix **is** here. No alternate TOCTOU fix. No later revert or follow-up on this file.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

**Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY**
Record: **drivers/ipack (IndustryPack / GE IP-OCTAL UART).** **PERIPHERAL.** CONFIG_SERIAL_IPOCTAL depends on IPACK_BUS && TTY, **default n**. Used in industrial/HEP-style carrier boards (CERN/GE history), also QEMU TPCI200.

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**
Record: **Mature / low churn.** Until this 2026 series, last functional ipoctal work was small tty API conversions and older leak/race fixes. Not a hot new subsystem.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

**Step 8.1: DETERMINE WHO IS AFFECTED**
Record: **Driver-specific / config-specific** (CONFIG_SERIAL_IPOCTAL). Not universal.

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**
Record: Concurrent tty op and __ipoctal_remove. Reproduced with **root sysfs unbind** while fd open. Same remove path as PCI remove / module unload. Unprivileged user cannot unbind; they can issue write/ioctl on an already-open fd. Race window is real but narrow.

**Step 8.3: DETERMINE THE FAILURE MODE SEVERITY**
Record: **Oops / KASAN UAF / MMIO page fault.** **HIGH** when it fires (kernel crash). Not a generic unprivileged LPE path. Greg called the underlying unbind-vs-open-fd class **low priority** for this driver.

**Step 8.4: CALCULATE RISK-BENEFIT RATIO**
Record:
- **Benefit:** medium-high *if* patch 1 is present (this tree):
completes an incomplete UAF mitigation; prevents residual oops on remove-with-open-tty.
- **Risk:** low — ~10 lines, one file, scoped guards, no API change.
- **Ratio:** favorable **on this tree**, because shipping patch 1 without patch 2 leaves a known TOCTOU.

---

## PHASE 9: FINAL SYNTHESIS

**Step 9.1: COMPILE THE EVIDENCE**

**For backporting to this tree:**
- Real TOCTOU: check removed then access MMIO/xmit_buf while remove frees them.
- Failure is oops/UAF (reporter already hit page fault and KASAN on related paths).
- Small, obviously correct rwsem barrier; tester confirmed 1/2+2/2 no longer crashes.
- Prerequisite patch 1 **is in this tree**; without this commit the 7.3 removed flag is racy.
- Greg KH applied it; no NAKs.
- Matches stable “race with severe outcome” guidance.

**Against:**
- Explicit **PATCH 2/2** (but dependency is already here).
- Niche default n IndustryPack UART.
- Trigger in the report is root sysfs unbind; Greg called that class low priority.
- This commit has no Fixes:/Reported-by of its own (expected).
- Not a core-kernel path.

**Unresolved:**
- Stable-list search 403 (no confirmation anyone asked stable@).
- No independent reproduction of *only* the TOCTOU (series tested as a whole).

**Step 9.2: APPLY THE STABLE RULES CHECKLIST**
1. Obviously correct and tested? **PASS** — lock spans check+use; Shuangpeng retested the series.
2. Fixes a real bug that affects users? **PASS** — race on this tree’s removed flag; same remove-vs-open-tty path as the KASAN report.
3. Important issue? **PASS** — oops/UAF/page fault, not a style change. Importance is limited by hardware rarity, not by bug class.
4. Small and contained? **PASS** — one file, +10/−6.
5. No new features or APIs? **PASS**.
6. Can apply to the local tree? **PASS** — parent, removed, and guard(rwsem_*) all exist here.

**Step 9.3: CHECK FOR EXCEPTION CATEGORIES**
Record: **None** (not an ID/quirk/DT/build/doc exception). Qualifies as a normal race/UAF-completion fix.

**Step 9.4: MAKE YOUR DECISION**

This tree is 7.3-rc4 and already contains the parent UAF fix that added an unlocked removed flag. Leaving that flag without remove_sem re- opens MMIO-after-unmap and freed-xmit_buf on remove-while-tty-open. The patch is small, correct, and was tested as the second half of that series. That is enough technical merit to backport it **into this tree**.

It would be the wrong patch to take **alone** on a tree that still lacks b6b5d64cb161a; that is not this tree.

---

## Detailed explanation

The parent commit keeps struct ipoctal alive with a kref and uses removed to skip MMIO after unmap. That check is TOCTOU:
__ipoctal_remove() can set removed and free xmit_buf/unmap BARs between the load of the flag and iowrite8 / buffer use. The rwsem makes “still using hardware” and “publish removed” exclusive. That is a real crash class on a path the reporter already exercised.

Stable rules are met: real bug, crash severity, tiny diff, no new API, applies here. Peripheral hardware and a root-oriented repro lower *breadth*, not correctness. Risk is low vs the benefit of not shipping the incomplete flag.

---

## Verification
- **[Phase 1]** Parsed tags: Link msgid, SOB Pei Xiao + Greg KH; no Fixes/Reported-by on this commit; parent has Reported-by Shuangpeng Bai + Fixes 05e5027efc9c
- **[Phase 2]** Diff: drivers/ipack/devices/ipoctal.c +10/−6; rwsem around five tty ops + probe init + remove store
- **[Phase 2]** Confirmed tty_port_hangup calls port .shutdown, not tty_operations.shutdown; ipoctal port ops have no .shutdown
- **[Phase 2]** tty_unregister_device is device_destroy/cdev_del only
- **[Phase 3]** git describe HEAD → v7.3-rc4-27-gf0100363d8c37; make kernelversion → 7.3.0-rc4
- **[Phase 3]** git merge-base --is-ancestor b6b5d64, 7d3a708, 05e5027 → all in HEAD
- **[Phase 3]** git log -1 7d3a708^ → parent is exactly the UAF/removed commit
- **[Phase 3]** blame: removed from b6b5d64; remove_sem from 7d3a708
- **[Phase 4]** b4 dig -c 7d3a708af7f4e / -a / -w / -m: PATCH 2/2, RFC→v2 series, recipients Pei/Shuangpeng/lkml
- **[Phase 4]** mbox: KASAN report, Greg low-priority comment, Shuangpeng “no bug is triggered” on 1/2+2/2
- **[Phase 4]** lore.kernel.org WebFetch/curl: **403** — discussion taken from b4 mbox instead
- **[Phase 5]** Callers traced in ipoctal.c + tty_io.c / tty_port.c
- **[Phase 6]** Local file has removed + remove_sem; no later follow-up on this file
- **[Phase 7]** Kconfig: SERIAL_IPOCTAL default n, depends IPACK_BUS && TTY
- **[Phase 8]** Failure mode: UAF/oops/PF on remove vs open tty; trigger requires device removal
- **UNVERIFIED:** whether anyone mailed stable@ about this exact commit (lore/stable 403)

**YES**

 drivers/ipack/devices/ipoctal.c | 16 ++++++++++------
 1 file changed, 10 insertions(+), 6 deletions(-)
drivers/ipack/devices/ipoctal.c +10 -6
index 474b58858dca6..aab303c4a9837 100644
@@ -11,6 +11,7 @@
 #include <linux/module.h>
 #include <linux/interrupt.h>
 #include <linux/kref.h>
+#include <linux/rwsem.h>
 #include <linux/sched.h>
 #include <linux/tty.h>
 #include <linux/serial.h>
@@ -54,6 +55,7 @@ struct ipoctal {
 	u8 __iomem			*int_space;
 	struct kref			kref;
 	struct module			*carrier_owner;
+	struct rw_semaphore		remove_sem;
 	bool				removed;
 };
 
@@ -81,7 +83,7 @@ static int ipoctal_port_activate(struct tty_port *port, struct tty_struct *tty)
 	channel = dev_get_drvdata(tty->dev);
 	ipoctal = chan_to_ipoctal(channel, tty->index);
 
-
+	guard(rwsem_read)(&ipoctal->remove_sem);
 	if (ipoctal->removed)
 		return -ENODEV;
 
@@ -476,7 +478,7 @@ static ssize_t ipoctal_write_tty(struct tty_struct *tty, const u8 *buf,
 	struct ipoctal *ipoctal = chan_to_ipoctal(channel, tty->index);
 	size_t char_copied;
 
-
+	guard(rwsem_read)(&ipoctal->remove_sem);
 	if (ipoctal->removed || !channel->tty_port.xmit_buf)
 		return 0;
 
@@ -522,7 +524,7 @@ static void ipoctal_set_termios(struct tty_struct *tty,
 	struct ipoctal *ipoctal = chan_to_ipoctal(channel, tty->index);
 	speed_t baud;
 
-
+	guard(rwsem_read)(&ipoctal->remove_sem);
 	if (ipoctal->removed)
 		return;
 
@@ -660,7 +662,7 @@ static void ipoctal_hangup(struct tty_struct *tty)
 		return;
 
 	ipoctal = chan_to_ipoctal(channel, tty->index);
-
+	guard(rwsem_read)(&ipoctal->remove_sem);
 	if (ipoctal->removed)
 		return;
 
@@ -686,7 +688,7 @@ static void ipoctal_shutdown(struct tty_struct *tty)
 		return;
 
 	ipoctal = chan_to_ipoctal(channel, tty->index);
-
+	guard(rwsem_read)(&ipoctal->remove_sem);
 	if (ipoctal->removed)
 		return;
 
@@ -736,6 +738,7 @@ static int ipoctal_probe(struct ipack_device *dev)
 		return -ENOMEM;
 
 	kref_init(&ipoctal->kref);
+	init_rwsem(&ipoctal->remove_sem);
 
 	ipoctal->dev = dev;
 	ipoctal->carrier_owner = dev->bus->owner;
@@ -755,7 +758,8 @@ static void __ipoctal_remove(struct ipoctal *ipoctal)
 {
 	int i;
 
-	ipoctal->removed = true;
+	scoped_guard(rwsem_write, &ipoctal->remove_sem)
+		ipoctal->removed = true;
 
 	ipoctal->dev->bus->ops->free_irq(ipoctal->dev);
 
Signature · 1 line
2.53.0
author maintainer
#73 lore raw

PATCH 1/1 serial: 8250: force synchronous probe for the ISA and PNP drivers

In reply to Sasha Levin

From: Rahul Bukte <[email protected]>

[ Upstream commit 31e11af34e2c7cc61e25533ab877b1f9cc3eb528 ]

On x86_64 defconfig, booting with driver_async_probe=serial hangs in early init. The 8250 PNP driver is put onto the async probe pool. serial8250_register_8250_port() runs in a kworker concurrently with the ISA registration done from the serial8250_init() initcall resulting in a deadlock or NULL dereference.

- Deadlock: serial_core_register_port() holds port_mutex across serial_core_add_one_port()
uart_configure_port()
autoconfig_irq()
probe_irq_on()
async_synchronize_full(),
which waits for the async probe pool to drain.

The async PNP worker reaches the "port already in use" check and tries to unregister it. serial8250_register_8250_port()
uart_remove_one_port()
serial_core_unregister_port()
This blocks on port_mutex.
The init thread waits for the worker and the worker waits for the init thread.

- NULL deref: when the worker instead observes a slot whose port.dev is set but whose port_dev has not yet been populated, it hits the null pointer on the call to serial_core_get_ctrl_dev() in serial_core_unregister_port().

---

LLM Generated explanations, may be completely bogus:

The local tree is **v7.3-rc4**. The two-line PROBE_FORCE_SYNCHRONOUS change is a real deadlock/NULL-deref fix on the 8250 ISA vs PNP probe path, and the affected code is present here.

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

**Step 1.1: PARSE THE SUBJECT LINE**
Record: [serial/8250] [force] force synchronous probe for the ISA and PNP drivers

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**
Record:
- Signed-off-by: Rahul Bukte <[email protected]> (author)
- `Link: https://patch.msgid.link/20260610054130.2825182-1-
[email protected]`
- Signed-off-by: Greg Kroah-Hartman <[email protected]> (tty maintainer applied it)
- No Fixes:, Reported-by:, Tested-by:, Reviewed-by:, Acked- by:, or Cc: stable (absence of Fixes/Cc-stable is expected for this review)

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**
Record:
- **Bug:** On x86_64 defconfig, driver_async_probe=serial hangs in early init. The 8250 PNP driver (name = "serial") is queued for async probe while serial8250_init() still registers ISA ports.
- **Symptom/failure mode:**
1. **Deadlock:** ISA serial_core_register_port() holds port_mutex through autoconfig_irq() → probe_irq_on() → async_synchronize_full(). The async PNP worker hits the in-use port path and blocks in serial_core_unregister_port() on the same mutex.
2. **NULL deref:** The worker sees port.dev set but port_dev still NULL, then serial_core_get_ctrl_dev(port_dev) oopses.
- **Version information:** None beyond “x86_64 defconfig”.
- **Root cause:** Concurrent ISA initcall registration vs async PNP probe of the same 8250 port slots.

**Step 1.4: DETECT HIDDEN BUG FIXES**
Record: Not a disguised cleanup. It is an explicit deadlock/oops fix. The in-thread note “Found while experimenting with driver_async_probe=* to improve boot time” only explains how it was found, not that it is theoretical.

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

**Step 2.1: INVENTORY THE CHANGES**
Record:
- drivers/tty/serial/8250/8250_platform.c: +1 (serial8250_isa_driver.driver.probe_type)
- drivers/tty/serial/8250/8250_pnp.c: +1 (serial_pnp_driver.driver.probe_type)
- Two insertions total. Surgical, two-file, same subsystem.

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**
Record:
- **Before:** Both drivers use default PROBE_DEFAULT_STRATEGY. driver_allows_async_probing() then honors driver_async_probe= / module async-probe, so PNP probe can run in a kworker while serial8250_init() is still in the initcall.
- **After:** PROBE_FORCE_SYNCHRONOUS makes driver_allows_async_probing() return false, so probe stays on the registration thread and cannot overlap ISA uart_add_one_port().

**Step 2.3: IDENTIFY THE BUG MECHANISM**
Record:
- **Category:** Race → deadlock and NULL dereference.
- **Mechanism verified in this tree:**
- serial8250_init() calls serial8250_pnp_init() then later

    `serial8250_register_ports()` which sets `up->port.dev` and calls
    `uart_add_one_port()`.

- serial_core_register_port() holds port_mutex across serial_core_add_one_port() → uart_configure_port() → config_port(). With UPF_AUTO_IRQ (x86 STD_COM*_FLAGS when CONFIG_SERIAL_8250_DETECT_IRQ), that reaches autoconfig_irq() → probe_irq_on() → async_synchronize_full().
- Concurrent PNP: serial_pnp_probe() → serial8250_register_8250_port(). If uart->port.dev is already
set: uart_remove_one_port() → serial_core_unregister_port().
- serial_core_unregister_port() reads port->port_dev and calls serial_core_get_ctrl_dev(port_dev) **before** taking port_mutex. NULL port_dev is an oops. Non-NULL port_dev waits on port_mutex while the init thread waits for async probe → deadlock.

**Step 2.4: ASSESS THE FIX QUALITY**
Record:
- Obviously correct: PROBE_FORCE_SYNCHRONOUS exists specifically so drivers that cannot tolerate async probe stay synchronous, including against driver_async_probe=. Same pattern as i8042 PNP.
- Minimal: two field initializers, no API/behavior change for the default (already synchronous) boot path.
- Regression risk is very low. The only cost is that these two drivers cannot be async-probed, which is the intended workaround.

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

**Step 3.1: BLAME THE CHANGED LINES**
Record:
- ISA platform_driver struct: ffd8e8bd26e94 (“serial: 8250: Extract platform driver”, 2024).
- PNP pnp_driver struct: original tree (1da177e4c3f41, 2005).
- The race is not in newly added probe_type lines; those are the fix. The overlapping register/unregister design is long-standing. The NULL deref specifically needs port_dev / serial_core_get_ctrl_dev(), introduced by 84a9582fd2030 (“serial: core: Start managing serial controllers to enable runtime PM”, in v6.5-rc1).

**Step 3.2: FOLLOW THE FIXES: TAG**
Record: No Fixes: tag. Not applicable. The deadlock ingredients (probe_irq_on() → async_synchronize_full() in 22a9d645677fe; driver_async_probe= in 1ea61b68d0f86) and the serial-core port_dev path are all in this tree.

**Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES** Record:
- Recent 8250_platform/pnp work is refactoring, not a hidden prerequisite series.
- This is standalone (not patch X/Y).
- Follow-up on these files after this commit is only 4f643bef0984b (named initializers in the PNP ID table), unrelated.

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**
Record: Rahul Bukte is not a serial maintainer. This is their only serial commit here; other listed commits are i915 NULL checks. Weight comes from Greg Kroah-Hartman applying it to tty, not from author tenure.

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS**
Record: Standalone. It only needs struct device_driver.probe_type and PROBE_FORCE_SYNCHRONOUS, both present in include/linux/device/driver.h and drivers/base/dd.c in this tree.

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

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**
Record:
- b4 dig -c 31e11af34e2c7:
https://patch.msgid.link/[email protected]
- b4 dig -a: **v1 only**, no later revisions.
- Saved mbox (b4 dig -m) is the original patch only; **no review replies, NAKs, or Cc: stable comments**.
- Extra note in the mail (not in the committed message): “Found while experimenting with driver_async_probe=* … Tested on x86_64 defconfig under QEMU + KVM with driver_async_probe=serial.”
- lore.kernel.org HTTP fetch returned 403; LKML mirror matches the same v1 text.

**Step 4.2: CHECK WHO REVIEWED THE PATCH**
Record (b4 dig -w): To/Cc included Greg Kroah-Hartman, Jiri Slaby, Ilpo Järvinen, linux-serial, linux-kernel. No Reviewed-by landed. Greg applied it (tty maintainer SOB).

**Step 4.3: SEARCH FOR THE BUG REPORT**
Record: No syzbot/bugzilla. Author reproduced a boot hang on x86_64 defconfig + QEMU. That is a concrete trigger, not a static guess.

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**
Record: Standalone. Historical analogue: i8042 PNP PROBE_FORCE_SYNCHRONOUS (same driver-core annotation for probes that cannot run async). A 2018 attempt to mark 8250 PROBE_PREFER_ASYNCHRONOUS shows async 8250 probe has been known to be delicate.

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**
Record: https://lore.kernel.org/stable/?q=... returned 403. Web search found no stable-thread discussion. **UNVERIFIED:** whether anyone already asked for or rejected this on stable@.

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

**Step 5.1: IDENTIFY KEY FUNCTIONS**
Record: No function bodies changed. Annotations on serial8250_isa_driver and serial_pnp_driver. Runtime effect is through driver_allows_async_probing() → probe of serial8250_probe / serial_pnp_probe.

**Step 5.2: TRACE CALLERS**
Record:
- serial_pnp_probe: PNP match during pnp_register_driver() from serial8250_pnp_init() inside serial8250_init() (module_init / boot).
- ISA path: serial8250_register_ports() from the same initcall; platform serial8250_probe from platform_driver_register(&serial8250_isa_driver).
- Context: boot initcall, not a syscall hot path. Reachable on any x86 box with 8250 + PNP (ACPI selects PNP; SERIAL_8250_PNP defaults to y).

**Step 5.3: TRACE CALLEES**
Record: serial_pnp_probe → serial8250_register_8250_port → possible uart_remove_one_port → serial_core_unregister_port. ISA:
uart_add_one_port → serial_core_register_port → uart_configure_port → autoconfig_irq → probe_irq_on → async_synchronize_full.

**Step 5.4: FOLLOW THE CALL CHAIN**
Record: Triggered by the documented kernel parameter driver_async_probe=serial or =*, not by an unprivileged syscall. Still a real boot-time path: x86_64 defconfig sets CONFIG_SERIAL_8250=y, CONFIG_SERIAL_8250_CONSOLE=y, CONFIG_SERIAL_8250_DETECT_IRQ=y. Userspace cannot hit it after boot unless the driver is re-probed.

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**
Record: Many drivers already set PROBE_FORCE_SYNCHRONOUS (i8042 PNP, USB gadget UDC, PHY, Hyper-V, CXL, regulators, etc.). This is the established way to opt a driver out of async probe.

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

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?** Record:
- git describe HEAD: v7.3-rc4-27-gf0100363d8c37
- make kernelversion / Makefile: **7.3.0-rc4**
- Both files and both driver structs exist. serial_core_unregister_port() still dereferences port_dev before port_mutex. serial8250_register_ports() still sets port.dev then calls uart_add_one_port(). probe_irq_on() still calls async_synchronize_full(). x86_64_defconfig still enables SERIAL_8250_DETECT_IRQ.
- NULL-deref window exists since serial-core port_dev (v6.5). Deadlock window with driver_async_probe exists since that cmdline was added (2019) on kernels with IRQ autodetect.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**
Record: Clean apply in this tree. 8250_platform.c exists here (split in ffd8e8bd26e94). probe_type field exists. No conflicting local changes.

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**
Record: No earlier alternate fix for this race. git log --grep='synchronous probe' -- drivers/tty/serial/ only shows this commit.

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

**Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY**
Record: drivers/tty/serial/8250 — **IMPORTANT**. 8250 is the standard PC UART/console driver, not staging/peripheral.

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**
Record: Actively maintained (regular tty/serial 8250 cleanups). The bug is in long-lived register/unregister interaction plus async probe, not in brand-new 8250 code.

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

**Step 8.1: DETERMINE WHO IS AFFECTED**
Record: Config/cmdline specific: CONFIG_SERIAL_8250 + PNP 8250, and driver_async_probe=serial or =*. Default boot (no that parameter) stays synchronous and does not hit it. Population is everyone using that documented parameter on x86 8250, including distro/OEM boot-time experiments.

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**
Record:
- Trigger: boot with driver_async_probe=serial (PNP name) or =*.
- Not default, but documented in kernel-parameters.txt for boot-time optimization.
- Timing-dependent: deadlock vs NULL deref depends on whether port_dev is populated yet.
- Unprivileged users cannot set the cmdline after boot.

**Step 8.3: DETERMINE THE FAILURE MODE SEVERITY** Record:
- Deadlock during early init → **CRITICAL** (boot hang).
- NULL deref in serial_core_get_ctrl_dev() → **CRITICAL** (oops).
- Author reproduced the hang on x86_64 defconfig + QEMU.

**Step 8.4: CALCULATE RISK-BENEFIT RATIO**
Record:
- **Benefit:** High for anyone using driver_async_probe on 8250; prevents boot hang/oops. Default path is unchanged.
- **Risk:** Very low (2 lines, existing driver-core flag, no locking/API change).
- **Ratio:** Strongly in favor of taking it.

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

**Step 9.1: COMPILE THE EVIDENCE**

FOR backporting:
- Real, reproduced boot hang and a NULL deref on a common x86_64 defconfig.
- Failure modes are deadlock and oops (stable-class bugs).
- Two-line, obviously correct use of PROBE_FORCE_SYNCHRONOUS.
- Call paths verified in this 7.3-rc4 tree.
- Applied by the tty maintainer.
- Same annotation pattern as i8042 PNP.
- Default probe behavior is already synchronous; this only blocks a dangerous async override.

AGAINST:
- Trigger is a non-default cmdline, not everyday production boots.
- No Reviewed-by; mailing list had no discussion.
- Author is not a serial regular.
- No syzbot or multi-user reports.

UNRESOLVED:
- Stable@ discussion could not be fetched (HTTP 403).
- Whether a more invasive serial-core locking fix would be “more correct” long-term (not required for this self-contained workaround).

**Step 9.2: APPLY THE STABLE RULES CHECKLIST**
1. Obviously correct and tested? **PASS** — two field sets; tested on QEMU x86_64 defconfig; Greg applied it.
2. Fixes a real bug that affects users? **PASS** — hang/oops with a documented kernel parameter.
3. Important issue? **PASS** — deadlock and NULL deref, severity CRITICAL when triggered.
4. Small and contained? **PASS** — +2 lines, two 8250 driver structs.
5. No new features or APIs? **PASS** — uses existing probe_type.
6. Can apply to the local tree? **PASS** — files, APIs, and buggy paths all exist on v7.3-rc4.

**Step 9.3: CHECK FOR EXCEPTION CATEGORIES**
Record: Not a device-ID/DT/docs/build fix. Closest analogue is a hardware/driver quirk: annotate a driver that cannot safely probe asynchronously.

**Step 9.4: DECISION**
This belongs in this tree. The 8250 ISA/PNP overlap plus probe_irq_on()’s async_synchronize_full() is a genuine boot deadlock and oops once async probe is forced. The workaround is the smallest correct change and does not alter the default synchronous boot path.

===============================================================
Verification
===============================================================
- [Phase 1] Parsed tags: author SOB, Greg KH SOB, lore msgid link; no Fixes/Reported-by/Reviewed-by/Cc-stable.
- [Phase 2] Diff: +1 line each in 8250_platform.c and 8250_pnp.c; probe_type = PROBE_FORCE_SYNCHRONOUS.
- [Phase 2] driver_allows_async_probing(): PROBE_FORCE_SYNCHRONOUS returns false even when cmdline requests async.
- [Phase 2] serial8250_init() order: serial8250_pnp_init() then serial8250_register_ports() then platform_driver_register().
- [Phase 2] serial8250_register_8250_port(): if (uart->port.dev) uart_remove_one_port().
- [Phase 2] serial_core_unregister_port() calls serial_core_get_ctrl_dev(port_dev) before port_mutex.
- [Phase 2] probe_irq_on() calls async_synchronize_full() (kernel/irq/autoprobe.c:39).
- [Phase 2] x86 STD_COM*_FLAGS include UPF_AUTO_IRQ when CONFIG_SERIAL_8250_DETECT_IRQ; x86_64_defconfig sets that.
- [Phase 3] git blame: probe_type lines are this commit; surrounding structs are older.
- [Phase 3] 84a9582fd2030 introduced serial_core_unregister_port (contained in v6.5-rc1).
- [Phase 3] Author has no other 8250 commits; no prerequisite series.
- [Phase 4] b4 dig -c 31e11af34e2c7: original submission found; -a shows v1 only; -w lists Greg/Jiri/Ilpo/linux-serial; -m mbox has no replies.
- [Phase 4] lore.kernel.org WebFetch/curl: 403. LKML mirror confirms same v1 text.
- [Phase 4] UNVERIFIED: stable@ archive contents.
- [Phase 5] PNP driver .name = "serial" matches driver_async_probe=serial. ISA name is serial8250.
- [Phase 5] ACPI Kconfig select PNP; SERIAL_8250_PNP default y.
- [Phase 6] git describe HEAD: v7.3-rc4-27-gf0100363d8c37; Makefile 7.3.0-rc4.
- [Phase 6] git merge-base --is-ancestor 31e11af34e2c7 HEAD: ancestor (used only to confirm the code under review is this change).
- [Phase 8] Failure mode: early-init deadlock or NULL deref; severity CRITICAL when driver_async_probe is used.

The patch is small, correct, and prevents a boot hang/oops on a path that exists in this 7.3-rc4 tree.

**YES**

 drivers/tty/serial/8250/8250_platform.c | 1 +
 drivers/tty/serial/8250/8250_pnp.c      | 1 +
 2 files changed, 2 insertions(+)
drivers/tty/serial/8250/8250_platform.c +1 -0
index fe7ec440ffa58..69d8720fb65bf 100644
@@ -287,6 +287,7 @@ static struct platform_driver serial8250_isa_driver = {
 	.driver		= {
 		.name	= "serial8250",
 		.acpi_match_table = acpi_platform_serial_table,
+		.probe_type = PROBE_FORCE_SYNCHRONOUS,
 	},
 };
 
drivers/tty/serial/8250/8250_pnp.c +1 -0
index 7a837fdf9df13..3f41a9d6cb273 100644
@@ -521,6 +521,7 @@ static struct pnp_driver serial_pnp_driver = {
 	.remove		= serial_pnp_remove,
 	.driver         = {
 		.pm     = pm_sleep_ptr(&serial_pnp_pm_ops),
+		.probe_type = PROBE_FORCE_SYNCHRONOUS,
 	},
 	.id_table	= pnp_dev_table,
 };
Signature · 1 line
2.53.0
#74 lore raw

Re: [PATCH AUTOSEL 6.18-6.12] serial: 8250: force synchronous probe for the ISA and PNP drivers

Sashiko has reviewed this patch and found no issues.
Quoted 15 lines

From: Rahul Bukte <[email protected]>

[ Upstream commit 31e11af34e2c7cc61e25533ab877b1f9cc3eb528 ]

On x86_64 defconfig, booting with driver_async_probe=serial hangs in early init. The 8250 PNP driver is put onto the async probe pool. serial8250_register_8250_port() runs in a kworker concurrently with the ISA registration done from the serial8250_init() initcall resulting in a deadlock or NULL dereference.

- Deadlock: serial_core_register_port() holds port_mutex across

    serial_core_add_one_port()
        uart_configure_port()
            autoconfig_irq()
                probe_irq_on()
Quoted 6 lines

[ ... ]

Sashiko has reviewed this patch and found no issues.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author maintainer
#75 lore raw

PATCH 1/1 wifi: rtlwifi: fix disabling of ASPM for RTL8723BE with AER flooding

In reply to Sasha Levin

From: William Hansen-Baird <[email protected]>

[ Upstream commit 04a46c2dbf3b516c96a1d19b72917b56055ad6c1 ]

commit 77a6407c6ab2 ("wifi: rtlwifi: disable ASPM for RTL8723BE with subsystem ID 11ad:1723") adds code which sets ppsc->support_aspm to false in _rtl_pci_update_default_setting() in order to disable ASPM.
This does not, however, disable ASPM. Rather, it disables driver
control of ASPM, and blocks calls to rtl_pci_enable_aspm()
and rtl_pci_disable_aspm().

In some cases, the pci device supplied to the probe function has ASPM enabled. The code would therefore not disable ASPM, as it means to, but rather just leave it enabled.
This was discovered through testing on a Razer Blade 14 2017.

Implement a new __rtl_pci_disable_aspm(hw) function which does not check ppsc->support_aspm before disabling and call it from rtl_pci_disable_aspm().

Then move the code added in the previous commit to rtl_pci_init_aspm() to allow adding a call to __rtl_pci_disable_aspm(hw).
This makes sure ASPM is disabled while still disabling
driver control of ASPM to block it from being enabled later.

---

LLM Generated explanations, may be completely bogus:

Local tree is **7.3.0-rc4**. The original incomplete RTL8723BE ASPM quirk is in this lineage; this commit is a small, tested hardware-quirk fix that actually clears ASPM instead of only blocking driver control.

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

Step 1.1: PARSE THE SUBJECT LINE

Record: [wifi: rtlwifi:] [fix] [ASPM disable for RTL8723BE with AER flooding actually takes effect]

Step 1.2: PARSE ALL COMMIT MESSAGE TAGS

Record:
- No Fixes: tag (v3 cover letter: “Removed misleading Fixes tag from patch 1”)
- No Reported-by: / Tested-by: on this commit (testing is described in the body: Razer Blade 14 2017)
- Acked-by: Ping-Ke Shih <[email protected]> (rtlwifi maintainer)
- Signed-off-by: William Hansen-Baird (author)
- Signed-off-by: Ping-Ke Shih (maintainer applied to rtw-next)
- `Link: https://patch.msgid.link/20260630141553.785769-2-
[email protected]`
- No Cc: [email protected] (expected for this pipeline; not a negative)
- Pipeline Signed-off-by: Sasha Levin / [Upstream commit ...] ignored per instructions

Step 1.3: ANALYZE THE COMMIT BODY TEXT

Record:
- **Bug:** 77a6407c6ab2 set ppsc->support_aspm = false intending to disable ASPM. That only disables *driver control* of ASPM (rtl_pci_enable_aspm / rtl_pci_disable_aspm return early). If firmware/BIOS left ASPM on at probe, it stays on.
- **Symptom:** PCIe AER flooding, heavy lag, poor throughput, occasional lock-ups on RTL8723BE (subsystem 11ad:1723; same class of issue on other 8723BE cards).
- **Root cause:** Early return if (!ppsc->support_aspm) return; in rtl_pci_disable_aspm() prevents the register write that would clear L0s/L1.
- **Fix:** __rtl_pci_disable_aspm() skips that check; quirk in rtl_pci_init_aspm() calls it, then sets support_aspm = false so ASPM is not re-enabled.
- **Version info:** Fixes incomplete quirk from April 2025; that quirk is in this tree (first in v6.16).

Step 1.4: DETECT HIDDEN BUG FIXES

Record: Not hidden. Explicit fix of a broken hardware quirk. Not cleanup-only.

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

Step 2.1: INVENTORY THE CHANGES

Record:
- File: drivers/net/wireless/realtek/rtlwifi/pci.c only (26 insertions, 13 deletions)
- Functions: _rtl_pci_update_default_setting (quirk removed), rtl_pci_disable_aspm renamed to __rtl_pci_disable_aspm (early support_aspm check dropped), new thin rtl_pci_disable_aspm wrapper, rtl_pci_init_aspm (quirk moved here + __rtl_pci_disable_aspm() call)
- Scope: single-file surgical hardware-quirk fix

Step 2.2: UNDERSTAND THE CODE FLOW CHANGE

Record:
- **Before:** _rtl_pci_update_default_setting() for 11ad:1723 only sets support_aspm = false. Later rtl_pci_disable_aspm() / rtl_pci_enable_aspm() no-op. rtl_pci_init_aspm() never clears LNKCTL ASPM bits. RTL8723BE default const_pci_aspm = 3 would have taken RT_RF_PS_LEVEL_ALWAYS_ASPM and tried to *enable* ASPM; the quirk blocked that enable but did not clear already-set bits.
- **After:** After defaults, matching 11ad:1723 calls __rtl_pci_disable_aspm() (writes LNKCTL, clears L0s/L1), then support_aspm = false. ALWAYS_ASPM then calls rtl_pci_enable_aspm(), which no-ops. Normal disable path still respects support_aspm.

Step 2.3: IDENTIFY THE BUG MECHANISM

Record:
- Category: **hardware workaround / logic correctness** (quirk did not do what it claimed)
- Mechanism: support_aspm = false was treated as “ASPM off” but it only gated driver helpers. Probe-time ASPM from firmware stayed enabled → AER RxErr flood.

Step 2.4: ASSESS THE FIX QUALITY

Record:
- Obviously correct: disable first, then lock out re-enable.
- Minimal: no API change; other chips still go through the guarded wrapper.
- Regression risk low: extra disable only for 11ad:1723; wrapper preserves old behavior elsewhere.
- Residual limit (pre-existing): __rtl_pci_disable_aspm() still returns if bridge vendor is UNKNOWN. Not introduced here.
- _rtl8723be_enable_aspm_back_door() still runs in hw_init and can poke L0s/L1 via DBI; enable_aspm() afterward no-ops. Same as the original quirk. Author testing reported AER flood stopped. Not a reason to reject this patch.

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

Step 3.1: BLAME THE CHANGED LINES

Record:
- Incomplete quirk introduced by 77a6407c6ab24 (“wifi: rtlwifi:
disable ASPM for RTL8723BE with subsystem ID 11ad:1723”), 2025-04-28, **in v6.16** (not v6.15).
- That commit had Cc: stable, Fixes: a619d1abe20c (rtl8723be driver add), bugzilla 218127, Tested-by.
- ASPM helpers themselves date to the original rtlwifi PCI code (much older).

Step 3.2: FOLLOW THE FIXES: TAG

Record: No Fixes: on the candidate (intentionally dropped as “misleading” in v3). Functionally it completes 77a6407c6ab24. That commit **is** an ancestor of this HEAD.

Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES

Record: 3-patch series (v4):
1. **This commit** — actual bugfix (standalone)
2. 676e59a3825c6 — if-statement → rtl_aspm_quirks table (refactor)
3. 2b7858891b100 — add 17aa:b736 (Razer Blade 14 2017)

This patch does not need 2 or 3. Later b3943b3c29714 (2023) removed *bogus bridge* ASPM writes; this patch only uses the remaining device LNKCTL path, so it does not restore that danger.

Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS

Record: William Hansen-Baird authored this series plus one unrelated rtl8723be irq cleanup. Applied and Acked by Ping-Ke Shih (Realtek rtlwifi maintainer).

Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS

Record: Needs 77a6407c6ab24 (or equivalent 11ad:1723 quirk) and existing rtl_pci_disable_aspm / pcie_capability_* helpers. All present here. Standalone vs the rest of the series.

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

Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION

Record:
- b4 dig -c 04a46c2dbf3b5 → https://patch.msgid.link/20260630141553.78
[email protected]
- v1 2026-06-14, v2 2026-06-16, v3 2026-06-26, v4 2026-06-30 (applied)
- v2: split __rtl_pci_disable_aspm() so the check is bypassed only for the quirk
- v3: style nits; **removed misleading Fixes tag**; trailing whitespace
- v4: whitespace/{} nits; Acked-by carried forward
- No NAKs. Ping-Ke: “looks good to me” + Acked-by; applied all 3 to rtw- next
- No reviewer Cc: stable in the saved thread
- lore.kernel.org HTTP fetch returned 403; thread recovered via b4 dig -m

Step 4.2: CHECK WHO REVIEWED THE PATCH

Record: b4 dig -w: author, [email protected], linux- [email protected], [email protected]. Maintainer reviewed and applied.

Step 4.3: SEARCH FOR THE BUG REPORT

Record: This commit cites in-person testing on a Razer Blade 14 2017. Underlying AER issue: kernel bugzilla 218127 and lore discussion from 77a6407c6ab24 (ASUS F441U/X555UQ, 11ad:1723). Real user impact (lags, lock-ups), not theoretical.

Step 4.4: CHECK FOR RELATED PATCHES AND SERIES

Record: Patch 1 is the mechanism fix and is self-contained. Patches 2–3 are refactor + extra ID; not required for *this* commit.

Step 4.5: CHECK STABLE MAILING LIST HISTORY

Record: **UNVERIFIED** — lore.kernel.org/stable blocked (Anubis). No in- tree evidence this was rejected for stable.

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

Step 5.1: IDENTIFY KEY FUNCTIONS IN THE DIFF

Record: _rtl_pci_update_default_setting, __rtl_pci_disable_aspm (new name of old body), rtl_pci_disable_aspm (new wrapper), rtl_pci_init_aspm.

Step 5.2: TRACE CALLERS

Record:
- rtl_pci_init_aspm() from rtl_pci_probe() (device enumeration)
- rtl_pci_disable_aspm() from disconnect and intf_ops->disable_aspm
- disable_aspm/enable_aspm from rtl8723be hw_init, other rtlwifi chips, and ps.c power save
- Probe/init path; not a syscall hot path. Userspace-visible via loading the driver on affected laptops.

Step 5.3: TRACE CALLEES

Record: pcie_capability_read_word / _rtl_pci_platform_switch_device_pci_aspm → pcie_capability_clear_and_set_word on PCI_EXP_LNKCTL; optional clkreq via _rtl_pci_switch_clk_req.

Step 5.4: FOLLOW THE CALL CHAIN

Record: PCI probe → rtl_pci_init_aspm → quirk disable. Reachable on affected hardware when rtl8723be/rtlwifi loads. Not a sanitizer/syzbot path; real laptop hardware.

Step 5.5: SEARCH FOR SIMILAR PATTERNS

Record: Toshiba 8192SE still only sets support_aspm = false without forcing disable. Same class of incompleteness; this commit does not touch it. Follow-up series extends the same disable+flag pattern to 17aa:b736 via an ID table.

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

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

Record: **Yes.** Checkout is **7.3.0-rc4** (v7.3-rc4-27-gf0100363d8c37). 77a6407c6ab24 is an ancestor (present since v6.16). Parent of the candidate still has the 11ad:1723 block that only clears support_aspm. Driver, PCI ASPM helpers, and HARDWARE_TYPE_RTL8723BE are all here. Bug was **not** introduced after this tree branched.

Step 6.2: CHECK FOR BACKPORT COMPLICATIONS

Record: Against the parent of 04a46c2dbf3b5, the patch is a clean apply on this file. Later 7.3 commits already refactored that quirk into rtl_aspm_quirks[]; that is post-fix evolution, not a missing prerequisite. No rework needed for this tree’s lineage.

Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE

Record: No alternate fix of the same “flag vs actually clear LNKCTL” bug besides this series. Original 77a6407c6ab24 is the incomplete version this completes.

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

Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY

Record: drivers/net/wireless/realtek/rtlwifi — **PERIPHERAL/IMPORTANT** for owners of RTL8723BE laptops (ASUS F441U/X555UQ and similar). Not core mm/fs, but a shipping WiFi adapter in production machines.

Step 7.2: ASSESS SUBSYSTEM ACTIVITY

Record: Mature driver; still receiving bugfixes. rtlwifi 8723BE is old but still the in-tree driver for that chip.

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

Step 8.1: DETERMINE WHO IS AFFECTED

Record: Driver-specific: RTL8723BE with subsystem **11ad:1723** (ASUSTek F441U, X555UQ, etc.). Only that ID in *this* commit.

Step 8.2: DETERMINE THE TRIGGER CONDITIONS

Record: Trigger is boot/probe with ASPM already enabled (common). Not a race. Unprivileged users do not need a special exploit; plugging/using the laptop is enough. Confirmed on real hardware.

Step 8.3: DETERMINE THE FAILURE MODE SEVERITY

Record: AER correctable-error flood → system-wide slowdown, bad WiFi throughput, **occasional lock-ups**. Severity **HIGH** (hang/lock-up and severe lag), not a KASAN crash.

Step 8.4: CALCULATE RISK-BENEFIT RATIO

Record:
- **Benefit:** High for affected laptops; makes an already-stable quirk actually work.
- **Risk:** Low (~26/+13 lines, one file, ID-gated, maintainer Acked, tested).
- **Ratio:** Strongly favors backport.

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

Step 9.1: COMPILE THE EVIDENCE

**FOR:**
- Real hardware bug: AER flood, lag, lock-ups on known laptops
- Existing stable-bound quirk (77a6407c6ab24) did not disable ASPM when it was already on
- Small, obviously correct, ID-scoped
- Hardware quirk exception
- Maintainer Acked-by and applied; author tested
- Prerequisite incomplete quirk is in this 7.3 tree
- Self-contained as patch 1/3

**AGAINST:**
- Affects a specific PCI subsystem ID, not all users
- No Fixes:/Cc: stable (expected here; Fixes was dropped as misleading)
- DBI backdoor in hw_init still exists (pre-existing; testing said AER stopped)

**UNRESOLVED:**
- Stable mailing-list history (lore/stable fetch blocked)
- Direct lore.kernel.org HTTP (403); discussion recovered via b4

Step 9.2: APPLY THE STABLE RULES CHECKLIST

1. Obviously correct and tested? **PASS** — maintainer ack; tested on affected hardware; v2–v4 review
2. Fixes a real bug that affects users? **PASS** — broken quirk left ASPM on; AER/lag/lock-ups
3. Important issue? **PASS** — lock-ups and severe performance, not cosmetic
4. Small and contained? **PASS** — one file, +26/-13
5. No new features or APIs? **PASS** — completes an existing quirk
6. Can apply to the local tree? **PASS** — pci.c and 77a6407c6ab24 are here; context matches

Step 9.3: CHECK FOR EXCEPTION CATEGORIES

Record: **Hardware quirk/workaround** for a broken RTL8723BE/ASPM combination.

Step 9.4: MAKE YOUR DECISION

This tree has the incomplete 11ad:1723 quirk and the rtlwifi ASPM path. The change is a small, reviewed fix that actually clears ASPM so those laptops do not keep flooding AER and locking up. It belongs in this tree.

Verification:
- [Phase 1] Tags: Acked-by Ping-Ke Shih; Link msgid 20260630141553.785769-2; no Fixes/Cc:stable; v3 changelog said Fixes was removed as misleading
- [Phase 1] Body: support_aspm=false blocks disable/enable helpers instead of clearing ASPM
- [Phase 2] Diff: pci.c +26/-13; quirk moved to rtl_pci_init_aspm; __rtl_pci_disable_aspm skips the flag check
- [Phase 2] RTL8723BE default const_pci_aspm = 3 / aspm_support = 1 verified in rtl8723be/sw.c
- [Phase 3] git merge-base --is-ancestor 77a6407c6ab24 HEAD → yes; original first in v6.16, not v6.15
- [Phase 3] git merge-base --is-ancestor 04a46c2dbf3b5 HEAD → yes; not an ancestor of v7.2; is in v7.3-rc1
- [Phase 3] Series: this commit, then ID-table refactor, then 17aa:b736; this patch standalone
- [Phase 4] b4 dig -c 04a46c2dbf3b5 / -a / -w / -m: v1–v4, maintainer Ack, applied to rtw-next; no NAK
- [Phase 4] WebFetch lore 403; stable lore Anubis — UNVERIFIED via HTTP
- [Phase 5] Callers: rtl_pci_probe → rtl_pci_init_aspm; intf_ops->disable_aspm from rtl8723be hw_init and ps.c
- [Phase 6] make kernelversion / git describe HEAD: 7.3.0-rc4 / v7.3-rc4-27-gf0100363d8c37; origin torvalds/linux.git
- [Phase 6] Parent of candidate still has 11ad:1723 support_aspm = false only
- [Phase 8] Failure mode: AER flood, lag, lock-ups — HIGH; change ID- gated — low risk
- UNVERIFIED: Whether this was discussed on stable@; whether DBI backdoor re-enables L0s/L1 after probe on all machines (testing said AER stopped)

The patch is a contained hardware-quirk correctness fix for a bug this tree actually has.

**YES**

 drivers/net/wireless/realtek/rtlwifi/pci.c | 39 ++++++++++++++--------
 1 file changed, 26 insertions(+), 13 deletions(-)
drivers/net/wireless/realtek/rtlwifi/pci.c +26 -13
index 8fb9604c3c533..f9f05252b890e 100644
@@ -156,15 +156,6 @@ static void _rtl_pci_update_default_setting(struct ieee80211_hw *hw)
 				PCI_EXP_LNKCTL_ASPM_L1 | PCI_EXP_LNKCTL_CCC))
 		ppsc->support_aspm = false;
 
-	/* RTL8723BE found on some ASUSTek laptops, such as F441U and
-	 * X555UQ with subsystem ID 11ad:1723 are known to output large
-	 * amounts of PCIe AER errors during and after boot up, causing
-	 * heavy lags, poor network throughput, and occasional lock-ups.
-	 */
-	if (rtlpriv->rtlhal.hw_type == HARDWARE_TYPE_RTL8723BE &&
-	    (rtlpci->pdev->subsystem_vendor == 0x11ad &&
-	     rtlpci->pdev->subsystem_device == 0x1723))
-		ppsc->support_aspm = false;
 }
 
 static bool _rtl_pci_platform_switch_device_pci_aspm(
@@ -203,7 +194,7 @@ static void _rtl_pci_switch_clk_req(struct ieee80211_hw *hw, u16 value)
 }
 
 /*Disable RTL8192SE ASPM & Disable Pci Bridge ASPM*/
-static void rtl_pci_disable_aspm(struct ieee80211_hw *hw)
+static void __rtl_pci_disable_aspm(struct ieee80211_hw *hw)
 {
 	struct rtl_priv *rtlpriv = rtl_priv(hw);
 	struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
@@ -215,9 +206,6 @@ static void rtl_pci_disable_aspm(struct ieee80211_hw *hw)
 	u16 aspmlevel = 0;
 	u16 tmp_u1b = 0;
 
-	if (!ppsc->support_aspm)
-		return;
-
 	if (pcibridge_vendor == PCI_BRIDGE_VENDOR_UNKNOWN) {
 		rtl_dbg(rtlpriv, COMP_POWER, DBG_TRACE,
 			"PCI(Bridge) UNKNOWN\n");
@@ -240,6 +228,16 @@ static void rtl_pci_disable_aspm(struct ieee80211_hw *hw)
 	_rtl_pci_platform_switch_device_pci_aspm(hw, linkctrl_reg);
 }
 
+static void rtl_pci_disable_aspm(struct ieee80211_hw *hw)
+{
+	struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
+
+	if (!ppsc->support_aspm)
+		return;
+
+	__rtl_pci_disable_aspm(hw);
+}
+
 /*Enable RTL8192SE ASPM & Enable Pci Bridge ASPM for
  *power saving We should follow the sequence to enable
  *RTL8192SE first then enable Pci Bridge ASPM
@@ -330,10 +328,25 @@ static void rtl_pci_parse_configuration(struct pci_dev *pdev,
 
 static void rtl_pci_init_aspm(struct ieee80211_hw *hw)
 {
+	struct rtl_pci *rtlpci = rtl_pcidev(rtl_pcipriv(hw));
 	struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
+	struct rtl_priv *rtlpriv = rtl_priv(hw);
 
 	_rtl_pci_update_default_setting(hw);
 
+	/*
+	 * RTL8723BE found on some ASUSTek laptops, such as F441U and
+	 * X555UQ with subsystem ID 11ad:1723 are known to output large
+	 * amounts of PCIe AER errors during and after boot up, causing
+	 * heavy lags, poor network throughput, and occasional lock-ups.
+	 */
+	if (rtlpriv->rtlhal.hw_type == HARDWARE_TYPE_RTL8723BE &&
+	    (rtlpci->pdev->subsystem_vendor == 0x11ad &&
+	     rtlpci->pdev->subsystem_device == 0x1723)) {
+		__rtl_pci_disable_aspm(hw);
+		ppsc->support_aspm = false;
+	}
+
 	if (ppsc->reg_rfps_level & RT_RF_PS_LEVEL_ALWAYS_ASPM) {
 		/*Always enable ASPM & Clock Req. */
 		rtl_pci_enable_aspm(hw);
Signature · 1 line
2.53.0
author maintainer
#76 lore raw

PATCH 1/1 arm64/runtime-const: Use aarch64_insn_patch_text_nosync() for patching

In reply to Sasha Levin

From: K Prateek Nayak <[email protected]>

[ Upstream commit a6690350a4ae7558b39d15fcc776c4d1ab5bbf39 ]

The current scheme to directly patch the kernel text for runtime constants runs into the following issue with futex adapted to using runtime constants on arm64:

  Unable to handle kernel write to read-only memory at virtual address ...

The pc points to the *p assignment in the following call chain:

  futex_init()
    runtime_const_init(shift, __futex_shift)
      __runtime_fixup_shift()
        *p = cpu_to_le32(insn);

which suggests that core_initcall() is too late to patch the kernel text directly unlike the "d_hash_shift" which is initialized during vfs_caches_init_early() before the protections are in place.

Use aarch64_insn_patch_text_nosync() to patch the runtime constants instead of doing it directly to allow runtime_const_init() slightly later into the boot.

Since aarch64_insn_patch_text_nosync() calls caches_clean_inval_pou() internally, __runtime_fixup_caches() ends up being redundant. runtime_const_init() are rare and the overheads of multiple calls to caches_clean_inval_pou() instead of batching them together should be negligible in practice.

The cpu_to_le32() conversion of instruction isn't necessary since it is handled later in the aarch64_insn_patch_text_nosync() call-chain:

aarch64_insn_patch_text_nosync(addr, insn)

    aarch64_insn_write(addr, insn)
      __aarch64_insn_write(addr, cpu_to_le32(insn))

Sashiko noted that aarch64_insn_patch_text_nosync() does not expect a lm_alias() address and Catalin suggested it is safe to drop the lm_alias() for runtime patching since the kernel text is readable. The address passed to fixup function is interpreted as a __le32 and dereferenced as is to read the opcode at the patch site.

No functional changes are intended.

---

LLM Generated explanations, may be completely bogus:

Connection lost, reconnecting to https://agentn.us.api5.cursor.sh
(attempt 1)...
Retry attempt 1...
## Phase 1: Commit message forensics

**Step 1.1 — Subject line**
- Record: **[arm64/runtime-const] [Use] switch text patching from a direct store to aarch64_insn_patch_text_nosync()**

**Step 1.2 — Tags**
- Record:
- Signed-off-by: K Prateek Nayak (author)
- Signed-off-by: Peter Zijlstra (locking/futex maintainer)
- Reviewed-by: Catalin Marinas (arm64 maintainer)
- Reviewed-by: Charlie Jenkins
- Tested-by: Charlie Jenkins
- Link: https://patch.msgid.link/20260728052540.4728-3-
[email protected]
- No Fixes:, no Reported-by, no Cc: stable (absence expected)
- Ignore pipeline SOBs if present; none in the real commit

**Step 1.3 — Body**
- Record:
- **Bug:** arm64 runtime-const writes the patched opcode with *p = cpu_to_le32(insn) through lm_alias(). That faults once kernel text (including the linear alias) is read-only.
- **Symptom:** Unable to handle kernel write to read-only memory during futex_init() → runtime_const_init() → __runtime_fixup_shift().
- **Root cause:** d_hash_shift is patched in vfs_caches_init_early() while the linear alias is still writable. futex_init() is a core_initcall, after mark_linear_text_alias_ro().
- **Fix:** use the existing text-poking helper (fixmap writable alias
+ cache maintenance). Drop redundant __runtime_fixup_caches() and cpu_to_le32() (done inside the helper). Drop lm_alias() because the helper wants a kernel-text address.
- **Version info:** none beyond the futex/runtime-const interaction.

**Step 1.4 — Hidden bug fix?**
- Record: Not hidden. The message describes a concrete oops. “No functional changes are intended” means the patched immediates are the same; the write path is what changes so late runtime_const_init() can succeed.

## Phase 2: Diff analysis

**Step 2.1 — Inventory**
- Record: one file, arch/arm64/include/asm/runtime-const.h (~5 insertions, 12 deletions). Functions: __runtime_fixup_16(), __runtime_fixup_caches() (removed), __runtime_fixup_ptr(), __runtime_fixup_shift(). Surgical, single-header.

**Step 2.2 — Flow change**
- Record:
- **Before:** read opcode at lm_alias(where), store new insn with

    `*p = cpu_to_le32(insn)`, then `caches_clean_inval_pou()` on the
    original VA.
  - **After:** pass the kernel-text pointer and host-endian insn to
    `aarch64_insn_patch_text_nosync()`, which maps a writable fixmap
    page, writes, and flushes I/D caches.
  - Affected path: boot-time `runtime_const_init()` only (not a hot
    path).

**Step 2.3 — Bug mechanism**
- Record: **logic/correctness of text patching after RO protection**. Direct store to RO kernel text. The helper uses patch_map() → FIX_TEXT_POKE0, the same path as kprobes/jump labels/ftrace.

**Step 2.4 — Fix quality**
- Record: Obviously correct. Matches how arm64 already patches text. Regression risk is low: leftover #include <asm/cacheflush.h> is unused after the helper absorbs the flush; return value of the helper is ignored (old path had no error check either; kernel text is 4-byte aligned). Catalin confirmed dropping lm_alias() is safe because kernel text remains readable for the opcode load.

## Phase 3: Git history

**Step 3.1 — Blame**
- Record: Buggy direct-write scheme introduced in 94a2bc0f611cd (“arm64: add 'runtime constant' support”, Linus, 2024-07-09). Present since ~v6.11. The crash only appears when runtime_const_init() runs after mark_linear_text_alias_ro().

**Step 3.2 — Fixes: tag**
- Record: none. Introducing commit is 94a2bc0f611cd (in this tree). The late caller that actually faults is b78b0b6582527 (“futex: Use runtime constants for __futex_hash() hot path”), also in this tree (v7.3-rc1).

**Step 3.3 — File history**
- Record: 94a2bc0f611cd add support → 0100e495cdf04 modules ban → **a6690350a4ae7 this fix** → 7eccf137dc044 runtime_const_mask_32(). Same series as the futex conversion; this patch is 2/8 and does not depend on later patches. Later mask support *uses* this helper.

**Step 3.4 — Author**
- Record: K Prateek Nayak (AMD), not the arm64 maintainer. Arm64 review is from Catalin. Peter Zijlstra signed off (locking tree). Related:
7eccf137dc044 immediately after.

**Step 3.5 — Dependencies**
- Record: Needs aarch64_insn_patch_text_nosync() / <asm/text- patching.h> — present at the parent and on HEAD. Standalone vs the rest of the series. On *this* tree the futex caller is already present, so the fix is load-bearing.

## Phase 4: Mailing list

**Step 4.1 — Original discussion**
- Record: b4 dig -c a6690350a4ae → `[PATCH v6 2/8] arm64/runtime-
const: Use aarch64_insn_patch_text_nosync() for patching` at
https://patch.msgid.link/[email protected].
Cover: [PATCH v6 0/8] futex: Use runtime constants for futex_hash computation. v5→v6: no diff change on this patch; tags collected. No NAKs. Sashiko noted the helper must not get an lm_alias() address; Catalin said dropping it is fine. No reviewer asked for Cc: stable.

**Step 4.2 — Recipients**
- Record: Catalin Marinas, Will Deacon, Peter Zijlstra, Thomas Gleixner, linux-arm-kernel, linux-arch. Right maintainers were on the To/Cc list. Catalin Reviewed-by is on the committed patch.

**Step 4.3 — Bug report**
- Record: No syzbot/bugzilla. The oops is from the author’s own futex+runtime-const bring-up on arm64. Charlie Jenkins Tested-by. Cover letter: build+boot on x86 bare metal and QEMU for other arches.

**Step 4.4 — Series**
- Record: v6 8-patch feature series. This commit is the arm64 text- poking prerequisite. Patch 8 adds runtime_const_init() in futex_init(). Both are in this 7.3-rc4 tree.

**Step 4.5 — Stable list**
- Record: UNVERIFIED for a dedicated stable@ thread (lore HTTP 403). No stable mention in the saved v6 mbox.

## Phase 5: Code semantics

**Step 5.1 — Functions**
- Record: __runtime_fixup_16, __runtime_fixup_ptr, __runtime_fixup_shift; __runtime_fixup_caches removed. Current tree also has __runtime_fixup_mask (later commit) using the same helper.

**Step 5.2 — Callers**
- Record: runtime_const_init() → runtime_const_fixup() → those fixups. Call sites in this tree:
- kernel/futex/core.c futex_init() — core_initcall — **after**

    `smp_cpus_done()` → `mark_linear_text_alias_ro()`
  - `fs/dcache.c`, `fs/file_table.c`, `fs/namei.c` —
    `vfs_caches_init[_early]()` in `start_kernel()` — **before** that RO
    switch

**Step 5.3 — Callees**
- Record: aarch64_insn_patch_text_nosync() → aarch64_insn_write() → __aarch64_insn_write() (patch_map + copy_to_kernel_nofault) + caches_clean_inval_pou().

**Step 5.4 — Reachability**
- Record: Unconditional on arm64. futex_init is a core_initcall. Every arm64 boot on this tree hits the late patch. Without this fix:
boot oops.

**Step 5.5 — Similar patterns**
- Record: x86 runtime-const still does a direct store and documents “only at init before text is RO”. arm64’s linear-map alias is marked RO earlier (smp_cpus_done), so arm64 cannot follow that model for core_initcall.

## Phase 6: This tree

**Step 6.1 — Buggy code here?**
- Record: Yes. Tree is **v7.3-rc4** (7.3.0-rc4, HEAD f0100363d8c37). File exists. Pre-fix body is at a6690350a4ae^. futex_init() still calls runtime_const_init() (kernel/futex/core.c). The fix commit **is already an ancestor of HEAD** (in v7.3-rc1). Current runtime- const.h already calls aarch64_insn_patch_text_nosync().

**Step 6.2 — Backport difficulty**
- Record: Clean on the parent snapshot. Current HEAD already has this plus runtime_const_mask_32(); re-applying the exact hunk would be a no-op / already-applied.

**Step 6.3 — Related fixes already here**
- Record: This *is* the fix. No later Fixes: for a6690350. Follow-up 7eccf137dc044 only adds mask patching on the new helper.

## Phase 7: Subsystem

**Step 7.1**
- Record: **arch/arm64** text-patching used by **futex** (core locking).
Criticality: **IMPORTANT** — every arm64 boot.

**Step 7.2**
- Record: Active in the 7.3 window (futex runtime-const series). The underlying helper is old, stable infrastructure.

## Phase 8: Impact and risk

**Step 8.1**
- Record: All arm64 users of this kernel (futex init is not optional).

**Step 8.2**
- Record: Every boot, core_initcall(futex_init). Not userspace- triggered; it is a boot breaker.

**Step 8.3**
- Record: Kernel fault writing RO text → boot failure. **CRITICAL**.

**Step 8.4**
- Record: Benefit high (arm64 actually boots with the futex runtime- const code this tree already has). Risk low (~one-header, established poking API, arm64 maintainer Reviewed-by).

## Phase 9: Synthesis

**Evidence for YES**
- Documented oops: write to RO memory in __runtime_fixup_shift().
- This tree has the late caller (futex_init / core_initcall) and mark_linear_text_alias_ro() in smp_cpus_done() before do_basic_setup() / initcalls.
- Small, local, uses the standard arm64 patching API.
- Reviewed by Catalin Marinas; tested by Charlie Jenkins; signed off by Peter Zijlstra.
- No new userspace API.

**Evidence against**
- Lives in a feature series (futex hash optimization). On trees *without* a late runtime_const_init(), the old path never faulted.
- No Fixes:/Cc: stable (not a negative under these rules).
- Already in this 7.3-rc4 history, so a second apply is unnecessary — that is not used as a NO (pipeline “already selected” is ignored).

**Unresolved**
- No stable@ thread readable (lore 403). Does not change the local technical picture.

**Stable-rules checklist**
1. Obviously correct and tested — **PASS** (Catalin + Tested-by + QEMU boot)
2. Real user-visible bug — **PASS** (arm64 boot oops with this tree’s futex init)
3. Important (crash) — **PASS** (CRITICAL)
4. Small/contained — **PASS** (one header, ~17 lines)
5. No new features/APIs — **PASS**
6. Applies to this tree — **PASS** (code and helper are here; commit already merged in 7.3-rc1)

**Exception category:** none (not an ID/quirk/DT/docs/build-only change).

This tree ships both the late runtime_const_init() and arm64 STRICT_KERNEL_RWX linear-alias RO. The old lm_alias() store is a boot crash. Replacing it with aarch64_insn_patch_text_nosync() is the correct, minimal fix and belongs in this series.

### Verification
- [Phase 1] Parsed tags: Reviewed-by Catalin Marinas, Tested-by Charlie Jenkins, Link to v6 2/8; no Fixes:/syzbot
- [Phase 2] Diff: one file; direct *p store + lm_alias + __runtime_fixup_caches replaced by aarch64_insn_patch_text_nosync
- [Phase 2] Confirmed helper: arch/arm64/kernel/patching.c aarch64_insn_patch_text_nosync() → write via patch_map + caches_clean_inval_pou
- [Phase 3] git describe HEAD / Makefile: **v7.3-rc4**, 7.3.0-rc4
- [Phase 3] git merge-base --is-ancestor a6690350 HEAD: yes; also in v7.3-rc1; not in v7.2
- [Phase 3] Blame: buggy writes from 94a2bc0f611cd (2024); late caller b78b0b6582527 in this tree
- [Phase 3] Parent file shown: *p = cpu_to_le32(insn) + lm_alias
- [Phase 4] b4 dig -c a6690350: lore match v6 2/8; mbox saved; no NAK; Catalin R-b on the patch
- [Phase 4] Cover letter: feature series for futex runtime const; this patch is the arm64 poking prerequisite
- [Phase 4] UNVERIFIED: stable@ mailing-list search (lore 403)
- [Phase 5] Callers: futex core_initcall (late); VFS caches in start_kernel (early)
- [Phase 5] mark_linear_text_alias_ro() called from smp_cpus_done(); do_basic_setup()/do_initcalls() after smp_init()
- [Phase 6] Current runtime-const.h already uses the helper; text- patching.h exists at parent
- [Phase 8] Failure mode: RO-text write → boot oops on all arm64, CRITICAL
- UNVERIFIED: Catalin’s original review mail text (only R-b + commit- message paraphrase in v6 mbox)

The patch is small, uses the existing arm64 text-poking path, and prevents a boot crash on this tree’s futex runtime_const_init().

**YES**

 arch/arm64/include/asm/runtime-const.h | 17 +++++------------
 1 file changed, 5 insertions(+), 12 deletions(-)
arch/arm64/include/asm/runtime-const.h +5 -12
index be5915669d239..31a6f94e57955 100644
@@ -3,6 +3,7 @@
 #define _ASM_RUNTIME_CONST_H
 
 #include <asm/cacheflush.h>
+#include <asm/text-patching.h>
 
 /* Sigh. You can still run arm64 in BE mode */
 #include <asm/byteorder.h>
@@ -46,34 +47,26 @@ static inline void __runtime_fixup_16(__le32 *p, unsigned int val)
 	u32 insn = le32_to_cpu(*p);
 	insn &= 0xffe0001f;
 	insn |= (val & 0xffff) << 5;
-	*p = cpu_to_le32(insn);
-}
-
-static inline void __runtime_fixup_caches(void *where, unsigned int insns)
-{
-	unsigned long va = (unsigned long)where;
-	caches_clean_inval_pou(va, va + 4*insns);
+	aarch64_insn_patch_text_nosync(p, insn);
 }
 
 static inline void __runtime_fixup_ptr(void *where, unsigned long val)
 {
-	__le32 *p = lm_alias(where);
+	__le32 *p = where;
 	__runtime_fixup_16(p, val);
 	__runtime_fixup_16(p+1, val >> 16);
 	__runtime_fixup_16(p+2, val >> 32);
 	__runtime_fixup_16(p+3, val >> 48);
-	__runtime_fixup_caches(where, 4);
 }
 
 /* Immediate value is 6 bits starting at bit #16 */
 static inline void __runtime_fixup_shift(void *where, unsigned long val)
 {
-	__le32 *p = lm_alias(where);
+	__le32 *p = where;
 	u32 insn = le32_to_cpu(*p);
 	insn &= 0xffc0ffff;
 	insn |= (val & 63) << 16;
-	*p = cpu_to_le32(insn);
-	__runtime_fixup_caches(where, 1);
+	aarch64_insn_patch_text_nosync(p, insn);
 }
 
 static inline void runtime_const_fixup(void (*fn)(void *, unsigned long),
Signature · 1 line
2.53.0
author maintainer
#77 lore raw

PATCH 1/1 HID: rmi: check report length before trimming sentinel bytes

In reply to Sasha Levin

From: Pengpeng Hou <[email protected]>

[ Upstream commit 28a3e326fad2451bdb66b747dd1f7ccbb900eed6 ]

rmi_check_sanity() trims trailing 0xff sentinel bytes, but its loop reads data[valid_size - 1] before checking that valid_size is non-zero.

Reverse the condition so the length is proved before the last byte is inspected.

---

LLM Generated explanations, may be completely bogus:

The local tree is **pending-6.12** (6.12.111). The buggy rmi_check_sanity() loop is still present, the one-line short-circuit reorder is not an ancestor of HEAD, and the patch applies here with only a line-number offset.

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

**Step 1.1: PARSE THE SUBJECT LINE**
Record: **[HID: rmi]** **[check]** check report length before trimming sentinel bytes. Same class of wording as other HID length-check fixes:
the length must be proved before data[valid_size - 1] is read.

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**
Record:
- Signed-off-by: Pengpeng Hou \<[email protected]\> (author)
- Signed-off-by: Jiri Kosina \<[email protected]\> (HID maintainer)
- No Fixes:, Reported-by, Tested-by, Reviewed-by, Acked-by, Link:, or
Cc: stable (absence is expected for this review pipeline)
- Ignore any pipeline “Upstream commit” / Sasha Levin SOB markers

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**
Record:
- Bug: rmi_check_sanity() trims trailing 0xff sentinels but evaluates data[valid_size - 1] before valid_size > 0.
- Symptom: one-byte out-of-bounds read when the loop has already trimmed the buffer to length 0.
- Root cause: C && is left-to-right; the original order does the index first.
- No stack traces, syzbot IDs, or version list in the message.
- Introducer (from git, not the message): 5b65c2a029664 (“HID: rmi:
check sanity of the incoming report”, 2014-09-10), first tagged v3.18-rc1.

**Step 1.4: DETECT HIDDEN BUG FIXES**
Record: Not a disguised cleanup. It is an explicit short-circuit-order OOB fix. The valid_size > 0 test was already there; it was just on the wrong side of &&.

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

**Step 2.1: INVENTORY THE CHANGES**
Record:
- File: drivers/hid/hid-rmi.c (1 insertion, 1 deletion)
- Function: rmi_check_sanity()
- Scope: single-file, one-line surgical fix

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**
Record:
- Before: while ((data[valid_size - 1] == 0xff) && valid_size > 0) — when valid_size is 0, data[-1] is still read.
- After: while (valid_size > 0 && data[valid_size - 1] == 0xff) — the subscript is not evaluated on an empty buffer.
- Path: runtime HID raw_event input, not probe/error-only.

**Step 2.3: IDENTIFY THE BUG MECHANISM**
Record: **Memory safety / OOB read.** HID core rejects a zero-length report (hid_input_report() returns if !size), so the realistic trigger is trimming an all-0xff (or fully trailing-0xff) report down to 0, then doing one more iteration. That is the exact Dell XPS 13 9333 bus-sentinel case this helper was written for. One OOB byte is compared to 0xff and discarded; it is not copied to userspace, so this is not an info leak, but it is still undefined-behavior / KASAN-class.

**Step 2.4: ASSESS THE FIX QUALITY**
Record: Obviously correct C short-circuit reorder. No API, locking, or control-flow change beyond skipping the illegal index. Regression risk is negligible. rmi_raw_event() already drops size < 2 after this call.

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

**Step 3.1: BLAME THE CHANGED LINES**
Record: Line 389 blamed to 5b65c2a029664 (Benjamin Tissoires, 2014-09-10). Present since **v3.18-rc1**. Long-lived in this 6.12 tree.

**Step 3.2: FOLLOW THE FIXES: TAG**
Record: No Fixes: tag. Introducer confirmed via blame: 5b65c2a029664 is an ancestor of HEAD.

**Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES**
Record:
- Candidate SHA on master: 28a3e326fad2451bdb66b747dd1f7ccbb900eed6 (author date 2026-06-30, committer 2026-08-03). git merge-base --is- ancestor vs HEAD: **not in this tree**.
- Related later commit already here: ab2958e0c94ed / upstream 183da103022ec “HID: rmi: fix OOB access with undersized RMI reports” — probe-time report-size clamps and copy bounds. **Does not change this loop.**
- Standalone one-line patch, not “X/Y”.

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**
Record: Pengpeng Hou is not the HID maintainer. Jiri Kosina applied it. No other hid-rmi commits from this author in this checkout.

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS**
Record: None. Same while line exists here. git apply --check of 28a3e326fad24 succeeded (hunk offset 21 from the later OOB patch).

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

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**
Record:
- b4 dig -c 28a3e326fad24:
https://patch.msgid.link/2026063007016439.1-ccfa108-0006-HID-rmi-
[email protected]
- b4 dig -a: **v1 only** (2026-06-30).
- Thread (3 messages): submission; Sashiko bot flagging **unrelated pre- existing** read/write OOB in rmi_hid_{read,write}_block (later the undersized-report patch already in this tree); Jiri Kosina “Applied, thanks.” (2026-08-03).
- No NAK. No reviewer asked for Cc: stable.

**Step 4.2: CHECK WHO REVIEWED THE PATCH**
Record (b4 dig -w): To Jiri Kosina and Benjamin Tissoires; Cc linux- input and linux-kernel. HID maintainers were on the original To: line.

**Step 4.3: SEARCH FOR THE BUG REPORT**
Record: No syzbot/bugzilla link on this patch. The sentinel behavior itself is documented in-tree and in 5b65c2a029664 (Red Hat bugzilla 1123584 for Dell XPS 13 9333). That is the hardware path that can fill a report with 0xff and drive this loop to length 0.

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**
Record: Standalone. Sibling OOB work (HID: rmi: fix OOB access with undersized RMI reports) is already on pending-6.12 and does not subsume this change.

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**
Record: **UNVERIFIED** — lore.kernel.org/stable/?q=... returned HTTP
403. No evidence in the linux-input thread that stable was discussed or rejected.

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

**Step 5.1: IDENTIFY KEY FUNCTIONS IN THE DIFF**
Record: rmi_check_sanity() only.

**Step 5.2: TRACE CALLERS**
Record: Sole caller is rmi_raw_event() (drivers/hid/hid-rmi.c), registered as .raw_event. HID core hid_input_report() (drivers/hid/hid-core.c) calls it after rejecting empty reports and resolving a valid hid_report. hid-rmi has no report_table, so hid_match_report() matches all reports. rmi_raw_event() then requires RMI_DEVICE (set after probe validates RMI report IDs).

**Step 5.3: TRACE CALLEES**
Record: The function only indexes data[] and decrements valid_size. No alloc/lock/I/O.

**Step 5.4: FOLLOW THE CALL CHAIN**
Record: USB/i2c HID interrupt → hid_input_report() → rmi_raw_event() → rmi_check_sanity(). Reachable from Synaptics RMI touchpads (HID_GROUP_RMI in hid_scan_report(), plus specific USB IDs: Razer Blade, Lenovo X1 cover, Primax, Acer Switch). Unprivileged USB can also feed HID reports. Userspace-reachable: **yes** (device I/O, not a syscall that crafts the buffer directly).

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**
Record: Only this loop in hid-rmi. Same-tree HID length checks already backported include HID: lg4ff: validate report length before fixed offsets and HID: wacom: validate report length in wacom_intuos_pro2_bt_irq.

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

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?**
Record: **Yes.** drivers/hid/hid-rmi.c lines 389–390:
while ((data[valid_size - 1] == 0xff) && valid_size > 0). Introduced v3.18, still here on 6.12.111. Candidate 28a3e326fad24 is **not** an ancestor of HEAD.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**
Record: Clean apply with +21 line offset. No refactor of this helper.

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**
Record: ab2958e0c94ed is a different OOB (report descriptor / copy length). It does not reorder this condition. No earlier equivalent of this one-liner.

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

**Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY**
Record: **HID / hid-rmi** (Synaptics RMI4 over i2c-hid/usbhid). **IMPORTANT** for laptops with Synaptics HID touchpads; not mm/VFS core, but not staging/obscure either.

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**
Record: hid-rmi is mature (2014+). Recent churn is security-style OOB hardening, not a rewrite of this path.

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

**Step 8.1: DETERMINE WHO IS AFFECTED**
Record: Driver-specific: CONFIG_HID_RMI / Synaptics RMI HID devices (common on some Dell/Lenovo/Acer laptops). Also any malicious HID gadget bound as hid-rmi.

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**
Record: A report whose remaining bytes are all 0xff (documented XPS 13 9333 bus glitch, or a device sending that pattern). After the last decrement, valid_size == 0 and the next condition still reads data[-1]. Not every report; it is the sentinel path this function exists to handle. Physical HID access required; not a random unprivileged syscall.

**Step 8.3: DETERMINE THE FAILURE MODE SEVERITY**
Record: One-byte heap underflow read. Typical result: KASAN report; crash only if that byte is unmapped (uncommon for kmalloc). Not data corruption. **Severity: HIGH** for memory safety / HID attack surface, not a guaranteed panic.

**Step 8.4: CALCULATE RISK-BENEFIT RATIO**
Record:
- Benefit: stops a real OOB on a long-lived, hardware-motivated path; 1 line.
- Risk: very low (boolean operand swap).
- Ratio: strongly in favor of backport.

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

**Step 9.1: COMPILE THE EVIDENCE**

FOR:
- Real OOB; the > 0 check was present but evaluated too late.
- Trigger matches the in-tree Dell XPS sentinel comment, not a hypothetical size=0 from HID core.
- Code has been in this tree since v3.18.
- 1-line, obviously correct; HID maintainer applied v1 as-is.
- Applies cleanly; no prerequisites.
- Same class as other HID length-check stable backports already on this branch.

AGAINST:
- No Fixes:/Cc: stable/syzbot (not a negative under these rules).
- Single-byte read, not a demonstrated oops or leak.
- Affects hid-rmi users, not every machine.

UNRESOLVED:
- Could not search lore.kernel.org/stable (HTTP 403).

**Step 9.2: APPLY THE STABLE RULES CHECKLIST**
1. Obviously correct and tested? **PASS** — C short-circuit; applied by Jiri Kosina.
2. Fixes a real bug that affects users? **PASS** — OOB on the sentinel- trim path this driver documents.
3. Important issue? **PASS** — memory-safety OOB on HID input (HIGH, not a guaranteed panic).
4. Small and contained? **PASS** — 1 line, one function.
5. No new features or APIs? **PASS**.
6. Can apply to the local tree? **PASS** — buggy line present; git apply --check succeeded.

**Step 9.3: CHECK FOR EXCEPTION CATEGORIES**
Record: None. Ordinary small bugfix.

**Step 9.4: MAKE YOUR DECISION**
This belongs on **this** 6.12 tree: the bug exists here, the later undersized-report patch does not fix it, and the change is a one-line operand swap with no API or locking impact.

===============================================================
What the commit solves for stable users
===============================================================
rmi_check_sanity() is supposed to strip trailing 0xff filler from Synaptics HID reports. Because && evaluates left-to-right, an all- sentinel report is trimmed to length 0 and then still reads data[-1]. Laptop touchpads that hit that bus glitch, and USB HID devices that send the same pattern, can fire a KASAN OOB on every such report. Reordering the condition makes the existing length check actually protect the index.

Risk vs benefit: benefit is a real memory-safety hole on a driver already receiving other OOB backports; risk is a one-line boolean reorder. No dependencies beyond code that has been here since v3.18.

===============================================================
Verification
===============================================================
- [Phase 1] Parsed subject/body/tags: no Fixes/Reported-by/Cc: stable; SOBs Hou + Kosina.
- [Phase 2] Diff: 1 line in rmi_check_sanity(); operand order only.
- [Phase 3] git describe HEAD / Makefile: **pending-6.12, 6.12.111**.
- [Phase 3] git blame -L 379,410 -- drivers/hid/hid-rmi.c: introducer 5b65c2a029664 (v3.18-rc1).
- [Phase 3] git merge-base --is-ancestor 5b65c2a029664 HEAD: yes; 28a3e326fad24: **no**.
- [Phase 3] Current file still has while ((data[valid_size - 1] == 0xff) && valid_size > 0).
- [Phase 3] Related ab2958e0c94ed already in tree; does not touch this loop.
- [Phase 3] git show 28a3e326fad24 | git apply --check: hunk succeeded at offset 21.
- [Phase 4] b4 dig -c 28a3e326fad24: lore msgid 2026063007016439.1-ccfa108-...; To: Kosina + Tissoires.
- [Phase 4] b4 dig -a: v1 only; Kosina “Applied, thanks.”
- [Phase 4] Mbox: Sashiko comments are about other pre-existing OOBs, not this line.
- [Phase 5] Callers: rmi_raw_event ← hid_input_report; empty size rejected at hid-core.c:2111–2115.
- [Phase 6] Bug present; apply clean; no duplicate fix.
- [Phase 8] Failure mode: 1-byte OOB read on all-0xff reports; HID input path.
- UNVERIFIED: stable@ lore search (HTTP 403).

**YES**

 drivers/hid/hid-rmi.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/hid/hid-rmi.c +1 -1
index d55a0388895fb..ecc19387f6b05 100644
@@ -386,7 +386,7 @@ static int rmi_check_sanity(struct hid_device *hdev, u8 *data, int size)
 	 * such reports here.
 	 */
 
-	while ((data[valid_size - 1] == 0xff) && valid_size > 0)
+	while (valid_size > 0 && data[valid_size - 1] == 0xff)
 		valid_size--;
 
 	return valid_size;
Signature · 1 line
2.53.0
author maintainer
#78 lore raw

PATCH 1/1 ata: ata_generic: Don't store pci_device_id

In reply to Sasha Levin

From: Gary Guo <[email protected]>

[ Upstream commit 4f3075f629077a8cb3d3455c794a1f4a8fc8b43e ]

pci_device_id is not guaranteed to live longer than probe due to presence of dynamic ID. All information apart from driver_data can be easily retrieved from pci_dev, so just store driver_data.

---

LLM Generated explanations, may be completely bogus:

I have the history, the series context, and the UAF path. Next I’ll write the full nine-phase verdict for this 7.3-rc4 tree.

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

**Step 1.1: PARSE THE SUBJECT LINE**

Record: [ata / ata_generic] [Don't store] [Stop keeping a pointer to struct pci_device_id in host private_data; keep only driver_data]

Subsystem prefix is ata: ata_generic:. Action is “Don’t store” — defensive lifetime fix, not a feature.

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

Record:
- **Fixes:** none (expected for this review pipeline)
- **Reported-by:** none on this commit
- **Tested-by:** none
- **Reviewed-by:** Danilo Krummrich <[email protected]> (PCI/driver- core)
- **Acked-by:** Damien Le Moal <[email protected]> (libata maintainer)
- **Link:** https://patch.msgid.link/20260723-pci_id_fix-v4-1- [email protected] (v4 patch 1/9)
- **Cc: stable:** none (not a negative signal)
- **Signed-off-by:** Gary Guo (author); Bjorn Helgaas (PCI maintainer, committer)
- Ignore any Sasha Levin SOB if present — none on the actual git commit 4f3075f629077

Notable: ATA maintainer Ack plus PCI maintainer commit. Series name pci_id_fix-v4 — this is patch 1 of 9.

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

Record:
- **Bug:** pci_device_id is not guaranteed to outlive probe because PCI dynamic IDs (new_id / remove_id) can free that object.
- **Symptom/failure mode:** later dereference of ap->host->private_data as const struct pci_device_id * is a use- after-free.
- **Version info:** none in the message.
- **Root cause:** ata_generic_init_one() stored the id pointer via ata_pci_bmdma_init_one(..., (void *)id, ...). generic_set_mode() later reads id->driver_data. Only driver_data is needed; vendor/device can come from pci_dev.

**Step 1.4: DETECT HIDDEN BUG FIXES**

Record: Not a disguised cleanup. The subject is lifetime hygiene, but the mechanism is a real UAF if a dynamic ID is freed while the ATA host still holds the pointer. Cover letter for the series calls storing pci_device_id from probe a “bad pattern” and names a genuine dynamic- ID UAF (Sashiko report, used for the PCI-core patch). This driver change is both a standalone dangling-pointer fix and a prerequisite so PCI core can shrink dyn-ID lifetime.

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

**Step 2.1: INVENTORY THE CHANGES**

Record:
- File: drivers/ata/ata_generic.c — 3 insertions, 3 deletions (net 0, 6 lines touched)
- Functions: generic_set_mode(), ata_generic_init_one()
- Scope: single-file surgical fix

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

Hunk 1 (generic_set_mode):
- Before: const struct pci_device_id *id = ap->host->private_data; then id->driver_data & ATA_GEN_FORCE_DMA
- After: unsigned long driver_data = (unsigned long)ap->host->private_data; then driver_data & ATA_GEN_FORCE_DMA
- Path: ATA mode programming, including libata error handling (ata_eh_set_mode() → ap->ops->set_mode), not probe-only

Hunk 2 (ata_generic_init_one):
- Before: ata_pci_bmdma_init_one(..., (void *)id, 0) stores the full pci_device_id *
- After: ata_pci_bmdma_init_one(..., (void *)id->driver_data, 0) stores the integer flags only
- Path: PCI probe / host registration

ATA_GEN_CLASS_MATCH and ATA_GEN_INTEL_IDER remain consumed from the live id argument during probe only — they are not read from private_data.

**Step 2.3: IDENTIFY THE BUG MECHANISM**

Record:
- **Category:** memory safety / use-after-free (stale pointer)
- **Mechanism:** PCI remove_id_store() does list_del + kfree(dynid) under dynids.lock without unbinding devices. If the host was bound via that dyn ID, host->private_data still pointed at dynid->id. generic_set_mode() later loads id->driver_data.
- After the later PCI-core change in this same series (3ffc4c9690c33), dyn-ID matches return a **stack copy** valid only during probe (include/linux/pci.h: “The pci_device_id parameter is only valid during probe.”). Storing that pointer past probe would then be a stack UAF even without remove_id. This driver patch must land first (and it did: v4-1 before v4-9).

**Step 2.4: ASSESS THE FIX QUALITY**

Record:
- Obviously correct: the only post-probe use was id->driver_data; copy that integer instead of the object.
- Minimal; no unrelated edits; no API change.
- Regression risk: very low. driver_data values are small flags (1<<0..1<<2). Same void * ↔ unsigned long trick already used elsewhere (e.g. pata_amd.c).
- This tree already contains the after-state (4f3075f629077 is an ancestor of HEAD).

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

**Step 3.1: BLAME THE CHANGED LINES**

Record:
- Storing the pci_device_id * in host->private_data was introduced in 1529c69adce1e (“ata_generic: implement ATA_GEN_* flags and force enable DMA on MBP 7,1”), 2010-07-01, contained in v2.6.35-rc4.
- That commit is an ancestor of this tree. The pattern is ~16 years old, not new 7.3 code.

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

Record: No Fixes: tag on this commit. The buggy pattern is 1529c69adce1e, verified present. Related PCI-core UAF has `Fixes:
0994375e9614 (“PCI: add remove_id sysfs entry”) on 3ffc4c9690c33` — different patch, same series.

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

Record (last commits on drivers/ata/ata_generic.c):
- 4f3075f629077 this fix
- 9986ce65bebb9 constify pci_device_id (unrelated)
- No other recent functional churn at these lines

Standalone vs series: **patch 1/9** of pci_id_fix. Sibling driver patches (nsp32, tpci200, mlxsw, agp). PCI core is patches 7–9. **This patch applies standalone**; it does not call new PCI helpers.

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

Record: Gary Guo is not the ATA maintainer; he is the series author (Rust/PCI ID work). Nearby same-author commits: 3c28376273e8f nsp32, 9a1b9aa5cedf3 tpci200, 1ae2920768f79 mlxsw, plus PCI TOCTOU/UAF. Damien Le Moal Acked this ATA patch. Bjorn Helgaas committed it.

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

Record: No prerequisites. ata_pci_bmdma_init_one(..., void *host_priv, ...) has taken an opaque host_priv for a long time (libata-sff.c). This is a caller-side change only. Later PCI patches depend on *this* class of driver fix, not the reverse.

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

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

Record:
- b4 dig -c 4f3075f629077 matched patch-id; lore URL: https://patch.m sgid.link/[email protected]
- b4 dig -a revisions:
- v1 2026-06-26: PCI match refactor only (this driver fix not yet present)
- v2 2026-06-30: [PATCH v2 1/7] ata: don't keep pci_device_id — driver stores added
- v3 2026-07-06: [PATCH v3 1/9] ata: don't store pci_device_id
- v4 2026-07-23: applied version; cover: “PCI: Fix UAF and TOCTOU related to dynamic ID”
- v2 changelog: “Fix users which store pci_device_id.” v4: style fixes from Bjorn. Applied version is latest.
- No NAK on this patch. Sashiko bot: “found no issues.”
- Cover letter: Sashiko reported a genuine dynamic-ID UAF; storing pci_device_id from probe is called out as a bad pattern.

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

Record (b4 dig -w): linux-ide, linux-pci, driver-core, linux-scsi, netdev, dri-devel; Damien Le Moal, Niklas Cassel, Bjorn Helgaas, Danilo Krummrich, Greg KH. Right maintainers were on CC. Reviewed-by Krummrich, Acked-by Le Moal, committed by Helgaas.

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

Record: This specific ATA patch has no Reported-by. The series UAF report is on patch 9: Reported-by: Sashiko <[email protected]> / lore [email protected]. Direct WebFetch of lore returned HTTP 403; thread was recovered via b4 dig -m. No user crash log for ata_generic itself.

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

Record: 9-patch series. Patches 1–6 fix drivers that stash or pointer- arithmetic the ID. Patches 7–9 change PCI matching, dyn-ID TOCTOU, and concurrent probe vs remove_id UAF. This commit is self-contained; it does not require 7–9 to be correct. If 9 were backported without 1, dyn- ID probe would hand a stack copy to ata_generic, which would then store it — a worse UAF. Evaluating **this** commit alone: it is independently correct.

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

Record: curl/WebFetch to lore.kernel.org/stable/ returned 403. The saved v4 thread contains **no** Cc: stable discussion. **UNVERIFIED:** whether anyone asked for this on the stable list.

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

**Step 5.1: IDENTIFY KEY FUNCTIONS**

Record: generic_set_mode(), ata_generic_init_one(). (semcode MCP not available; used hunks + grep.)

**Step 5.2: TRACE CALLERS**

Record:
- ata_generic_init_one — PCI .probe of ata_generic_pci_driver (device bind).
- generic_set_mode — generic_port_ops.set_mode. Called from ata_eh_set_mode() in drivers/ata/libata-eh.c when ap->ops->set_mode is set. That runs from ata_eh_recover() when ATA_EHI_SETMODE is set (initial config, reset, revalidate). **After probe**, disk errors / resume / EH can invoke it.

**Step 5.3: TRACE CALLEES**

Record: ata_pci_bmdma_init_one() stores host_priv on the ata_host. generic_set_mode reads BMDMA status and libata xfer-mask helpers. No new allocations or locks.

**Step 5.4: FOLLOW THE CALL CHAIN**

Record:
- Common path: PCI probe of a device in the static ata_generic[] table → id points at module .rodata for the module’s lifetime → **no UAF** on static IDs.
- Buggy path: echo ... > /sys/bus/pci/drivers/ata_generic/new_id (typically CAP_SYS_ADMIN) → bind via heap pci_dynid → store pointer → remove_id kfree’s dynid while host still bound → later EH generic_set_mode → UAF.
- Reachable from userspace: yes, via PCI sysfs + later ATA EH. Not a normal unprivileged syscall path.

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**

Record: Same-series fixes in nsp32, tpci200, mlxsw, agp. Other ATA drivers store their own hpriv, not pci_device_id *. Pattern was systematic across PCI drivers, not unique to ATA.

===============================================================
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 = v7.3-rc4-27-gf0100363d8c37; make kernelversion = 7.3.0-rc4 (Linus mainline, detached HEAD).
- Commit 4f3075f629077 **is already an ancestor of HEAD** (git merge- base --is-ancestor succeeded; first appeared in v7.3-rc1).
- Current drivers/ata/ata_generic.c already stores id->driver_data and reads it as unsigned long.
- The **pre-fix** code existed on this lineage from 1529c69adce1e (v2.6.35) until that commit. This is not a “bug introduced after this tree branched” case.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**

Record: Against the pre-fix file (4f3075f629077^), the diff is a clean 6-line replace. No refactor of ata_generic.c in between. Expected apply on a tree that still has the old pointer store: **clean**. On *this* checkout the after-state is already present, so re-applying the patch would be a no-op/conflict with itself — that is git ancestry, not a missing-code problem.

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

Record: This exact fix is in HEAD. PCI-core companion 3ffc4c9690c33 is also an ancestor. No alternate/earlier ata_generic dyn-ID fix found (git log --grep=pci_device_id -- drivers/ata/ata_generic.c only this commit and an unrelated constify).

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

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

Record: drivers/ata/ — libata generic PCI IDE driver (CONFIG_ATA_GENERIC). **IMPORTANT** for machines that still use BIOS- configured PATA/IDE (Cenatek FORCE_DMA, Intel IDE-R, various legacy chips). Not mm/net core, but storage.

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**

Record: libata is actively maintained (recent EH/LPM/AHCI fixes). ata_generic.c itself is mature; little churn besides this lifetime fix.

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

**Step 8.1: DETERMINE WHO IS AFFECTED**

Record: Driver-specific (CONFIG_ATA_GENERIC), and the UAF only if the host was bound via a **dynamic** PCI ID. Static-table devices (the usual case) keep id in module memory. Affected population: admins using new_id on ata_generic, then remove_id or (after PCI stack-copy) any post-probe set_mode.

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**

Record:
- Trigger: privileged sysfs new_id/remove_id, then ATA EH set_mode.
- Likelihood on production LTS: **low** (dyn IDs are uncommon for this driver).
- Unprivileged trigger: **no** (driver new_id/remove_id are root- owned sysfs). Still a real kernel UAF, not theoretical pointer math.

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

Record: Use-after-free of pci_dynid / dangling ID pointer → KASAN/oops or worse. **Severity: HIGH** when triggered; **likelihood: LOW**.

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

Record:
- **Benefit:** Prevents a real UAF in a long-lived storage driver; 3-line change; maintainer-acked. Also keeps the driver correct if the PCI dyn-ID lifetime fix is applied.
- **Risk:** Very low (tiny, local, no locking/API).
- **Ratio:** favorable. Conservative “rare trigger” concern does not outweigh UAF + trivial patch.

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

**Step 9.1: COMPILE THE EVIDENCE**

FOR backporting:
- Real UAF: host->private_data held pci_device_id * beyond probe; remove_id can free dyn IDs; generic_set_mode runs from libata EH after probe.
- Bug present since v2.6.35 (1529c69adce1e); code exists on this lineage.
- 6-line, obviously correct; only driver_data was used post-probe.
- Reviewed/Acked by PCI and ATA maintainers; PCI maintainer committed it.
- No new APIs/features.
- Self-contained; no missing helpers in this tree.

AGAINST:
- Common static-ID path was not buggy; trigger needs dyn-ID sysfs (root).
- No user crash report / syzbot on this exact driver file.
- Part of a 9-patch series whose headline UAF is PCI-core patch 9; this was added in v2 as “fix users which store pci_device_id.”
- No Cc: stable in the thread (absence is expected).

UNRESOLVED:
- lore.kernel.org HTTP 403 for live pages; used b4 dig mbox instead.
- Stable-list discussion UNVERIFIED (403).

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

1. Obviously correct and tested? **PASS** — logic is local and reviewed; Sashiko found no issues on v4-1.
2. Fixes a real bug that affects users? **PASS** — dangling pci_device_id after dyn-ID removal / after probe lifetime; users of ata_generic + new_id can hit it.
3. Important issue (crash, security, corruption, deadlock)? **PASS** — UAF → oops/KASAN (HIGH, rare trigger).
4. Small and contained? **PASS** — 6 lines, one file.
5. No new features or APIs? **PASS**.
6. Can apply to the local tree? **PASS** for trees still on the old pointer store. This 7.3-rc4 checkout already contains the commit; that does not make the fix unsuitable — it confirms the code and helpers exist here.

**Step 9.3: CHECK FOR EXCEPTION CATEGORIES**

Record: None (not a device ID / quirk / DT / build / docs exception). Qualifies as a normal small UAF fix.

**Step 9.4: MAKE YOUR DECISION**

This tree is **Linux 7.3-rc4** (mainline). ata_generic is present; the buggy store-the-id-pointer pattern lived here from 2010 until 4f3075f629077. The patch is a 3-line lifetime fix for a real UAF, not a feature or refactor, and it applies in isolation.

Rare privileged trigger is not enough to reject a tiny, maintainer-acked UAF fix in a storage driver. It meets stable-kernel-rules.

### What the commit solves (for stable users)

ata_generic used to keep a pointer to the pci_device_id passed into probe. For IDs added through sysfs new_id, that object can be freed by remove_id while the ATA host is still live. generic_set_mode() — including from error handling — then dereferences freed memory. The fix copies driver_data (the only field used later) and drops the pointer.

### Risk vs benefit

Benefit is avoiding a UAF/oops on a long-standing driver. Risk is negligible. No prerequisites missing in this tree.

---

Verification:
- [Phase 1] Parsed tags on 4f3075f629077: Reviewed-by Danilo Krummrich, Acked-by Damien Le Moal, Link to v4-1; no Fixes/Reported- by/Cc:stable
- [Phase 1] Subject/body: don’t store pci_device_id; dyn-ID lifetime
- [Phase 2] Diff: 3+ / 3- in drivers/ata/ata_generic.c; generic_set_mode + ata_generic_init_one
- [Phase 2] Pre-fix file via git show 4f3075f629077^:drivers/ata/ata_generic.c: stored (void *)id, later id->driver_data & ATA_GEN_FORCE_DMA
- [Phase 3] git blame / git log -S private_data -- drivers/ata/ata_generic.c: introduced 1529c69adce1e (2010, v2.6.35-rc4)
- [Phase 3] git merge-base --is-ancestor 1529c69adce1e HEAD — yes; 4f3075f629077 — yes
- [Phase 3] Series: 3c28376273e8f, 9a1b9aa5cedf3, 1ae2920768f79, c967b365d7b51, 04fde70f782b6, 3ffc4c9690c33
- [Phase 4] b4 dig -c 4f3075f629077: patch.msgid.link v4-1; -a:
v1–v4; -w: linux-ide/linux-pci + Le Moal/Helgaas
- [Phase 4] b4 dig -m: cover letter genuine dyn-ID UAF; this patch added in v2; no NAK; Sashiko OK
- [Phase 4] WebFetch lore/patch.msgid.link: HTTP 403; used b4 mbox instead
- [Phase 4] Stable list: UNVERIFIED (403)
- [Phase 5] Callers: PCI probe; ata_eh_set_mode() in libata-eh.c lines 3480–3482 and 3962–3963
- [Phase 5] remove_id_store() in drivers/pci/pci-driver.c kfree’s dynid without unbind
- [Phase 5] include/linux/pci.h ~989: id only valid during probe (after series)
- [Phase 6] git describe HEAD = v7.3-rc4-27-gf0100363d8c37; kernelversion 7.3.0-rc4
- [Phase 6] Current file already has the fix (commit in 7.3-rc1)
- [Phase 7] CONFIG_ATA_GENERIC in drivers/ata/Kconfig — generic BIOS ATA, PCI+BMDMA
- [Phase 8] Failure mode: UAF in EH set_mode; severity HIGH; trigger privileged dyn-ID; risk of the patch itself very low
- UNVERIFIED: stable@ lore discussion (HTTP 403)

The patch is small, fixes a real use-after-free, and meets stable criteria for this tree’s ata_generic code.

**YES**

 drivers/ata/ata_generic.c | 6 +++---
 1 file changed, 3 insertions(+), 3 deletions(-)
drivers/ata/ata_generic.c +3 -3
index e70b6c089cf17..18ea740ca5829 100644
@@ -51,11 +51,11 @@ enum {
 static int generic_set_mode(struct ata_link *link, struct ata_device **unused)
 {
 	struct ata_port *ap = link->ap;
-	const struct pci_device_id *id = ap->host->private_data;
+	unsigned long driver_data = (unsigned long)ap->host->private_data;
 	int dma_enabled = 0;
 	struct ata_device *dev;
 
-	if (id->driver_data & ATA_GEN_FORCE_DMA) {
+	if (driver_data & ATA_GEN_FORCE_DMA) {
 		dma_enabled = 0xff;
 	} else if (ap->ioaddr.bmdma_addr) {
 		/* Bits 5 and 6 indicate if DMA is active on master/slave */
@@ -206,7 +206,7 @@ static int ata_generic_init_one(struct pci_dev *dev, const struct pci_device_id
 			return rc;
 		pcim_pin_device(dev);
 	}
-	return ata_pci_bmdma_init_one(dev, ppi, &generic_sht, (void *)id, 0);
+	return ata_pci_bmdma_init_one(dev, ppi, &generic_sht, (void *)id->driver_data, 0);
 }
 
 static const struct pci_device_id ata_generic[] = {
Signature · 1 line
2.53.0
author maintainer
#79 lore raw

PATCH 1/1 soundwire: intel_auxdevice: Add cs42l44 to wake_capable_list

In reply to Sasha Levin

From: Charles Keepax <[email protected]>

[ Upstream commit d08e4d9197396ceb906715d976b63aed0c5cc8e5 ]

Add cs42l44 to the wake_capable_list because it can generate jack events whilst the bus is stopped.

---

LLM Generated explanations, may be completely bogus:

I have enough to judge this: it is a one-line Intel SoundWire wake quirk for CS42L44, which this 7.3-rc4 tree already contains.

## Local tree

- git describe HEAD: v7.3-rc4-27-gf0100363d8c37
- make kernelversion: 7.3.0-rc4
- Makefile: VERSION=7 PATCHLEVEL=3 SUBLEVEL=0 EXTRAVERSION=-rc4
- Commit under review: d08e4d9197396ceb906715d976b63aed0c5cc8e5
- git merge-base --is-ancestor d08e4d9197396 HEAD: yes (merged via soundwire-7.3-rc1; not in v7.2)

Verdict is for this 7.3-rc4 checkout only. intel_auxdevice.c, wake_capable_list, and is_wake_capable() are present here. This is a host-side ID quirk in an existing Intel SoundWire master driver.

---

## PHASE 1: COMMIT MESSAGE FORENSICS

**Step 1.1: PARSE THE SUBJECT LINE**
Record: [soundwire/intel_auxdevice] [Add] [put CS42L44 on the Intel wake-capable quirk list]

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**
Record:
- Fixes: none (expected)
- Reported-by: none
- Tested-by: none
- Reviewed-by: none on the committed version
- Acked-by: none
- Link: https://patch.msgid.link/20260708122948.1502227-1- [email protected]
- Cc: [email protected]: none (expected)
- Signed-off-by: Charles Keepax <[email protected]> (Cirrus, chip vendor)
- Signed-off-by: Vinod Koul <[email protected]> (SoundWire maintainer)
- Ignore any Sasha Levin SOB / [Upstream commit] markers (none in the real commit)

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**
Record:
- Bug: CS42L44 can raise jack events while the SoundWire bus is clock- stopped, but the Intel master did not treat it as wake-capable.
- Symptom: headset plug/unplug while audio is idle is missed; bus/system does not wake for jack detect.
- Version info: none in the message. Commit landed for 7.3-rc1.
- Root cause (from this patch plus e66f91a2d10b9): ACPI does not export wake capability; the codec driver’s wake_capable flag is too late (set at probe, after device-number assignment). The Intel master uses a static mfg/part quirk table.

**Step 1.4: DETECT HIDDEN BUG FIXES**
Record: Not disguised cleanup. Explicit hardware-quirk / device-ID addition.

---

## PHASE 2: DIFF ANALYSIS

**Step 2.1: INVENTORY THE CHANGES**
Record:
- File: drivers/soundwire/intel_auxdevice.c (+1 / -0)
- Function: none; one entry in wake_capable_list[]
- Scope: single-file surgical ID add

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**
Record:
- Before: {0x01fa, 0x4244} was absent, so is_wake_capable() returned false for CS42L44 unless firmware already set slave->prop.wake_capable.
- After: match on Cirrus mfg_id 0x01fa + part_id 0x4244.
- Path: SoundWire enumeration / device-number allocation (intel_get_device_num_ida, generic_new_peripheral_assigned), not an error path.

**Step 2.3: IDENTIFY THE BUG MECHANISM**
Record:
- Category: **hardware workaround / device ID in an existing quirk table**
- Mechanism: Intel Lunar Lake-class wake requires a system-unique SDI and IDA device numbers in a reserved range. Without the list entry, CS42L44 is allocated a non-wake number, program_sdi() is skipped, and jack IRQs while the bus is stopped are not handled.

**Step 2.4: ASSESS THE FIX QUALITY**
Record:
- Obviously correct: same pattern as CS42L43 (0x4243), CS42L45 (0x4245), CS42L49 (0x4249), CS42L43B (0x2A30/0x2A3B).
- Minimal: one array line; no API, locking, or structure change.
- Regression risk: very low. Extra list iteration is cheap; the new ID only matches that part. Wrong SDI assignment would only affect that exact codec, and the vendor authored the entry.
- Nearby gap (does not make this patch wrong):
drivers/mfd/cs42l43-sdw.c still has no SDW_SLAVE_ENTRY for 0x4244. DT only gained cirrus,cs42l44 later (d4c669890ed08). This commit is still the correct host-side quirk.

---

## PHASE 3: GIT HISTORY INVESTIGATION

**Step 3.1: BLAME THE CHANGED LINES**
Record:
- Table introduced in e66f91a2d10b9 (2023-07-31, described as v6.5-rc1-6-ge66f91a2d10b9): “add hybrid IDA-based device_number allocation”.
- That commit states the quirk table is expected to grow for each new headset codec because firmware does not provide wake capability.
- Line 0x4244 itself is this commit (d08e4d9197396, Charles Keepax, 2026-07-08).

**Step 3.2: FOLLOW THE FIXES: TAG**
Record: No Fixes: tag. Not applicable. The “bug” is an incomplete quirk table, not a regression from a single earlier SHA.

**Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES**
Record: Same one-line additions: fe600c8e2dc5d (cs42l43), f87e5575a6bd1 (cs42l45), b8f2d65fec19f (cs42l49), be6d8daaab654 (cs42l43b), 4b8fc2b17272d (CS47L47), 4e90368e8680d (es9356). Standalone, not N/M.

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**
Record: Charles Keepax is a regular Cirrus SoundWire/ASoC contributor and also authored the CS42L43B and CS42L49 wake-list entries. Vinod Koul applied it.

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS**
Record: Depends only on wake_capable_list / is_wake_capable(), present here since e66f91a2d10b9. Applies standalone. No new helper or struct.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**
Record:
- b4 dig -c d08e4d9197396: https://patch.msgid.link/20260708122948.15 [email protected]
- b4 dig -a: v1 only; committed version is that v1
- Thread: submit (Keepax) + “Applied, thanks!” (Vinod Koul). No NAK, no v2, no reviewer risk notes, no Cc: stable in-thread.

**Step 4.2: CHECK WHO REVIEWED THE PATCH**
Record (b4 dig -w): To [email protected]; Cc Bard Liao, Pierre-Louis Bossart, linux-sound, linux-kernel, Cirrus patches. Maintainer applied; no extra Reviewed-by on this revision.

**Step 4.3: SEARCH FOR THE BUG REPORT**
Record: No bugzilla/syzbot. Vendor (Cirrus) patch. Later DT text:
“cs42l44 is a cost optimised variant of cs42l43b” (d4c669890ed08).

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**
Record: Standalone 1/1. Related later: DT compatible only. MFD SoundWire ID for 0x4244 is still missing in this tree.

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**
Record: lore.kernel.org/stable fetch returned 403. Web search found [PATCH AUTOSEL 6.19-6.12] ... add cs42l45 codec to wake_capable_list — same class of ID was auto-selected for stable. No evidence this CS42L44 patch was rejected for stable.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

**Step 5.1: IDENTIFY KEY FUNCTIONS**
Record: wake_capable_list[] data only. Consumers: is_wake_capable(), intel_get_device_num_ida(), intel_put_device_num_ida(), generic_new_peripheral_assigned().

**Step 5.2: TRACE CALLERS**
Record:
- is_wake_capable() is static; three call sites in this file (lines 135, 269, 283).
- intel_get/put_device_num_ida are sdw_intel_ops.get_device_num / put_device_num.
- generic_new_peripheral_assigned is sdw_intel_ops.new_peripheral_assigned.
- Context: Intel SoundWire enumeration / PM, not syscall-hot or IRQ handler body.

**Step 5.3: TRACE CALLEES**
Record: ida_alloc_range / ida_free for wake devices; hw_ops->program_sdi() when wake-capable.

**Step 5.4: FOLLOW THE CALL CHAIN**
Record: ACPI Intel SoundWire controller → peripheral enumeration → device number → optional SDI programming. Reachable on Intel laptops with this codec when audio clocks stop (idle/runtime PM). Not a userspace-triggered memory-safety bug; it is a device-operation path.

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**
Record: Same Cirrus IDs already in the table (0x4243, 0x4245, 0x4249, 0x2A30, 0x2A3B). sdca_class.c binds 0x4245/0x4249/0x4747 but not 0x4244. cs42l43-sdw.c binds 0x4243 and 0x2A3B only.

---

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

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?**
Record: Yes, the Intel quirk table and lookup exist (drivers/soundwire/intel_auxdevice.c). Without this ID, CS42L44 would not be wake-capable here. e66f91a2d10b9 is from 2023; the table is long-lived. This commit is already in 7.3-rc1+, so the ID is present at HEAD; the evaluation is whether that change belongs in this tree’s stable stream, not whether 6.x is different.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**
Record: Clean apply: insert {0x01fa, 0x4244} next to the other Cirrus entries. No refactor needed on this tree.

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**
Record: This SHA is already an ancestor of HEAD. Sibling codec IDs are already in the same table. No alternate CS42L44 wake fix.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

**Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY**
Record: drivers/soundwire/ Intel master (CONFIG_SOUNDWIRE_INTEL). **IMPORTANT** for Intel laptop audio, not core mm/VFS. Peripheral relative to the whole kernel; standard for headset jack/wake.

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**
Record: Active (regular wake-list IDs, DMI quirks, cadence clock-stop work). The table mechanism itself has been stable since 2023.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

**Step 8.1: DETERMINE WHO IS AFFECTED**
Record: Intel SoundWire hosts with Cirrus CS42L44 (mfg 0x01fa, part 0x4244). No effect on other devices.

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**
Record: Jack insert/remove while the SoundWire bus is stopped (runtime idle / clock stop). Common on laptops. Not a security trigger from unprivileged syscalls.

**Step 8.3: DETERMINE THE FAILURE MODE SEVERITY**
Record: Missed jack / wake events (headset not detected until something else restarts the bus). **MEDIUM** functional hardware bug; not oops/corruption. Covered by the hardware-quirk exception.

**Step 8.4: CALCULATE RISK-BENEFIT RATIO**
Record:
- Benefit: restores jack-wake on CS42L44, same as sibling Cirrus codecs.
- Risk: very low (one static ID).
- Ratio: strongly favors backport.

---

## PHASE 9: FINAL SYNTHESIS

**Step 9.1: COMPILE THE EVIDENCE**

FOR:
- One-line ID in an existing Intel SoundWire quirk table
- Real hardware: CS42L44 is a documented CS42L43B cost-down variant (Cirrus + DT cirrus,cs42l44)
- Without it, jack events while the bus is stopped are dropped (by design of e66f91a2d10b9)
- Same pattern already used for cs42l43/45/49/43b; cs42l45 was AUTOSEL’d for stable
- Vendor author, SoundWire maintainer applied, v1 accepted
- Applies cleanly; no new API

AGAINST:
- Not a crash/UAF/security fix
- No Reported-by from end users
- MFD cs42l43-sdw.c still lacks 0x4244, so codec bind on Intel SDW is incomplete in this tree
- No in-thread Cc: stable (not a negative per rules)

UNRESOLVED:
- lore.kernel.org/stable search HTTP 403
- How many shipping Intel SKUs use CS42L44 (unverified; vendor patch is the evidence)

The missing MFD ID is a separate gap. This patch only teaches the **Intel master** to treat the part as wake-capable at enumeration, which must happen before codec probe. That is exactly what this table is for.

**Step 9.2: APPLY THE STABLE RULES CHECKLIST**
1. Obviously correct and tested? **PASS** — one ID, established table, maintainer applied
2. Fixes a real bug that affects users? **PASS** — missed jack/wake on CS42L44
3. Important issue? **PASS** via hardware-quirk exception (broken jack detect while bus stopped)
4. Small and contained? **PASS** — +1 line, one file
5. No new features or APIs? **PASS** — ID in existing quirk list, not a new driver
6. Can apply to the local tree? **PASS** — wake_capable_list exists; patch is a clean insert

**Step 9.3: CHECK FOR EXCEPTION CATEGORIES**
Record: **Hardware quirk / device ID addition to an existing driver** (wake_capable_list in intel_auxdevice.c). Prompt: these are YES for stable.

**Step 9.4: MAKE YOUR DECISION**
This tree has the Intel SoundWire master and the quirk table. Adding CS42L44 is the same class of change as USB/PCI ID and codec quirks:
small, obviously correct, and required for real hardware. Benefit outweighs risk.

---

## What the commit solves for this tree

On Intel SoundWire, device numbers for wake-capable codecs must be assigned at enumeration from a reserved IDA range, and SDI must be programmed. Firmware does not advertise wake capability, and the codec driver has not probed yet, so the master uses wake_capable_list. CS42L44 can generate jack IRQs while the bus is clock-stopped; without {0x01fa, 0x4244} those events are lost. That is a real user-visible headset-detect failure, not a new feature.

Risk is a single static table entry. No locking, alloc, or ABI change.

---

## Verification

- [Phase 1] git show d08e4d9197396 --format=fuller: tags as listed; body is the two-line jack-event rationale
- [Phase 2] Diff: +{0x01fa, 0x4244} only in wake_capable_list
- [Phase 2] Read intel_auxdevice.c: is_wake_capable() used at lines 135, 269, 283
- [Phase 3] git blame -L 53,77 drivers/soundwire/intel_auxdevice.c:
table from e66f91a2d10b9; this ID from d08e4d9197396
- [Phase 3] git show e66f91a2d10b9: explains why the quirk table exists and will grow
- [Phase 3] git merge-base --is-ancestor d08e4d9197396 HEAD: yes; not an ancestor of v7.2; is in v7.3-rc1
- [Phase 3] No Fixes:; related one-liners listed above
- [Phase 4] b4 dig -c/-a/-w/-m: v1 lore thread; Vinod applied; recipients include Liao, Bossart, linux-sound
- [Phase 4] WebSearch: AUTOSEL of the cs42l45 equivalent; CS42L44 thread has no NAK
- [Phase 4] UNVERIFIED: stable@ lore (HTTP 403)
- [Phase 5] Callers confirmed by grep in drivers/soundwire/intel_auxdevice.c
- [Phase 5] cs42l43-sdw.c id_table: 0x4243 and 0x2A3B only — no 0x4244 (verified)
- [Phase 6] git describe HEAD / make kernelversion: 7.3.0-rc4; file and table present
- [Phase 6] git show d4c669890ed08: DT cirrus,cs42l44 = cost- optimised CS42L43B
- [Phase 8] Failure mode: missed jack/wake, not oops; quirk exception applies

**YES**

 drivers/soundwire/intel_auxdevice.c | 1 +
 1 file changed, 1 insertion(+)
drivers/soundwire/intel_auxdevice.c +1 -0
index c0c8ffcecc6bf..347e06ad6edba 100644
@@ -54,6 +54,7 @@ static struct wake_capable_part wake_capable_list[] = {
 	{0x01fa, 0x2A30},
 	{0x01fa, 0x2A3B},
 	{0x01fa, 0x4243},
+	{0x01fa, 0x4244},
 	{0x01fa, 0x4245},
 	{0x025d, 0x5682},
 	{0x025d, 0x700},
Signature · 1 line
2.53.0
author maintainer
#80 lore raw

PATCH 1/1 nvmet: zns: reject full zone report when buffer is too small

In reply to Sasha Levin

From: Xixin Liu <[email protected]>

[ Upstream commit 86985da12699360a2b20748c5a492ddd92db8c47 ]

Zone Management Receive uses the Partial Report (PR) bit in dword 13. On a partial report (PR bit set), the host accepts an incomplete listing and Number of Zones must not exceed the zone descriptors copied to the host buffer. On a full report (PR bit clear), Number of Zones is the total number of matching zones and every descriptor must fit in the buffer (ZNS Command Set Specification Rev 1.2, section 3.4.2).

nvmet_bdev_zone_zmgmt_recv_work() already caps Number of Zones for partial reports, but on a full report it may still succeed when the buffer only holds part of the matching descriptors. Reject the command in that case.

---

LLM Generated explanations, may be completely bogus:

The local tree is **6.12.111** (pending-6.12). The buggy Zone Management Receive path is present here, and this is a small spec- compliance fix that should be backported to this tree.

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

Step 1.1: PARSE THE SUBJECT LINE
- Subsystem prefix: nvmet: zns:
- Action verb: **reject** (prevents an illegal success path)
- Claimed intent: fail a full (PR=0) zone report when the host buffer cannot hold every matching descriptor

Record: [nvmet/zns] [reject] [fail full zone report when the data buffer is too small]

Step 1.2: PARSE ALL COMMIT MESSAGE TAGS
- Signed-off-by: Xixin Liu <[email protected]> (author)
- Reviewed-by: Christoph Hellwig <[email protected]> (NVMe/block maintainer)
- Signed-off-by: Keith Busch <[email protected]> (NVMe maintainer; applied the patch)
- No Fixes: tag (expected for this review pipeline)
- No Reported-by / Tested-by / Link / Cc: stable
- Ignore any pipeline-added Sasha Levin SOB / Upstream markers

Record: Author SOB + Hellwig Reviewed-by + Busch SOB. No syzbot, no user report, no Fixes tag.

Step 1.3: ANALYZE THE COMMIT BODY TEXT
Zone Management Receive uses the Partial Report (PR) bit:
- PR=1 (partial): host accepts an incomplete listing; Number of Zones must not exceed descriptors actually copied.
- PR=0 (full): Number of Zones is the total match count; every matching descriptor must fit (ZNS Command Set Spec Rev 1.2 §3.4.2). If the buffer is too small, the command must be aborted with Invalid Field in Command.

nvmet_bdev_zone_zmgmt_recv_work() already caps Number of Zones for PR=1, but for PR=0 it can still complete successfully when only some matching descriptors were copied.

Record:
- Bug: full report succeeds with incomplete descriptors while Number of Zones is the full match count
- Symptom: initiator sees SUCCESS plus a header that claims more zones than were transferred
- Version info: none in the message; code dates to 2021
- Root cause: PR=0 path never checks nr_zones > out_nr_zones

Step 1.4: DETECT HIDDEN BUG FIXES
Not hidden. This is an explicit protocol-correctness fix: illegal SUCCESS → INVALID_FIELD | DNR.

Record: [Not a disguised cleanup; it is a command-handling bug fix]

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

Step 2.1: INVENTORY THE CHANGES
- File: drivers/nvme/target/zns.c
- Scope: ~10 insertions / 3 deletions in one function
- Function: nvmet_bdev_zone_zmgmt_recv_work()
- Classification: single-file surgical fix

Record: [zns.c, ~+10/-3] [nvmet_bdev_zone_zmgmt_recv_work] [surgical]

Step 2.2: UNDERSTAND THE CODE FLOW CHANGE
Before (this tree, lines 301–309):

```301:309:drivers/nvme/target/zns.c
        /*
  - When partial bit is set nr_zones must indicate the number of zone
  - descriptors actually transferred.
         */
        if (req->cmd->zmr.pr)
                rz_data.nr_zones = min(rz_data.nr_zones,
rz_data.out_nr_zones);

        nr_zones = cpu_to_le64(rz_data.nr_zones);
        status = nvmet_copy_to_sgl(req, 0, &nr_zones, sizeof(nr_zones));
```

After:
- PR=1: same cap as today
- PR=0 and nr_zones > out_nr_zones: set error_loc to numd, return NVME_SC_INVALID_FIELD | NVME_STATUS_DNR, skip writing the header
- Otherwise: unchanged success path

The callback still copies only descriptors that fit (if (rz->nr_zones < rz->out_nr_zones)), then increments nr_zones for every match. So after blkdev_report_zones(), nr_zones is the match count and out_nr_zones is buffer capacity. That comparison is exactly the missing check.

Record: [PR=0 undersized buffer: SUCCESS + inflated nr_zones → INVALID_FIELD | DNR]

Step 2.3: IDENTIFY THE BUG MECHANISM
Category: **logic / protocol correctness** (not UAF, leak, or race).

Mechanism: PR=0 must fail when the buffer cannot hold every matching descriptor. The target currently reports SUCCESS and writes Number of Zones = full match count while copying only out_nr_zones descriptors. A host that iterates report->nr_zones entries then reads past its buffer.

The status and error_loc match the existing too-small-header check in nvmet_bdev_validate_zone_mgmt_recv() (lines 164–166).

Record: [Logic/spec] [PR=0 truncated full report incorrectly succeeds]

Step 2.4: ASSESS THE FIX QUALITY
Obviously correct against the spec and against the existing PR=1 cap. Minimal. No API/data-structure change.

Regression risk is low:
- Linux kernel host always sets c.zmr.pr = NVME_REPORT_ZONE_PARTIAL in nvme_ns_report_zones() — that path is unchanged
- PR=0 with an adequate buffer is unchanged
- Only PR=0 with a too-small buffer flips SUCCESS → error, which is the specified behavior
- Failed commands already goto out in this function; error_loc / NVME_STATUS_DNR are used throughout this file

Record: [High quality, surgical] [Low regression risk; only the illegal success path changes]

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

Step 3.1: BLAME THE CHANGED LINES
git blame -L 267,313 drivers/nvme/target/zns.c: every line of this function is from

aaf2e048af2704 — nvmet: add ZBD over ZNS backend support (Chaitanya Kulkarni, 2021-06-09)

git merge-base --is-ancestor aaf2e048af2704 v6.12 succeeded. The bug has been in this series from the start of 6.12 (and since ~v5.14).

Record: [Introduced by aaf2e048af2704, 2021] [Present in this 6.12 tree]

Step 3.2: FOLLOW THE FIXES: TAG
No Fixes: tag. The introducing commit is the original ZNS target feature, not a later regression.

Record: [No Fixes tag] [Buggy code is the original 2021 implementation, ancestor of HEAD]

Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES
Recent drivers/nvme/target/zns.c history in this tree: identify NULL deref, DNR rename, conv_zones_bitmap, etc. None already implement this PR=0 rejection. Current source still has the old comment and the if (req->cmd->zmr.pr) cap only.

Standalone 1/1 (cover letter on lore confirms a single patch).

Record: [No prior equivalent fix in this file] [Standalone; no series prerequisites]

Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS
Xixin Liu has other NVMe work in this tree (tcp/rdma), but this ZNS recv check is not already here. Review weight comes from Hellwig + Busch, not from the author being the subsystem maintainer.

Record: [Contributor, not nvmet maintainer] [Reviewed/applied by NVMe maintainers]

Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS
Diff uses req->error_loc, offsetof(struct nvme_zone_mgmt_recv_cmd, numd), NVME_SC_INVALID_FIELD | NVME_STATUS_DNR. All exist in this tree (NVME_STATUS_DNR via dd0b0a4a2c5d7, already in 6.12). Context in zns.c matches the pre-image exactly.

Record: [No missing helpers] [Applies standalone to this tree]

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

Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION
lore.kernel.org WebFetch returned 403. Thread recovered from the gnuweeb mirror:

https://lore-kernel.gnuweeb.org/linux-
nvme/[email protected]/T/

- v1: 2026-07-09, nested else { if (...) }
- Hellwig: line too long; use else if
- v2: 2026-07-13, matches the candidate diff
- Hellwig: “Looks good” + Reviewed-by
- Busch: “Thanks, applied to nvme-7.3.”
- No NAK, no stable discussion, no security/crash report
- Author: “Tested on nvmet-tcp loopback with io-passthru.”

b4 dig -c was not used: the candidate SHA is not in this checkout. Thread contents were verified from the archive instead.

Record: [v1→v2 style-only] [Hellwig RB, Busch applied] [No NAK / no Cc:
stable in review]

Step 4.2: CHECK WHO REVIEWED THE PATCH
Original To/Cc: linux-nvme, hch, sagi (Sagi Grimberg), kch (Chaitanya Kulkarni). Right maintainers were on the thread.

Record: [Hellwig reviewed; Busch applied; Kulkarni/Grimberg CCed]

Step 4.3: SEARCH FOR THE BUG REPORT
No Reported-by, bugzilla, or syzbot. Same author also posted a host-side defensive patch (nvme: zns: cap zone report nr_zones by DMA buffer size) because hosts that trust Number of Zones can walk past the DMA buffer. That is independent; this tree’s host zns.c has no max_in_buf yet, and Linux host uses PR=1 anyway.

Record: [No end-user crash report] [Author also wrote a host-side bound against inflated nr_zones]

Step 4.4: CHECK FOR RELATED PATCHES AND SERIES
Cover is 0/1 + 1/1. Self-contained. Host cap patch is a separate hardening change, not a prerequisite for the target rejection.

Record: [Standalone target fix] [Host companion not required here]

Step 4.5: CHECK STABLE MAILING LIST HISTORY lore.kernel.org/stable search also 403. No evidence in the nvme thread that stable was requested or rejected.

Record: [No stable-list discussion found] [UNVERIFIED: could not query lore.kernel.org/stable directly]

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

Step 5.1: IDENTIFY KEY FUNCTIONS IN THE DIFF
Record: [nvmet_bdev_zone_zmgmt_recv_work]

Step 5.2: TRACE CALLERS
- nvmet_bdev_execute_zone_mgmt_recv() queues that work
- Set as req->execute from nvmet_bdev_zns_parse_io_cmd() on nvme_cmd_zone_mgmt_recv
- nvmet_parse_io_cmd() → nvmet_bdev_zns_parse_io_cmd() when req->ns->csi == NVME_CSI_ZNS and CONFIG_BLK_DEV_ZONED

Record: [I/O path for ZNS namespaces on nvmet] [Triggered by Zone Management Receive from an initiator]

Step 5.3: TRACE CALLEES nvmet_bdev_validate_zone_mgmt_recv, blkdev_report_zones / nvmet_bdev_report_zone_cb, nvmet_copy_to_sgl, nvmet_req_complete. No new locks or allocations.

Record: [Existing report/copy/complete helpers only]

Step 5.4: FOLLOW THE CALL CHAIN
Reachable from NVMe-oF (TCP/RDMA/FC/loop) against a ZNS target namespace. Userspace tools (nvme zns report-zones, libnvme, SPDK) can send PR=0. Linux in-kernel host always uses PR=1, so it does not hit the bug, but other initiators can.

Record: [Userspace/NVMe-oF reachable] [Linux kernel host does not use PR=0]

Step 5.5: SEARCH FOR SIMILAR PATTERNS
Only this one PR=0/PR=1 split in nvmet. Host always sets NVME_REPORT_ZONE_PARTIAL. No sibling driver with the same missing full-report check.

Record: [Single instance in nvmet ZNS]

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

Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?
Yes. make kernelversion = 6.12.111; git describe HEAD = p-6.12-3-gc504cf0baa3d8. Current nvmet_bdev_zone_zmgmt_recv_work() still only caps PR=1. Introducer aaf2e048af2704 is an ancestor of v6.12 and of HEAD.

Record: [Bug exists at drivers/nvme/target/zns.c:305-306] [Since aaf2e048af2704 / ~5.14]

Step 6.2: CHECK FOR BACKPORT COMPLICATIONS
Pre-image matches this file exactly (OLD FOUND in a dry-run of the hunk). NVME_STATUS_DNR and numd exist. No refactor in the way.

Record: [Expected clean apply]

Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE
git log --grep on this file found no “reject full zone report”. Host max_in_buf is also absent. No equivalent fix.

Record: [Not already present]

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

Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY drivers/nvme/target/zns.c — NVMe target ZNS backend, built as nvmet-$(CONFIG_BLK_DEV_ZONED).

Record: [nvmet ZNS] [IMPORTANT for NVMe-oF zoned exports; not core mm/VFS]

Step 7.2: ASSESS SUBSYSTEM ACTIVITY
nvmet is actively fixed in this 6.12 tree (TCP OOB, auth, RDMA leaks, ZNS identify NULL deref). ZNS recv itself has been stable since 2021.

Record: [nvmet active; this function long-unchanged]

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

Step 8.1: DETERMINE WHO IS AFFECTED
Config-specific: CONFIG_NVME_TARGET=y and CONFIG_BLK_DEV_ZONED=y, exporting a zoned bdev as a ZNS namespace. Initiators that send Zone Management Receive with PR=0 and a buffer smaller than the matching descriptor list.

Record: [Config-specific: nvmet + zoned bdev + PR=0 full report]

Step 8.2: DETERMINE THE TRIGGER CONDITIONS
Deterministic: PR=0 + numd too small for every matching zone. Not a race. Linux kernel host does not trigger it (PR=1). Userspace and non- Linux NVMe-oF initiators can. Needs access to the subsystem, not a random unprivileged syscall on a machine that is not an NVMe target.

Record: [Deterministic protocol path] [Common for tools that request a full report with a small buffer] [Not a local unprivileged syscall unless nvmet is configured]

Step 8.3: DETERMINE THE FAILURE MODE SEVERITY
Target kernel: no oops, leak, or deadlock — wrong SUCCESS instead of Invalid Field.

Initiator: SUCCESS + Number of Zones = full match count + only a prefix of descriptors transferred. A parser that trusts that count walks past its buffer (userspace OOB / wrong zone map). Incomplete zone inventory can then drive wrong zone management.

Record: [Incorrect SUCCESS / truncated full report] [Severity: MEDIUM — protocol/data-integrity for zoned NVMe-oF, not a target oops]

Step 8.4: CALCULATE RISK-BENEFIT RATIO
Benefit: spec-correct failure instead of a silently truncated zone map; avoids initiator over-read and incomplete inventory. Small but real for nvmet ZNS users.

Risk: ~10 lines, error path only, same status pattern already used in this file. Linux in-kernel host path unchanged.

Record: [Benefit: medium for affected nvmet ZNS users] [Risk: very low] [Favor backport]

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

Step 9.1: COMPILE THE EVIDENCE

FOR:
- Real, deterministic spec violation in command completion (ZNS 1.2 §3.4.2)
- SUCCESS with Number of Zones > descriptors transferred can make initiators over-read or act on an incomplete zone map
- ~10-line surgical change, obviously correct
- Hellwig Reviewed-by, Busch applied; author tested nvmet-tcp loopback
- Buggy code has been in this 6.12 tree since the original ZNS target code (2021)
- Applies cleanly; all symbols exist (NVME_STATUS_DNR, numd, error_loc)
- No new API/feature
- Fits stable-kernel-rules “oh, that's not good” for storage protocol results

AGAINST:
- Not a target oops/UAF/deadlock
- No syzbot or production Reported-by
- Niche: nvmet + zoned + PR=0
- Linux in-kernel host always uses PR=1
- No Cc: stable (not a negative under these review rules)

UNRESOLVED:
- Could not b4 dig a local SHA (commit not in this checkout)
- lore.kernel.org and git.kernel.org fetches were blocked; thread verified via gnuweeb mirror
- Exact mainline SHA not confirmed locally

Step 9.2: APPLY THE STABLE RULES CHECKLIST
1. Obviously correct and tested? **PASS** — spec-aligned; Hellwig RB; author tested loopback
2. Fixes a real bug that affects users? **PASS** — wrong SUCCESS on a real NVMe-oF command
3. Important issue? **PASS** (MEDIUM) — not a kernel oops, but incorrect zoned inventory / initiator over-read; “oh, that's not good” for a storage protocol
4. Small and contained? **PASS** — one function, ~10 lines
5. No new features or APIs? **PASS**
6. Can apply to the local tree? **PASS** — pre-image matches 6.12.111 zns.c

Step 9.3: CHECK FOR EXCEPTION CATEGORIES
Not a device-ID, quirk, DT, build, or docs exception. It is a normal small bugfix.

Step 9.4: MAKE YOUR DECISION
This 6.12 tree still has the original PR=0 hole. The fix is tiny, maintainer-reviewed, and changes only the illegal success path. That is appropriate for this stable tree.

Verification:
- [Phase 1] Tags: Xixin Liu SOB, Christoph Hellwig Reviewed-by, Keith Busch SOB; no Fixes/Reported-by/Cc: stable
- [Phase 1] Body: PR=0 full report must fail when buffer cannot hold every matching descriptor (ZNS 1.2 §3.4.2)
- [Phase 2] Diff: one hunk in nvmet_bdev_zone_zmgmt_recv_work(); PR=1 still capped; PR=0 adds nr_zones > out_nr_zones → NVME_SC_INVALID_FIELD | NVME_STATUS_DNR
- [Phase 2] Callback already copies only out_nr_zones descriptors while counting all matches — verified at drivers/nvme/target/zns.c:227-246
- [Phase 3] git blame: function from aaf2e048af2704 (2021-06-09)
- [Phase 3] git merge-base --is-ancestor aaf2e048af2704 HEAD and ... v6.12: both true
- [Phase 3] No equivalent fix in git log -- drivers/nvme/target/zns.c
- [Phase 4] Thread: https://lore-kernel.gnuweeb.org/linux-
nvme/[email protected]/T/ — v1→v2 style only; Hellwig RB; Busch applied to nvme-7.3
- [Phase 4] UNVERIFIED: b4 dig (SHA not in tree); lore.kernel.org HTTP 403
- [Phase 5] Callers: nvmet_parse_io_cmd → nvmet_bdev_zns_parse_io_cmd → nvmet_bdev_execute_zone_mgmt_recv (core.c:954-961, zns.c:315-318, 614-615)
- [Phase 5] Linux host uses c.zmr.pr = NVME_REPORT_ZONE_PARTIAL (host/zns.c:197)
- [Phase 6] make kernelversion = 6.12.111; buggy if (req->cmd->zmr.pr) still present; dry-run pre-image found; NVME_STATUS_DNR and numd exist
- [Phase 7] Built only with nvmet-$(CONFIG_BLK_DEV_ZONED)
- [Phase 8] Failure mode: incorrect SUCCESS / truncated full report, not a target crash
- UNVERIFIED: whether a later mainline follow-up changed this hunk after nvme-7.3 apply

The problem is a spec-incorrect SUCCESS on a full zone report when the host buffer is too small. That is a real command-handling bug in this 6.12 tree, the patch is small and already matches local code, and the risk is limited to failing a command that was already returning inconsistent data.

**YES**

 drivers/nvme/target/zns.c | 13 ++++++++++---
 1 file changed, 10 insertions(+), 3 deletions(-)
drivers/nvme/target/zns.c +10 -3
index 95af4b67108c7..abf3435ca2900 100644
@@ -299,11 +299,18 @@ static void nvmet_bdev_zone_zmgmt_recv_work(struct work_struct *w)
 	}
 
 	/*
-	 * When partial bit is set nr_zones must indicate the number of zone
-	 * descriptors actually transferred.
+	 * Partial report (PR bit set): the host accepts an incomplete listing,
+	 * so cap Number of Zones to the descriptors that fit in the buffer.
+	 * Full report (PR bit clear): Number of Zones is the match count; fail
+	 * if the buffer cannot hold every matching zone descriptor.
 	 */
-	if (req->cmd->zmr.pr)
+	if (req->cmd->zmr.pr) {
 		rz_data.nr_zones = min(rz_data.nr_zones, rz_data.out_nr_zones);
+	} else if (rz_data.nr_zones > rz_data.out_nr_zones) {
+		req->error_loc = offsetof(struct nvme_zone_mgmt_recv_cmd, numd);
+		status = NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
+		goto out;
+	}
 
 	nr_zones = cpu_to_le64(rz_data.nr_zones);
 	status = nvmet_copy_to_sgl(req, 0, &nr_zones, sizeof(nr_zones));
Signature · 1 line
2.53.0
#81 lore raw

Re: [PATCH AUTOSEL 6.18-5.15] nvmet: zns: reject full zone report when buffer is too small

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] nvmet: zns: broken PR=0 zone reports in nvmet_bdev_zone_zmgmt_recv_work() --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] nvmet: zns: broken PR=0 zone reports in nvmet_bdev_zone_zmgmt_recv_work() --

commit 42bb4c679b1e6318e7ed82bbe79461a255997505
Author: Xixin Liu <[email protected]>

nvmet: zns: reject full zone report when buffer is too small

This patch updates nvmet_bdev_zone_zmgmt_recv_work() in drivers/nvme/target/zns.c to fail Zone Management Receive commands with NVME_SC_INVALID_FIELD | NVME_STATUS_DNR when the Partial Report (PR) bit is clear and rz_data.nr_zones exceeds rz_data.out_nr_zones.

Quoted 13 lines
drivers/nvme/target/zns.c +3 -2
index 15a579cf528c1..dfa9269b59992 100644
@@ -299,11 +299,18 @@ static void nvmet_bdev_zone_zmgmt_recv_work(struct work_struct *w)
 	}
 
 	/*
-	 * When partial bit is set nr_zones must indicate the number of zone
-	 * descriptors actually transferred.
+	 * Partial report (PR bit set): the host accepts an incomplete listing,
+	 * so cap Number of Zones to the descriptors that fit in the buffer.
+	 * Full report (PR bit clear): Number of Zones is the match count; fail

drivers/nvme/target/zns.c static void nvmet_bdev_zone_zmgmt_recv_work(struct work_struct *w) · line 313

Quoted 10 lines
drivers/nvme/target/zns.c +7 -1
+	 * if the buffer cannot hold every matching zone descriptor.
 	 */
-	if (req->cmd->zmr.pr)
+	if (req->cmd->zmr.pr) {
 		rz_data.nr_zones = min(rz_data.nr_zones, rz_data.out_nr_zones);
+	} else if (rz_data.nr_zones > rz_data.out_nr_zones) {
+		req->error_loc = offsetof(struct nvme_zone_mgmt_recv_cmd, numd);
+		status = NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
+		goto out;
+	}

[Severity: High]
Won't rejecting req->cmd->zmr.pr == 0 commands when rz_data.nr_zones > rz_data.out_nr_zones break valid non-partial Zone Management Receive queries?

Per the NVMe Zoned Namespace Command Set specification (section 3.4.2), the Partial Report (PR) bit controls the value placed in the Number of Zones field of the 64-byte Report Zones header (struct nvme_zone_report):

- When PR is 0, Number of Zones indicates the total number of zones matching the ZRASF criteria from SLBA to the end of the namespace, regardless of the size of the data buffer, while only as many zone descriptors as fit in the buffer are transferred.

- When PR is 1, Number of Zones indicates the number of zone descriptors actually transferred in the buffer.

The only NUMD buffer size condition that aborts the command with Invalid Field in Command is when the buffer is smaller than the 64-byte Report Zones header itself, which nvmet_bdev_validate_zone_mgmt_recv() already checks:

drivers/nvme/target/zns.c:nvmet_bdev_validate_zone_mgmt_recv() {
	...
	if (out_bufsize < sizeof(struct nvme_zone_report)) {
		req->error_loc = offsetof(struct nvme_zone_mgmt_recv_cmd, numd);
		return NVME_SC_INVALID_FIELD | NVME_STATUS_DNR;
	}
	...
}

The existing helpers in drivers/nvme/target/zns.c are built around this behavior. In particular, get_nr_zones_from_buf() explicitly allows a 64-byte header-only buffer (returning out_nr_zones == 0) so an initiator can issue a PR=0 command to discover the total number of matching zones before allocating a full descriptor buffer:

drivers/nvme/target/zns.c:get_nr_zones_from_buf() {
	if (bufsize <= sizeof(struct nvme_zone_report))
		return 0;

	return (bufsize - sizeof(struct nvme_zone_report)) /
		sizeof(struct nvme_zone_descriptor);
}

And nvmet_bdev_report_zone_cb() copies descriptors into the host SGL only while rz->nr_zones < rz->out_nr_zones, yet continues incrementing rz->nr_zones across all remaining matching zones specifically to compute the total match count for PR=0:

drivers/nvme/target/zns.c:nvmet_bdev_report_zone_cb() {
	...
	if (rz->nr_zones < rz->out_nr_zones) {
		...
		status = nvmet_copy_to_sgl(rz->req, rz->out_buf_offset, &zdesc,
					   sizeof(zdesc));
		if (status)
			return -EINVAL;

		rz->out_buf_offset += sizeof(zdesc);
	}

	rz->nr_zones++;

	return 0;
}

With this new check in nvmet_bdev_zone_zmgmt_recv_work(), any 64-byte header-only PR=0 query (out_nr_zones == 0) fails with NVME_SC_INVALID_FIELD | NVME_STATUS_DNR whenever at least one zone matches, and any bounded-buffer PR=0 query fails after nvmet_bdev_report_zone_cb() has already written out_nr_zones descriptors into the host SGL.

Quoted 3 lines
drivers/nvme/target/zns.c +0 -0
 	nr_zones = cpu_to_le64(rz_data.nr_zones);
 	status = nvmet_copy_to_sgl(req, 0, &nr_zones, sizeof(nr_zones));
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author maintainer
#82 lore raw

PATCH 1/1 ASoC: SOF: Intel: mtl: Power down DSP if it is left enabled in pre_fw_run()

In reply to Sasha Levin

From: Peter Ujfalusi <[email protected]>

[ Upstream commit 31fd7a0bbfa4b7e8aff11f278e817664c6a5f68b ]

It is expected that the DSP is in power down state when the firmware boot is attempted.
If the DSP for any reason was left powered up then the DSP boot will fail since the ROM boot sequence might not be able to run.

Make sure that the DSP is off before proceeding to boot it up.

---

LLM Generated explanations, may be completely bogus:

Local tree is **6.1.188** (pending-6.1). The Meteor Lake SOF path this patch targets is present here, so the question is whether the DSP-left- on boot failure is worth a backport on this tree.

---

## PHASE 1: COMMIT MESSAGE FORENSICS

**Step 1.1: PARSE THE SUBJECT LINE**

Record: **[ASoC / SOF Intel MTL] [Power down] Ensure DSP is off before firmware boot in pre_fw_run()**

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

Record:
- Signed-off-by: Peter Ujfalusi <[email protected]> (author; Intel SOF)
- Reviewed-by: Bard Liao <[email protected]> (Intel SOF)
- Reviewed-by: Liam Girdwood <[email protected]> (ASoC/SOF maintainer)
- `Link: https://patch.msgid.link/20260730122857.5294-3-
[email protected]`
- Signed-off-by: Mark Brown <[email protected]> (ASoC maintainer, applied)
- No Fixes:, no Reported-by:, no Cc: stable (absence is expected for this review)
- Ignore any Signed-off-by: Sasha Levin / [Upstream commit ...] pipeline markers

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

Record:
- **Bug:** Firmware boot is assumed to start with the DSP powered down. If it is already up, the ROM boot sequence cannot run and DSP boot fails.
- **Symptom:** SOF firmware boot failure → no audio on Meteor Lake.
- **Cover letter (series 0/2, verified via b4):** “We have seen reports that for some undetermined reasons the DSP was on during system boot and this caused firmware boot failure as the DSP cannot be booted up - it was already in booted up state.”
- **Root cause:** DSP subsystem left powered (BIOS leftover, kexec, failed prior boot, etc.); pre_fw_run() only powers up, never powers down first.
- **Version info:** Applied by Mark Brown to for-7.3 (next merge window), not as a current-rc hotfix.

**Step 1.4: DETECT HIDDEN BUG FIXES**

Record: **Not a disguised cleanup.** Explicit hardware recovery: if CPA shows the DSP already on, power it down before the normal power-up sequence. This is a real functional fix.

---

## PHASE 2: DIFF ANALYSIS

**Step 2.1: INVENTORY THE CHANGES**

Record:
- File: sound/soc/sof/intel/mtl.c only
- ~23 lines added, 0 removed
- New: mtl_dsp_is_enabled()
- Modified: mtl_dsp_pre_fw_run() — extra check at the start
- **Scope:** single-file, surgical

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

Record:
- **Before:** mtl_dsp_pre_fw_run() always sets SPA to power the DSP subsystem on, waits, then powers the gated DSP domain. No check of current power state.
- **After:** Read MTL_HFDSSCS; if MTL_HFDSSCS_CPA_MASK is set, call existing mtl_power_down_dsp(). On failure, dev_warn and continue. Then the existing power-up sequence runs.
- **Path:** firmware boot (snd_sof_run_firmware()), probe and resume. The new code runs only when the DSP is already enabled.

**Step 2.3: IDENTIFY THE BUG MECHANISM**

Record:
- **Category:** hardware workaround / logic correctness (wrong assumed power state)
- **Mechanism:** ROM boot needs a cold/off DSP. CPA=1 means the subsystem is already on; setting SPA again does not run ROM init. Powering down first restores a clean boot state.
- Same idea as SKL’s existing hda_dsp_core_is_enabled() handling in hda-loader-skl.c (already in this tree).

**Step 2.4: ASSESS THE FIX QUALITY**

Record:
- **Quality:** Obviously correct. Uses existing mtl_power_down_dsp() and the same CPA bit already used for power-up poll.
- **Minimal:** one helper + one guarded call; normal path unchanged.
- **Regression risk:** Low. Clean suspend already calls power_down_dsp() (hda_suspend()), so IMR/resume should still see CPA=0. The new path only fires on the abnormal “already on” case. Power-down failure is warn-and-continue, not a hard fail.

---

## PHASE 3: GIT HISTORY INVESTIGATION

**Step 3.1: BLAME THE CHANGED LINES**

Record:
- mtl_dsp_pre_fw_run() introduced in 064520e8aeaa2 (“ASoC: SOF:
Intel: Add support for MeteorLake (MTL)”, Bard Liao, 2022-06-15) — **in this 6.1 tree**.
- mtl_power_down_dsp() added in 2090cb9bf5747 (2022-09-23) — **also in this tree** (git merge-base --is-ancestor confirmed).
- Buggy “power up without checking current state” has been here for the whole 6.1 lifetime of MTL.

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

Record: No Fixes: tag. Bug is the original MTL pre_fw_run() design, not a later regression.

**Step 3.3: CHECK FILE HISTORY**

Record: Recent local history is MTL bring-up/PM (064520e8aeaa2, 2090cb9bf5747, 6ae87bab269b3, timeout/dump tweaks). No existing “power down if already on” logic. Standalone vs CAVS: this is patch **2/2**; patch 1/2 is hda.c for older CAVS. MTL overrides .pre_fw_run with mtl_dsp_pre_fw_run, so **this commit does not depend on 1/2**.

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

Record: Peter Ujfalusi is an Intel SOF regular. Reviewers are Intel SOF (Bard Liao) and Liam Girdwood. High confidence in the hardware diagnosis.

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

Record:
- Needs mtl_power_down_dsp(), MTL_HFDSSCS, MTL_HFDSSCS_CPA_MASK — all present.
- Upstream context has later PTL/ACE 2.0 register selection (PTL_HFPWRCTL2, SOF_INTEL_ACE_2_0). **Those are context only, not this change.** 6.1 pre_fw_run() is the original MTL-only version.
- In 6.1 mtl_power_down_dsp() is static and defined **after** mtl_dsp_pre_fw_run() (line 401 vs 240). Upstream later made it a header prototype. Backport needs a **static forward declaration** (or a reorder). That is a trivial, mechanical adjustment, not a missing feature.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

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

Record:
- b4 dig -c 31fd7a0bbfa4 (hash from Mark Brown’s apply mail) matched patch-id.
- Thread: https://patch.msgid.link/20260730122857.5294-3-
[email protected]
- Cover: [PATCH 0/2] ASoC: SOF: Intel: hda/mtl: Handle powered on DSP on boot
- Full thread saved via b4 mbox (4 messages): cover, 1/2 hda, 2/2 mtl, Mark Brown apply.
- **v1 only** (b4 dig -a); no v2/v3.
- **No NAKs.** Applied to https://git.kernel.org/broonie/sound for-7.3 as 31fd7a0bbfa4.
- No reviewer Cc: stable in the thread.

**Step 4.2: CHECK WHO REVIEWED**

Record (b4 dig -w): To/Cc were Liam Girdwood, Mark Brown, linux-sound, Kai Vehmanen, Bard Liao, Pierre-Louis Bossart. Right maintainers. Reviewed-by from Bard Liao and Liam Girdwood.

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

Record: No public bugzilla/syzbot link. Evidence is the cover letter:
Intel has reports of DSP-on-at-boot causing firmware boot failure. Severity from reporters: **audio DSP does not boot**. User count:
unspecified (“reports”), not a single anecdotal one-off in the message, but not named either.

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

Record: Series is 2 independent platform hooks (hda CAVS vs mtl ACE). This MTL patch is self-contained. No later follow-up found in the thread.

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

Record: lore.kernel.org/stable WebFetch returned 403. Web search found no stable-list discussion of this subject. **UNVERIFIED:** no evidence it was requested or rejected for stable.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

**Step 5.1: IDENTIFY KEY FUNCTIONS**

Record: mtl_dsp_is_enabled() (new), mtl_dsp_pre_fw_run() (modified), mtl_power_down_dsp() (callee, unchanged).

**Step 5.2: TRACE CALLERS**

Record:
- sof_mtl_ops.pre_fw_run = mtl_dsp_pre_fw_run (sof_mtl_ops_init)
- snd_sof_dsp_pre_fw_run() → snd_sof_run_firmware() (sound/soc/sof/loader.c)
- snd_sof_run_firmware() from probe (sound/soc/sof/core.c) and resume (sound/soc/sof/pm.c)

**Step 5.3: TRACE CALLEES**

Record: snd_sof_dsp_read() (CPA), mtl_power_down_dsp() → mtl_dsp_core_power_down() then clear SPA and poll CPA=0. Same sequence already used on suspend/remove.

**Step 5.4: FOLLOW THE CALL CHAIN**

Record: Probe of sof-audio-pci-intel-mtl (PCI 8086:7e28) → load firmware → pre_fw_run → ROM boot. **Reachable on every MTL SOF boot**, not a debug-only path. Unprivileged users do not trigger it directly; it runs at device probe/resume.

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**

Record: SKL loader already handles “core already enabled” (hda-loader- skl.c). CAVS sibling is series 1/2. MTL/ACE had a gap this commit fills.

---

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

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

Record: **Yes.** sound/soc/sof/intel/mtl.c mtl_dsp_pre_fw_run() (from ~line 240) powers on with no prior CPA check. Introduced with MTL in v6.1 (064520e8aeaa2). PCI ID and CONFIG_SND_SOC_SOF_METEORLAKE exist. Local make kernelversion: **6.1.188**.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**

Record: **Minor conflicts, not rework.**
- Upstream hunk context includes later mtl_enable_interrupts(..., bool enable), EXPORT_SYMBOL_NS, PTL dsppwrctl/chip->hw_ip_version — **not in 6.1**.
- Logical change still maps 1:1 onto 6.1 pre_fw_run().
- Need a forward declaration of static mtl_power_down_dsp().

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

Record: No local commit with this subject or “power down if left enabled” on mtl.c. Not already fixed.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

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

Record: **ASoC SOF Intel Meteor Lake** (sound/soc/sof/intel/mtl.c). **IMPORTANT** for MTL laptops/desktops using SOF (not core mm/net). Peripheral relative to the whole kernel, but this is the Intel audio DSP path for that generation.

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**

Record: MTL was added during 6.1 development and then mostly stable on this branch (timeouts, dumps, PM ops). Mature for 6.1, not a brand-new post-branch subsystem.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

**Step 8.1: DETERMINE WHO IS AFFECTED**

Record: **Driver-specific** — CONFIG_SND_SOC_SOF_METEORLAKE, PCI 8086:7e28. 6.1 LTS users on Meteor Lake (e.g. Debian bookworm-class kernels on Core Ultra hardware).

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**

Record: DSP already powered when pre_fw_run() runs (BIOS, kexec, leftover from a failed boot). Not every boot. Not userspace-triggerable as a security issue. Intel reports it on **system boot**.

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

Record: SOF firmware boot failure → **no audio**. Not a panic/UAF/corruption. **HIGH for affected hardware** (device does not work), **MEDIUM** in whole-tree terms.

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

Record:
- **Benefit:** MTL machines that otherwise fail DSP boot get working audio. Matches the hardware-quirk exception.
- **Risk:** Low — ~20 lines, gated on CPA, uses existing power-down, warn-and-continue on failure, suspend already powers down so IMR resume should be unaffected.
- **Ratio:** Favorable for this tree.

---

## PHASE 9: FINAL SYNTHESIS

**Step 9.1: COMPILE THE EVIDENCE**

**FOR:**
- Real, reported firmware-boot failure when DSP is already on
- User-visible: no audio
- Small, obviously correct, Intel-reviewed
- Buggy code and mtl_power_down_dsp() both exist in 6.1
- Hardware workaround class (explicitly stable-appropriate)
- Standalone from series 1/2
- Normal boot/resume unchanged

**AGAINST:**
- Not a crash/security/corruption/deadlock
- Trigger is uncommon / “undetermined”
- Applied to for-7.3, not sent as -rc
- Needs a small backport (context + forward declaration)

**UNRESOLVED:**
- Stable list discussion (lore/stable 403)
- Exact BIOS/platforms in the unnamed reports

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

1. Obviously correct and tested? **PASS** — Intel review; uses existing power-down + CPA
2. Fixes a real bug that affects users? **PASS** — reported DSP-on-at- boot, firmware boot fail
3. Important issue? **PASS** — audio device fails to initialize (hardware-workaround class)
4. Small and contained? **PASS** — one file, ~23 lines
5. No new features or APIs? **PASS**
6. Can apply to the local tree? **PASS** — logic applies; minor context/prototype adaptation

**Step 9.3: CHECK FOR EXCEPTION CATEGORIES**

Record: **Hardware quirk/workaround** — force a known-good DSP power state before ROM boot, analogous to USB/PCI reset-on-init quirks.

**Step 9.4: DECISION**

This is a small recovery for a real MTL SOF boot failure that exists in 6.1. The bug is “DSP already on → firmware never boots,” not a theoretical cleanup. Risk is low because the new code only runs when CPA is already set, and that path already exists for suspend/remove. It should be backported to this tree.

---

### What the commit solves for stable users

On Meteor Lake, SOF expects the DSP subsystem off before ROM boot. If it is already on, pre_fw_run() still only sets SPA; ROM init does not run and probe/resume fails with no audio. The fix reads CPA and, if set, calls the existing mtl_power_down_dsp() so the following power-up is a clean boot.

### Stable rules / risk

Meets the rules: real bug, small, no new API, hardware workaround. Benefit is working audio on affected MTL systems; regression risk is low.

### Concerns

Literal git am will not apply (later PTL/bool enable context). A 6.1 backport is the same helper + call, plus a static forward declaration of mtl_power_down_dsp(). Series 1/2 (hda.c) is not required for this MTL change.

---

### Verification

- **[Phase 1]** Parsed tags from the provided message and the b4 mbox:
author Peter Ujfalusi; Reviewed-by Bard Liao, Liam Girdwood; applied by Mark Brown; no Fixes/Reported-by/Cc: stable
- **[Phase 1]** Cover letter (mbox): Intel reports of DSP-on-at-boot causing firmware boot failure
- **[Phase 2]** Diff: +23 lines in mtl.c; mtl_dsp_is_enabled() + guarded mtl_power_down_dsp() in mtl_dsp_pre_fw_run()
- **[Phase 3]** git describe HEAD / make kernelversion: p-6.1-12 / **6.1.188**
- **[Phase 3]** git merge-base --is-ancestor 064520e8aeaa2 HEAD: MTL support present
- **[Phase 3]** git merge-base --is-ancestor 2090cb9bf5747 HEAD:
mtl_power_down_dsp present
- **[Phase 3]** git blame -L 240,284 sound/soc/sof/intel/mtl.c:
pre_fw_run still original 064520e8aeaa2; no CPA-down check
- **[Phase 3]** Confirmed MTL_HFDSSCS / MTL_HFDSSCS_CPA_MASK in mtl.h
- **[Phase 3]** Function order: mtl_dsp_pre_fw_run @240, mtl_power_down_dsp @401 (forward decl needed)
- **[Phase 4]** b4 mbox of 20260730122857.5294-3: cover + 1/2 + 2/2 + apply; no NAK
- **[Phase 4]** b4 dig -c 31fd7a0bbfa4: lore match; v1 only; applied to for-7.3 as 31fd7a0bbfa4
- **[Phase 4]** b4 dig -w: maintainers CC’d
- **[Phase 4]** lore.kernel.org WebFetch: 403
- **[Phase 5]** Callers: snd_sof_run_firmware ← probe (core.c) and resume (pm.c)
- **[Phase 5]** hda_suspend() already calls chip->power_down_dsp() — clean resume should have CPA=0
- **[Phase 5]** SKL already has similar “if core enabled” handling in hda-loader-skl.c
- **[Phase 6]** pci-mtl.c PCI ID 8086:7e28; CONFIG_SND_SOC_SOF_METEORLAKE in Kconfig
- **[Phase 6]** MTL overrides .pre_fw_run; series 1/2 not a dependency
- **[Phase 8]** Failure: SOF firmware boot fail / no audio, not oops
- **UNVERIFIED:** stable@ discussion (HTTP 403); named reporters/machines

**YES**

 sound/soc/sof/intel/mtl.c | 23 +++++++++++++++++++++++
 1 file changed, 23 insertions(+)
sound/soc/sof/intel/mtl.c +23 -0
index 2242c96bfa519..f119e0e0651a2 100644
@@ -236,6 +236,17 @@ int mtl_enable_interrupts(struct snd_sof_dev *sdev, bool enable)
 }
 EXPORT_SYMBOL_NS(mtl_enable_interrupts, "SND_SOC_SOF_INTEL_MTL");
 
+static bool mtl_dsp_is_enabled(struct snd_sof_dev *sdev)
+{
+	int val;
+
+	val = snd_sof_dsp_read(sdev, HDA_DSP_BAR, MTL_HFDSSCS);
+	if (val & MTL_HFDSSCS_CPA_MASK)
+		return true;
+
+	return false;
+}
+
 /* pre fw run operations */
 static int mtl_dsp_pre_fw_run(struct snd_sof_dev *sdev)
 {
@@ -249,6 +260,18 @@ static int mtl_dsp_pre_fw_run(struct snd_sof_dev *sdev)
 	u32 dsppwrsts;
 	const struct sof_intel_dsp_desc *chip;
 
+	/* Power down the DSP if it is left enabled to ensure clean boot state */
+	if (mtl_dsp_is_enabled(sdev)) {
+		dev_dbg(sdev->dev, "powering down DSP first\n");
+
+		ret = mtl_power_down_dsp(sdev);
+		if (ret < 0) {
+			dev_warn(sdev->dev,
+				 "%s: failed to power down already-enabled DSP\n", __func__);
+			/* Continue anyway to attempt recovery */
+		}
+	}
+
 	chip = get_chip_info(sdev->pdata);
 	if (chip->hw_ip_version > SOF_INTEL_ACE_2_0) {
 		dsppwrctl = PTL_HFPWRCTL2;
Signature · 1 line
2.53.0
author maintainer
#83 lore raw

PATCH 1/1 iommu/qcom: Publish pgtbl_ops before releasing init_mutex

In reply to Sasha Levin

From: Mukesh Ojha <[email protected]>

[ Upstream commit a05b67cd45ad09a19f41b2d37255da714512e0ca ]

qcom_domain->pgtbl_ops was assigned after mutex_unlock(). Another thread calling qcom_iommu_init_domain() would see qcom_domain->iommu already set (domain fully initialized) and skip re-initialization under the mutex. If it then called qcom_iommu_map() before the first thread set pgtbl_ops, it would observe a NULL ops pointer and return -ENODEV for valid mappings.

Move the assignment to before mutex_unlock() so that once the mutex is released the domain is fully visible to concurrent operations.

---

LLM Generated explanations, may be completely bogus:

The local tree is **7.3-rc4** (mainline). The driver is present, the race is real, and the fix is a five-line lock-ordering correction. Below is the full nine-phase review.

---

## PHASE 1: COMMIT MESSAGE FORENSICS

**Step 1.1: PARSE THE SUBJECT LINE**
Record: [iommu/qcom] [Publish] Publish pgtbl_ops before releasing init_mutex
Subsystem: Qualcomm IOMMU (drivers/iommu/arm/arm-smmu/qcom_iommu.c). Verb “Publish … before” is a visibility/ordering fix (equivalent to “ensure” / “prevent”).

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**
Record:
- Reviewed-by: Konrad Dybcio <[email protected]>
- Signed-off-by: Mukesh Ojha <[email protected]> (author)
- Signed-off-by: Will Deacon <[email protected]> (IOMMU/SMMU maintainer)
- No Fixes:, Reported-by:, Tested-by:, Link:, or Cc: stable (absence expected; not a negative)

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**
Record:
- **Bug:** qcom_domain->pgtbl_ops was stored after mutex_unlock(&init_mutex).
- **Symptom:** A concurrent qcom_iommu_init_domain() sees qcom_domain->iommu already set, skips init, then qcom_iommu_map() reads a NULL ops pointer and returns -ENODEV for valid mappings.
- **Root cause:** The “domain initialized” flag (iommu) is published under the mutex; page-table ops are published after the mutex is dropped, so the domain is only half-visible.
- **Version info:** None in the message. Blame shows the unlock-then- assign pattern dates to the original driver (2017).

**Step 1.4: DETECT HIDDEN BUG FIXES**
Record: Not disguised. Explicit race with a concrete failure (-ENODEV on map). Not cleanup/refactor.

---

## PHASE 2: DIFF ANALYSIS

**Step 2.1: INVENTORY THE CHANGES**
Record:
- File: drivers/iommu/arm/arm-smmu/qcom_iommu.c — 2 insertions, 3 deletions
- Function: qcom_iommu_init_domain()
- Scope: single-file surgical reorder of three statements

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**
Record:
**Before:** program context banks → mutex_unlock(init_mutex) → pgtbl_ops = … → return 0.
**After:** program context banks → pgtbl_ops = … → mutex_unlock(init_mutex) → return 0.
Error paths (out_clear_iommu / out_unlock) are unchanged. This is the success-path publication of domain state.

**Step 2.3: IDENTIFY THE BUG MECHANISM**
Record: **[Synchronization / race]**.
qcom_domain->iommu is set near the start of init (under the mutex) and is the “already initialized” flag:

```227:229:drivers/iommu/arm/arm-smmu/qcom_iommu.c
        mutex_lock(&qcom_domain->init_mutex);
        if (qcom_domain->iommu)
                goto out_unlock;
```

qcom_iommu_map() does not take init_mutex; it only checks pgtbl_ops:

```436:439:drivers/iommu/arm/arm-smmu/qcom_iommu.c
        struct io_pgtable_ops *ops = qcom_domain->pgtbl_ops;

        if (!ops)
                return -ENODEV;
```

Unlocking before the store lets another attach skip init and then map with a NULL ops pointer. The fix publishes ops while still holding the mutex so that once waiters proceed, the domain is fully usable.

**Step 2.4: ASSESS THE FIX QUALITY**
Record: Obviously correct publish-under-lock. Minimal. No new locks, APIs, or control flow besides statement order. Regression risk is very
low: the assignment is a plain pointer store of a fully constructed object; holding the mutex a few extra instructions does not create deadlock (map/unmap use pgtbl_lock, not init_mutex).

---

## PHASE 3: GIT HISTORY INVESTIGATION

**Step 3.1: BLAME THE CHANGED LINES**
Record: Unlock-then-assign was introduced in 0ae349a0f33fb (“iommu/qcom: Add qcom_iommu”, Rob Clark, 2017-08-09), first in **v4.14-rc1**. The bug is ~9 years old in this driver, not a recent regression.

**Step 3.2: FOLLOW THE FIXES: TAG**
Record: No Fixes: tag. Buggy code is the original 2017 driver, which is an ancestor of this tree.

**Step 3.3: CHECK FILE HISTORY**
Record: Same-day series from Mukesh Ojha (applied 2026-07-22 by Will Deacon):
- 3c748a5554f96 — leak of pgtbl_ops on error (patch 4/6)
- a05b67cd45ad0 — this commit (patch 5/6)
- cb776a03a5342 — clocks before ctx probe (patch 6/6)

This patch only reorders unlock vs assignment. It does **not** depend on the leak fix.

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**
Record: Mukesh Ojha (Qualcomm) submitted a “Misc Fixes” series for the legacy qcom_iommu driver. Not the IOMMU subsystem maintainer; Will Deacon applied it. Konrad Dybcio (Qualcomm) reviewed.

**Step 3.5: DEPENDENT/PREREQUISITE COMMITS**
Record: Standalone. v2 series is 6 patches; this one has no code dependency on the others. Can apply alone.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**
Record:
- Lore (from b4 dig -c a05b67cd45ad0): https://patch.msgid.link/202607
[email protected]
- **v1:** [PATCH 5/8] 2026-06-23 — https://patch.msgid.link/2026062312
[email protected]
- **v2:** [PATCH v2 5/6] 2026-07-17 (applied version; same diff as v1 for this patch)
- Konrad on v1: Reviewed-by plus a non-blocking note that a guard(mutex) wrapper would also work. No NAK.
- Will Deacon applied the whole v2 series to iommu (arm/smmu/updates) on 2026-07-22. No stable nomination, no risk flags.

**Step 4.2: CHECK WHO REVIEWED THE PATCH**
Record (b4 dig -w): Mukesh Ojha, Rob Clark, Will Deacon, Joerg Roedel, Alex Williamson, Robin Murphy, Konrad Dybcio; lists [email protected], linux-arm-msm, linux-arm-kernel. Appropriate maintainers were on Cc. Konrad reviewed; Will applied.

**Step 4.3: SEARCH FOR THE BUG REPORT**
Record: No Reported-by, syzbot, or bugzilla. Author analysis only. UNVERIFIED whether anyone hit this in the field.

**Step 4.4: RELATED PATCHES AND SERIES**
Record: Part of “iommu/qcom: Misc Fixes”. Other patches (fault-log polarity, pm_runtime, leak, clocks) are independent. v1 patches 6/8 and 8/8 were dropped after review; this patch was unchanged.

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**
Record: lore.kernel.org/stable search for pgtbl_ops qcom did not show this patch. Hits were unrelated (arm-smmu-qcom power-up). No evidence it was rejected for stable.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

**Step 5.1: KEY FUNCTIONS**
Record: qcom_iommu_init_domain() (modified). Related:
qcom_iommu_attach_dev(), qcom_iommu_map(), qcom_iommu_unmap(), qcom_iommu_iova_to_phys().

**Step 5.2: TRACE CALLERS**
Record:
- qcom_iommu_init_domain() is only called from qcom_iommu_attach_dev().
- attach_dev is the IOMMU .attach_dev op (qcom_iommu_ops.default_domain_ops).
- Core path: __iommu_attach_device() → domain->ops->attach_dev().
- This driver select ARM_DMA_USE_IOMMU. arm_iommu_attach_device() documents that more than one client may share a mapping, and calls iommu_attach_device(). Parallel probe of two devices sharing a mapping is a realistic concurrent init_domain on the same qcom_domain. Group mutex serializes attach **within** a group; generic_device_group means one device per group, so two devices are two groups and are **not** serialized against each other.

**Step 5.3: TRACE CALLEES**
Record: alloc_io_pgtable_ops(), qcom_scm_restore_sec_cfg(), context- bank MMIO, mutex_lock/unlock. SCM and register programming make the critical section long; waiters pile up on init_mutex and then race the post-unlock store.

**Step 5.4: FOLLOW THE CALL CHAIN**
Record: Reachable from device probe / DMA attach on Qualcomm “B family” SMMU platforms (MSM8916/8937/8939/8953/8976, etc.). Not a syscall fuzzer path; it is a normal boot/probe path. Userspace-triggered concurrent attach is also possible via the ARM DMA mapping API / VFIO-style attach of separate groups to one domain.

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**
Record: init_mutex comment is “Protects iommu pointer” — the original code treated iommu as the publication point and left pgtbl_ops outside the lock. No sibling qcom function has the same bug. map/unmap/iova_to_phys all NULL-check pgtbl_ops and return -ENODEV/0 rather than crashing — so the race fails mappings instead of oopsing.

semcode MCP: not available; used git grep and reads.

---

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

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?** Record:
- Tree: v7.3-rc4-27-gf0100363d8c37, make kernelversion = **7.3.0-rc4**.
- File exists at drivers/iommu/arm/arm-smmu/qcom_iommu.c.
- git merge-base --is-ancestor a05b67cd45ad0 HEAD succeeds: this commit is already in this checkout (landed as v7.2-rc2-7-ga05b67cd45ad0).
- Pre-fix code existed here from v4.14 until that commit. The race is in this driver’s design, not in code added after this tree branched.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**
Record: Five-line reorder around a pattern present since 2017. File moved in e86d1aa8b60f7 (v5.8) from drivers/iommu/qcom_iommu.c; this tree already uses the new path. Expected apply: **clean**. No conflicting churn around the unlock.

**Step 6.3: RELATED FIXES ALREADY HERE**
Record: The leak fix 3c748a5554f96 is also here and is independent. No alternate fix for this race.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

**Step 7.1: SUBSYSTEM AND CRITICALITY**
Record: [iommu / Qualcomm legacy SMMU] [IMPORTANT]
Not mm/core, but IOMMU DMA for a family of Qualcomm SoCs still in DT (phones, Dragonboard-class boards, embedded). Mapping failures break DMA for those devices.

**Step 7.2: SUBSYSTEM ACTIVITY**
Record: Legacy driver (“Misc Fixes” cover letter). Recent Qualcomm fixes; not a new subsystem. Mature code, long-present bug.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

**Step 8.1: WHO IS AFFECTED**
Record: **driver-specific / config-specific** — CONFIG_QCOM_IOMMU on ARCH_QCOM (MSM8916, MSM8937, MSM8939, MSM8953, MSM8976, …). Not universal.

**Step 8.2: TRIGGER CONDITIONS**
Record: Two threads attaching the same qcom_iommu_domain (shared ARM DMA mapping, or two groups attached to one domain). After the first drops init_mutex and before it stores pgtbl_ops, the second skips init and maps. Window is a few instructions, but **preemption after unlock** makes it realistic; SCM-held init also means waiters are ready to run immediately. Not triggerable by an unprivileged syscall alone in the usual case; it is a probe/attach race. No field Reported-by (UNVERIFIED in production).

**Step 8.3: FAILURE MODE SEVERITY**
Record: **Failed IOMMU map (-ENODEV) for valid mappings** → DMA setup failure / device non-functional. Not a KASAN UAF or panic (map NULL- checks). **Severity: HIGH** (device DMA broken), not CRITICAL (no oops/corruption).

**Step 8.4: RISK-BENEFIT RATIO**
Record:
- **Benefit:** Prevents a real attach/map race on Qualcomm IOMMU; devices keep working under concurrent attach.
- **Risk:** Very low (3-statement reorder, no API/locking change).
- **Ratio:** Favorable.

---

## PHASE 9: FINAL SYNTHESIS

**Step 9.1: COMPILE THE EVIDENCE**

**FOR:**
- Real race: initialized flag published under lock, ops pointer published after unlock.
- User-visible failure: valid maps return -ENODEV (DMA/device failure).
- Bug in the driver since v4.14; this tree’s driver still has that design.
- 5-line, obviously correct publish-under-lock.
- Reviewed by Konrad Dybcio; applied by Will Deacon.
- Self-contained; not a new feature.
- Used on real Qualcomm SoCs that still ship on LTS-class kernels.

**AGAINST:**
- No Reported-by / syzbot / crash log.
- Window is small; needs concurrent attach to the **same** domain.
- Failure is -ENODEV, not oops/UAF/corruption.
- Cover letter calls the series “Misc Fixes”; nobody Cc’d stable.
- Peripheral vs core (legacy qcom_iommu, not arm-smmu-v3).

**UNRESOLVED:**
- No confirmed production hit.
- lore.kernel.org HTML fetch returned 403; discussion recovered via b4 dig/b4 mbox.
- How often qcom platforms share one dma_iommu_mapping across devices is not fully quantified; the ARM DMA API and init_mutex exist specifically for that case.

**Step 9.2: STABLE RULES CHECKLIST**
1. Obviously correct and tested? **PASS** — reorder is locally checkable; Konrad R-b; Will applied; in mainline since v7.2-rc2.
2. Fixes a real bug that affects users? **PASS** — concurrent attach can fail valid DMA maps.
3. Important issue? **PASS** — DMA map failure can take devices out; not a panic, but not cosmetic.
4. Small and contained? **PASS** — 5 lines, one function.
5. No new features or APIs? **PASS**.
6. Can apply to the local tree? **PASS** — same file/function; already the current code here.

**Step 9.3: EXCEPTION CATEGORIES**
Record: None (not a device-ID/quirk/DT/build/doc exception). It is a normal small race fix.

**Step 9.4: DECISION**

This tree is **7.3-rc4**. The Qualcomm IOMMU driver is here, and the race is in the original 2017 init/map split, not in later architecture. The patch is a correct, tiny publication-order fix: once init_mutex is dropped, pgtbl_ops must already be visible so a concurrent attach cannot skip init and then fail qcom_iommu_map().

It meets stable rules: real bug, user-visible DMA failure, surgical change, no new API, no prerequisites. Benefit outweighs the tiny race window and lack of a field report.

---

## Verification
- [Phase 1] Parsed tags: Reviewed-by Konrad Dybcio; SOB Mukesh Ojha + Will Deacon; no Fixes/Reported-by/Cc-stable
- [Phase 2] Diff: 2+/3- in qcom_iommu_init_domain(); move pgtbl_ops store before mutex_unlock
- [Phase 2] Confirmed map() NULL-checks ops and returns -ENODEV; init_domain early-outs on qcom_domain->iommu
- [Phase 3] git blame: unlock-then-assign from 0ae349a0f33fb (v4.14-rc1, Rob Clark)
- [Phase 3] No Fixes tag; leak fix 3c748a5554f96 is independent
- [Phase 3] git merge-base --is-ancestor a05b67cd45ad0 HEAD → yes (already in this 7.3-rc4 checkout)
- [Phase 3] git describe a05b67cd45ad0 → v7.2-rc2-7-ga05b67cd45ad0
- [Phase 4] b4 dig -c a05b67cd45ad0: v2 5/6 at patch.msgid.link/20260717144608.3216274-6-…
- [Phase 4] b4 dig -a: v1 5/8 (2026-06-23) → v2 5/6 (2026-07-17); this hunk unchanged
- [Phase 4] b4 dig -w: iommu maintainers + linux-arm-msm Cc’d
- [Phase 4] Konrad v1 review: R-b; optional guard(mutex) suggestion only; Will applied v2
- [Phase 4] lore.kernel.org WebFetch 403; used b4 mbox instead
- [Phase 4] stable@ search: this commit not discussed; unrelated arm- smmu-qcom hits
- [Phase 5] Callers: only qcom_iommu_attach_dev ← IOMMU .attach_dev ← __iommu_attach_device
- [Phase 5] ARM_DMA_USE_IOMMU / arm_iommu_attach_device() allows shared mappings across devices
- [Phase 5] semcode unavailable; used git grep + file reads
- [Phase 6] git describe HEAD = v7.3-rc4-27-gf0100363d8c37; make kernelversion = 7.3.0-rc4
- [Phase 6] Current file already has assignment before unlock (this commit)
- [Phase 7] DT: msm8916/8937/8939/8953/8976 use qcom,msm-iommu-v1/v2
- [Phase 8] Failure: -ENODEV on valid map, severity HIGH; not oops
- UNVERIFIED: production reproduction; exact share-mapping frequency on qcom boards

The fix is small, surgical, and meets the stable criteria for this tree’s Qualcomm IOMMU driver.

**YES**

 drivers/iommu/arm/arm-smmu/qcom_iommu.c | 5 ++---
 1 file changed, 2 insertions(+), 3 deletions(-)
drivers/iommu/arm/arm-smmu/qcom_iommu.c +2 -3
index 792585321bd11..1a046122fca0d 100644
@@ -306,13 +306,12 @@ static int qcom_iommu_init_domain(struct iommu_domain *domain,
 		ctx->domain = domain;
 	}
 
-	mutex_unlock(&qcom_domain->init_mutex);
-
 	/* Publish page table ops for map/unmap */
 	qcom_domain->pgtbl_ops = pgtbl_ops;
 
-	return 0;
+	mutex_unlock(&qcom_domain->init_mutex);
 
+	return 0;
 out_clear_iommu:
 	qcom_domain->iommu = NULL;
 out_unlock:
Signature · 1 line
2.53.0
author maintainer
#84 lore raw

PATCH 1/1 pinctrl: npcm8xx: move GPIO IRQ setup into request_resources

In reply to Sasha Levin

From: Tomer Maimon <[email protected]>

[ Upstream commit b8edfde12e355030e708394c0fa11632559c7ac5 ]

npcmgpio_irq_startup() calls pinctrl_gpio_direction_input(), which may sleep while taking the pinctrl core mutex. That makes IRQ startup trip lockdep when CONFIG_PROVE_LOCKING is enabled.

Move the direction change into irq_request_resources() and keep startup limited to the ack and unmask operations that are safe in atomic context.

---

LLM Generated explanations, may be completely bogus:

The local tree is **v7.3-rc4** (7.3.0-rc4). The NPCM8XX pinctrl driver is present, and this change is a real sleep-in-atomic IRQ fix, not a feature add.

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

Step 1.1: PARSE THE SUBJECT LINE
Record: **[pinctrl/npcm8xx] [move] move GPIO IRQ setup into request_resources**
Subsystem pinctrl: npcm8xx. Verb is “move”, but the body is a correctness fix: take a may-sleep call out of irq_startup.

Step 1.2: PARSE ALL COMMIT MESSAGE TAGS
Record:
- Signed-off-by: Tomer Maimon <[email protected]> (author; NPCM maintainer)
- Signed-off-by: Linus Walleij <[email protected]> (pinctrl 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 and is not a negative signal.

Step 1.3: ANALYZE THE COMMIT BODY TEXT
Record:
- Bug: npcmgpio_irq_startup() calls pinctrl_gpio_direction_input(), which takes the pinctrl mutex and may sleep.
- Symptom: lockdep splat with CONFIG_PROVE_LOCKING on IRQ startup.
- Root cause: IRQ startup runs in atomic context; mutex_lock there is illegal.
- Fix: do the direction change in irq_request_resources(); leave startup as ack+unmask only.
- No version range, stack trace, or reproducer in the message.

Step 1.4: DETECT HIDDEN BUG FIXES
Record: Not a hidden fix. It is an explicit locking/context bug. Cover letter of the v1 series called the set a “cleanup” from a Nuvoton tree comparison, but this patch itself describes a real sleep-in-atomic problem.

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

Step 2.1: INVENTORY THE CHANGES
Record:
- File: drivers/pinctrl/nuvoton/pinctrl-npcm8xx.c (+23 / -6, 29 lines)
- Functions: npcmgpio_irq_startup (changed), npcmgpio_irq_request_resources (added), npcmgpio_irq_release_resources (added), npcmgpio_irqchip (changed)
- Scope: single-file surgical irqchip callback change

Step 2.2: UNDERSTAND THE CODE FLOW CHANGE
Record:
- Before: irq_startup called npcmgpio_direction_input() then ack/unmask. Resource helpers came from GPIOCHIP_IRQ_RESOURCE_HELPERS (gpiochip_irq_reqres / gpiochip_irq_relres).
- After: irq_startup only ack+unmask. New irq_request_resources does npcmgpio_direction_input() then gpiochip_reqres_irq(). New irq_release_resources calls gpiochip_relres_irq(). Macro helpers removed because custom callbacks replace them.
- Path: GPIO request_irq() setup, not a probe-only path.

Step 2.3: IDENTIFY THE BUG MECHANISM
Record: **Synchronization / illegal sleep in atomic context** irq_startup() is invoked from __setup_irq() while desc->lock is held via raw_spin_lock_irqsave() (kernel/irq/manage.c: lock at 1589, irq_startup() at 1766, unlock at 1807). pinctrl_gpio_direction_input() takes pinctrldev_list_mutex and pctldev->mutex (drivers/pinctrl/core.c). Mutex in that context is sleep-in-atomic. irq_request_resources() runs before that spinlock and is allowed to sleep.

Step 2.4: ASSESS THE FIX QUALITY
Record: Quality is high. Same pattern as pinctrl-ingenic.c and pinctrl-st.c. Resource get/put is preserved. Direction-input errors are now returned instead of ignored. Regression risk is low: startup no longer re-applies input on later startups, which matches other drivers; first request_irq() still sets input before unmask. No API or data- structure change.

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

Step 3.1: BLAME THE CHANGED LINES
Record: Buggy npcmgpio_irq_startup() / GPIOCHIP_IRQ_RESOURCE_HELPERS came from acf4884a571709 (“pinctrl: nuvoton: add NPCM8XX pinctrl and GPIO driver”, 2023-08-28), first in **v6.7-rc1**. The bug is as old as the driver.

Step 3.2: FOLLOW THE FIXES: TAG
Record: No Fixes: tag. Introducer is the original driver commit above. git merge-base --is-ancestor acf4884a571709 HEAD is true in this tree.

Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES
Record: Submitted as **[PATCH v1 6/8]** “pinctrl: npcm8xx: fix pinmuxing and configuration handling”. Siblings (bmcuart1 pins, RMII, RG2 drive strength, event clear, rename, JM1/SMB7 flags, debounce) do not change the irqchip callbacks this patch needs. Standalone. No follow-up on these IRQ helpers after this commit.

Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS
Record: Tomer Maimon is listed under ARM/NUVOTON NPCM ARCHITECTURE in MAINTAINERS. Recent npcm8xx work is this same 8-patch set plus earlier pin-table updates. Maintainer-authored.

Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS
Record: Needs existing gpiochip_reqres_irq / gpiochip_relres_irq and GPIOCHIP_IRQ_RESOURCE_HELPERS, both present here. No series prerequisite for this hunk. Can apply standalone to this driver.

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

Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION
Record: b4 dig -c b8edfde12e355 →
https://patch.msgid.link/[email protected]
Only **v1**. Lore HTTP fetch returned 403; full thread was saved with b4 dig -m. Linus Walleij (24 Jul 2026): “No comments so patches applied.” No NAK, no stable nomination, no requested respin.

Step 4.2: CHECK WHO REVIEWED THE PATCH
Record: b4 dig -w To/Cc: Tomer Maimon, Andrew Jeffery, Linus Walleij, Bartosz Golaszewski, openbmc, linux-gpio, linux-kernel, Avi Fishman, Tali Perry, Patrick Venture, Nancy Yuen, Benjamin Fair. Right lists and maintainers. Only explicit reply is Walleij applying the series.

Step 4.3: SEARCH FOR THE BUG REPORT
Record: No Reported-by, syzbot, or bugzilla. Issue was found by comparing upstream with Nuvoton’s tree. Symptom claimed is lockdep with CONFIG_PROVE_LOCKING. No public user crash report found.

Step 4.4: CHECK FOR RELATED PATCHES AND SERIES
Record: 8-patch pinmux/config series. This IRQ move does not depend on the others. npcm7xx still calls npcmgpio_direction_input() from irq_startup() — same class of bug, different driver, not a dependency.

Step 4.5: CHECK STABLE MAILING LIST HISTORY
Record: lore.kernel.org/stable search via curl returned 403. UNVERIFIED whether stable@ already discussed this. No evidence in the gpio thread of a stable NAK.

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

Step 5.1: IDENTIFY KEY FUNCTIONS IN THE DIFF
Record: npcmgpio_irq_startup, npcmgpio_irq_request_resources, npcmgpio_irq_release_resources, plus npcmgpio_irqchip initializer.

Step 5.2: TRACE CALLERS
Record:
- irqchip ops invoked from IRQ core: irq_request_resources() / irq_release_resources() / irq_startup() in kernel/irq/manage.c and kernel/irq/chip.c
- Chip registered in npcm8xx_gpio_register() via girq->chip
- Reachable from request_irq() / gpiod_to_irq() users on NPCM8XX GPIO banks

Step 5.3: TRACE CALLEES
Record: npcmgpio_direction_input → pinctrl_gpio_direction_input (mutex) + generic bank->direction_input; npcmgpio_irq_ack / unmask (MMIO); gpiochip_reqres_irq / gpiochip_relres_irq.

Step 5.4: FOLLOW THE CALL CHAIN
Record: userspace or driver request_irq on a GPIO line → __setup_irq → irq_request_resources (sleep OK) → raw_spin_lock_irqsave(&desc->lock) → irq_startup (atomic). Path is reachable whenever GPIO IRQs are used (BMC buttons, hotplug, etc.). Not an obscure config-only path if PINCTRL_NPCM8XX is enabled (depends on ARCH_NPCM || COMPILE_TEST).

Step 5.5: SEARCH FOR SIMILAR PATTERNS
Record: Same “direction_input in irq_request_resources” pattern in ingenic and ST pinctrl. Sibling pinctrl-npcm7xx.c still has the old startup-time direction_input call.

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

Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?
Record: Yes. Driver is drivers/pinctrl/nuvoton/pinctrl-npcm8xx.c. Introduced v6.7 (acf4884a571709). git merge-base --is-ancestor acf4884a571709 HEAD succeeded. Pre-fix startup still present at parent b8edfde12e355^. Local kernel: **v7.3-rc4** (7.3.0-rc4).

Step 6.2: CHECK FOR BACKPORT COMPLICATIONS
Record: Expected apply: **clean**. Hunks are local to the irqchip struct and two small callbacks. GPIOCHIP_IRQ_RESOURCE_HELPERS and gpiochip_reqres_irq() exist here. Reverse-apply of the committed diff checked cleanly against current file.

Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE
Record: No earlier alternate fix for this irq_startup sleep. Current HEAD already contains b8edfde12e355 because this checkout is mainline after the pinctrl-v7.3 pull; that is the upstream commit under review, not a prior independent fix. No later corrective commit.

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

Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY
Record: **pinctrl / GPIO irqchip for Nuvoton NPCM8XX (Arbel BMC)**.
Criticality: **PERIPHERAL** for general kernels, **IMPORTANT** for OpenBMC/NPCM845 systems. Not mm/fs/net core.

Step 7.2: ASSESS SUBSYSTEM ACTIVITY
Record: File is actively updated (pin tables, debounce, RMII, this IRQ fix). Driver is mature since v6.7, not brand-new staging code.

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

Step 8.1: DETERMINE WHO IS AFFECTED
Record: **driver-specific / platform-specific**: NPCM8XX (CONFIG_PINCTRL_NPCM8XX), typically OpenBMC on NPCM845. Not universal.

Step 8.2: DETERMINE THE TRIGGER CONDITIONS
Record: Trigger is GPIO IRQ request (request_irq / irqchip startup). Common for BMC GPIO IRQs. Unprivileged userspace can hit it if a GPIO irq is exported; typical path is kernel drivers during bring-up. Not a rare race: with lockdep it fires on every such startup. Mutex contention can turn it into a real sleep-under-spinlock.

Step 8.3: DETERMINE THE FAILURE MODE SEVERITY
Record: Failure mode: mutex_lock while desc->lock is held and IRQs are off.
- With CONFIG_PROVE_LOCKING / DEBUG_ATOMIC_SLEEP: lockdep/WARN (always)
- If pctldev->mutex is contended: **scheduling while atomic** → BUG
Severity: **HIGH** (illegal atomic sleep; crash if contended), not a silent data-corruption bug.

Step 8.4: CALCULATE RISK-BENEFIT RATIO
Record:
- Benefit: medium-high for NPCM8XX/OpenBMC (correct IRQ request, no lockdep/sleep-in-atomic); zero for other platforms
- Risk: **low** (~20 net lines, irqchip callbacks only, established pattern)
- Ratio: favorable

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

Step 9.1: COMPILE THE EVIDENCE
FOR:
- Real sleep-in-atomic: pinctrl_gpio_direction_input() takes mutexes; irq_startup() runs under raw_spin_lock_irqsave(&desc->lock)
- Deterministic on GPIO IRQ request with lockdep
- Can BUG if the pinctrl mutex is contended
- Small, obviously correct, matches ingenic/ST
- Keeps gpiochip_reqres_irq / gpiochip_relres_irq
- Driver exists in this tree since v6.7
- Author is NPCM maintainer; applied by Linus Walleij
- Standalone vs the rest of the 8-patch series

AGAINST:
- No user crash report / syzbot / Fixes tag
- Author framed the user-visible issue as lockdep, not production oops
- NPCM8XX-only
- Cover letter called the series a vendor-tree cleanup
- npcm7xx still has the same pattern (does not make this patch wrong)

UNRESOLVED:
- lore.kernel.org HTTP 403; stable@ discussion not independently fetched (thread itself was retrieved via b4)

Step 9.2: APPLY THE STABLE RULES CHECKLIST
1. Obviously correct and tested? **PASS** — context split is the documented irqchip model; applied by pinctrl maintainer. No extra Tested-by.
2. Fixes a real bug that affects users? **PASS** — illegal mutex in IRQ startup on GPIO request_irq.
3. Important issue? **PASS** — sleep-in-atomic / lockdep; possible BUG if mutex contended. Not a new feature.
4. Small and contained? **PASS** — one file, ~29 lines.
5. No new features or APIs? **PASS** — only irqchip callback placement.
6. Can apply to the local tree? **PASS** — driver and helpers exist; hunks match.

Step 9.3: CHECK FOR EXCEPTION CATEGORIES
Record: None (not a device ID, quirk, DT, build, or docs-only change). Qualifies as a normal bugfix.

Step 9.4: MAKE YOUR DECISION
This tree has the NPCM8XX driver and the buggy startup path. The patch is a small, correct move of a may-sleep call to irq_request_resources(), which is the sleepable side of request_irq(). That meets stable rules for this checkout.

Verification:
- [Phase 1] Tags: only Tomer Maimon and Linus Walleij SOBs; no Fixes/Reported-by/stable Cc
- [Phase 2] Diff: 23 insertions, 6 deletions in pinctrl-npcm8xx.c; direction_input moved; GPIOCHIP_IRQ_RESOURCE_HELPERS replaced by custom reqres/relres
- [Phase 2] pinctrl_gpio_direction() locks pctldev->mutex; pinctrl_get_device_gpio_range() locks pinctrldev_list_mutex
- [Phase 2] __setup_irq(): irq_request_resources() before desc->lock; irq_startup() while lock held (manage.c 1574–1766, unlock 1807)
- [Phase 3] Blame: bug from acf4884a571709 (v6.7-rc1); git merge-base --is-ancestor true for intro and for b8edfde12e355
- [Phase 3] git describe HEAD: v7.3-rc4-27-gf0100363d8c37; make kernelversion: 7.3.0-rc4
- [Phase 3] Series 1/8–8/8 identified; this patch does not depend on the others
- [Phase 4] b4 dig -c b8edfde12e355: lore msgid 20260715122923.1938327-7; v1 only
- [Phase 4] b4 dig -w: Walleij, Golaszewski, Andrew Jeffery, openbmc, linux-gpio
- [Phase 4] mbox: Walleij “No comments so patches applied”; no NAK/stable Cc
- [Phase 4] UNVERIFIED: stable@ archive (HTTP 403)
- [Phase 5] Same pattern in ingenic_gpio_irq_request and st_gpio_irq_request_resources; npcm7xx still uses startup-time direction_input
- [Phase 6] File present; reverse git apply --check of the commit diff succeeded
- [Phase 8] Failure mode: lockdep always; scheduling-while-atomic if mutex contended — HIGH for this SoC, not universal
- UNVERIFIED: whether an unprivileged gpiochip ioctl is the common trigger vs kernel drivers (both reach request_irq)

**YES**

 drivers/pinctrl/nuvoton/pinctrl-npcm8xx.c | 29 ++++++++++++++++++-----
 1 file changed, 23 insertions(+), 6 deletions(-)
drivers/pinctrl/nuvoton/pinctrl-npcm8xx.c +23 -6
index 28464463ff833..0347a471f9226 100644
@@ -295,17 +295,33 @@ static void npcmgpio_irq_unmask(struct irq_data *d)
 
 static unsigned int npcmgpio_irq_startup(struct irq_data *d)
 {
-	struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
-	unsigned int gpio = irqd_to_hwirq(d);
-
-	/* active-high, input, clear interrupt, enable interrupt */
-	npcmgpio_direction_input(gc, gpio);
 	npcmgpio_irq_ack(d);
 	npcmgpio_irq_unmask(d);
 
 	return 0;
 }
 
+static int npcmgpio_irq_request_resources(struct irq_data *d)
+{
+	struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
+	unsigned int gpio = irqd_to_hwirq(d);
+	int ret;
+
+	ret = npcmgpio_direction_input(gc, gpio);
+	if (ret)
+		return ret;
+
+	return gpiochip_reqres_irq(gc, gpio);
+}
+
+static void npcmgpio_irq_release_resources(struct irq_data *d)
+{
+	struct gpio_chip *gc = irq_data_get_irq_chip_data(d);
+	unsigned int gpio = irqd_to_hwirq(d);
+
+	gpiochip_relres_irq(gc, gpio);
+}
+
 static struct irq_chip npcmgpio_irqchip = {
 	.name = "NPCM8XX-GPIO-IRQ",
 	.irq_ack = npcmgpio_irq_ack,
@@ -313,8 +329,9 @@ static struct irq_chip npcmgpio_irqchip = {
 	.irq_mask = npcmgpio_irq_mask,
 	.irq_set_type = npcmgpio_set_irq_type,
 	.irq_startup = npcmgpio_irq_startup,
+	.irq_request_resources = npcmgpio_irq_request_resources,
+	.irq_release_resources = npcmgpio_irq_release_resources,
 	.flags =  IRQCHIP_MASK_ON_SUSPEND | IRQCHIP_IMMUTABLE,
-	GPIOCHIP_IRQ_RESOURCE_HELPERS,
 };
 
 static const int gpi36_pins[] = { 36 };
Signature · 1 line
2.53.0
author maintainer
#85 lore raw

PATCH 1/1 hfs: validate catalog CNIDs before instantiating inodes

In reply to Sasha Levin

From: David Maximiliano Hermitte <[email protected]>

[ Upstream commit 53c3c138d672765c26884c55728307a65c634328 ]

hfs_cat_find_brec() first resolves a catalog thread record by CNID and then looks up the corresponding catalog record by parent/name. On a corrupted filesystem image, the second lookup may find a record whose CNID does not match the CNID that was requested.

Validate the record found by the second lookup before returning it. Read the already-found record with hfs_bnode_read(), require the exact fixed size for file and directory records, reject other record types, and verify that the stored CNID matches the requested CNID.

Also validate reserved CNIDs in hfs_read_inode() before populating the inode, propagate hfs_read_inode() failures from the resource-fork lookup path, and reject bad resource-fork and root inodes.

Keep hfs_write_inode() unchanged, so corrupted catalog records are rejected before reaching its existing reserved-CNID BUG() path.

---

LLM Generated explanations, may be completely bogus:

The local checkout is **7.3.0-rc4** (v7.3-rc4-27-gf0100363d8c37). The commit is 53c3c138d6727 and is already in this mainline history (first contained in v7.3-rc1). The evaluation below is whether that fix is suitable to take into stable from this tree: HFS is present, the BUG() path is ancient, and the patch is self-contained.

---

## PHASE 1: COMMIT MESSAGE FORENSICS

**Step 1.1: PARSE THE SUBJECT LINE**
Record: **[hfs] [validate] Validate catalog CNIDs before instantiating inodes** — “validate” here is a correctness/safety check, not a feature.

**Step 1.2: PARSE ALL COMMIT MESSAGE TAGS**
Record:
- **Reported-by:** [email protected] (fuzzer, reproducible)
- **Closes:**
https://syzkaller.appspot.com/bug?extid=97e301b4b82ae803d21b
- **Cc:** George Anthony Vernon, Tetsuo Handa
- **Signed-off-by:** David Maximiliano Hermitte (author); Viacheslav Dubeyko (HFS maintainer, twice)
- **Reviewed-by:** Viacheslav Dubeyko
- **Link:** https://lore.kernel.org/r/20260708215636.73815-1-
[email protected]
- **No Fixes:** tag (expected)
- **No Cc: stable** (expected; not a negative)

**Step 1.3: ANALYZE THE COMMIT BODY TEXT**
Record:
- **Bug:** hfs_cat_find_brec() resolves a thread by CNID, then looks up the catalog record by parent/name. On a corrupted image that second lookup can return a record whose stored CNID does not match the requested CNID.
- **Symptom/failure mode:** A corrupted catalog record is turned into an inode with a reserved CNID (i_ino < HFS_FIRSTUSER_CNID and not root/extents/catalog). Later writeback hits BUG() in hfs_write_inode().
- **Version info:** none in the message; syzbot first crash is 2022-11-25.
- **Root cause (author):** missing validation of the second catalog lookup, plus missing reserved-CNID checks at inode instantiation; resource-fork lookup ignored hfs_read_inode() failures.

**Step 1.4: DETECT HIDDEN BUG FIXES**
Record: Not a disguised cleanup. Explicit syzbot crash fix: reject bad catalog records so they never reach the reserved-CNID BUG().

---

## PHASE 2: DIFF ANALYSIS - LINE BY LINE

**Step 2.1: INVENTORY THE CHANGES**
Record:
- fs/hfs/catalog.c: +40 / -1 — add hfs_cat_validate_found_cnid(), call it from hfs_cat_find_brec()
- fs/hfs/hfs_fs.h: +19 — add inline hfs_is_valid_cnid()
- fs/hfs/inode.c: +12 / -1 — CNID checks in hfs_read_inode(); propagate errors and is_bad_inode() in hfs_file_lookup()
- fs/hfs/super.c: +5 — reject bad root inode in hfs_fill_super()
- **Total:** +76 / -2 across 4 HFS files
- **Scope:** single-subsystem surgical fix

**Step 2.2: UNDERSTAND THE CODE FLOW CHANGE**
Record:
- **hfs_cat_find_brec:** Before: thread lookup, then return hfs_brec_find(fd) with no check that the found record’s CNID matches.
After: on success, read the found record, require exact file/dir size, reject other types, require found_cnid == cnid, else -EIO.
- **hfs_read_inode:** Before: populate inode from any file/dir record, including reserved CNIDs 0,1,5–15. After: hfs_is_valid_cnid(); invalid → -EIO before i_ino is set.
- **hfs_file_lookup (rsrc):** Before: ignored hfs_read_inode() return, then mark_inode_dirty(). After: propagate errors; is_bad_inode() → -EIO + iput.
- **hfs_fill_super:** After hfs_iget(), is_bad_inode(root) → iput and fail mount instead of d_make_root() on a bad inode.

**Step 2.3: IDENTIFY THE BUG MECHANISM**
Record:
- **Category:** memory-safety / logic — corrupted on-disk metadata → kernel BUG() (oops, invalid opcode).
- **Mechanism:** Reserved CNIDs instantiated as normal inodes; writeback hfs_write_inode() does BUG() in the default branch of inode->i_ino < HFS_FIRSTUSER_CNID. Also bounds/type checks on catalog record length.
- **Not:** leak, UAF, or locking fix.

**Step 2.4: ASSESS THE FIX QUALITY**
Record:
- Obviously correct relative to HFS CNID rules: user CNIDs ≥ 16; reserved 2=root dir, 3=extents file, 4=catalog file; others invalid for catalog-instantiated inodes.
- iget5_locked set() returning non-zero → inode_insert5() returns NULL; hfs_iget() already treats NULL as failure.
- New hfs_read_inode() code does not sleep (safe under inode_hash_lock).
- Maintainer asked to leave hfs_write_inode() unchanged; defense is at instantiation. Remaining BUG() is only if some other path still creates a reserved-CNID inode.
- **Regression risk:** low. Could reject a theoretically weird volume with catalog entries using CNIDs 1 or 5–15; that is invalid HFS and those inodes would BUG() on writeback anyway.
- No public API / data-structure change.

---

## PHASE 3: GIT HISTORY INVESTIGATION

**Step 3.1: BLAME THE CHANGED LINES**
Record: hfs_write_inode() reserved-CNID BUG() and hfs_cat_find_brec() date to **1da177e4c3f41 (Linux-2.6.12-rc2, 2005)**. Long-standing, not a newly introduced bug.

**Step 3.2: FOLLOW THE FIXES: TAG**
Record: No Fixes: tag. Buggy behavior is original HFS catalog/inode code, not a recent regression.

**Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES**
Record: Nearby HFS work (hfs_correct_next_unused_CNID, MDB locking) is independent. This commit is standalone, not patch X/Y. After it, later fs/hfs/{inode,catalog,super,hfs_fs.h} commits are unrelated (MDB, delayed work, ENOSPC). No follow-up fix to this patch.

**Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS**
Record: Only this HFS commit from David Maximiliano Hermitte. Weight comes from **Reviewed-by / Signed-off-by Viacheslav Dubeyko** (HFS maintainer). Earlier related attempts: George Vernon, Tetsuo Handa (syzbot thread).

**Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS**
Record: Uses existing hfs_bnode_read(), hfs_brec_find(), is_bad_inode(), HFS_*_CNID, hfs_read_inode() already returning int since 2.6.12. **Can apply standalone.**

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

**Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION**
Record:
- **b4 dig:**
https://patch.msgid.link/[email protected]
- **Revisions:** v1 (2026-07-02) → v3 RESEND → v4 → **v5 (applied)**
- Maintainer review drove exact size checks, signed rec_len, keep hfs_write_inode() unchanged, preserve hfs_file_lookup() error codes
- v5: Slava: “Looks good. Thanks a lot for the fix.” + Reviewed-by
- Tetsuo: not a NAK; points at sashiko notes on *pre-existing* issues
- Author revalidated with HFS build and QEMU syzbot repro
- **No NAKs** of the committed approach

**Step 4.2: CHECK WHO REVIEWED THE PATCH**
Record (b4 dig -w): Viacheslav Dubeyko, Tetsuo Handa, George Vernon, Jori Koolstra, linux-fsdevel, syzbot. Maintainer reviewed and merged.

**Step 4.3: SEARCH FOR THE BUG REPORT**
Record (syzbot, live page):
- Title: **kernel BUG in hfs_write_inode**
- First crash: **2022-11-25**; last listed ~35d before the page snapshot; **243695 crashes**; C and syz reproducers
- Stack: hfs_write_inode ← writeback wb_workfn (kworker), invalid opcode at BUG()
- Security assessment: DenialOfService yes, FilesystemTrigger yes, **Unprivileged: no** (needs a mountable image)
- Duplicate: “invalid opcode in hfs_write_inode”
- Fix commit listed as 53c3c138d672

**Step 4.4: CHECK FOR RELATED PATCHES AND SERIES**
Record: Single-patch series (v1–v5 of the same change). Earlier alternate approaches (replace BUG() with -EIO/-EFSCORRUPTED, broader BUG() removal) were **not** what merged; this validation-at- instantiation patch is standalone.

**Step 4.5: CHECK STABLE MAILING LIST HISTORY**
Record: **UNVERIFIED** — lore.kernel.org fetches returned 403. No `Cc:
stable` in the fsdevel thread. That absence is not a reason to reject.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

**Step 5.1: IDENTIFY KEY FUNCTIONS**
Record: hfs_cat_validate_found_cnid (new), hfs_cat_find_brec, hfs_is_valid_cnid (new inline), hfs_read_inode, hfs_file_lookup, hfs_fill_super. hfs_write_inode unchanged.

**Step 5.2: TRACE CALLERS**
Record:
- hfs_cat_find_brec() — only hfs_fill_super() (root at mount)
- hfs_read_inode() — iget5_locked set callback from hfs_iget() (hfs_lookup / hfs_fill_super) and direct call from hfs_file_lookup() (rsrc)
- hfs_write_inode() — s_op->write_inode from writeback (crash site)

**Step 5.3: TRACE CALLEES**
Record: hfs_bnode_read, hfs_brec_find, be32_to_cpu, is_bad_inode, iput. No new allocations/locks.

**Step 5.4: FOLLOW THE CALL CHAIN**
Record: Reachable from **mounting an HFS image** and from **lookup / rsrc** on a mounted volume. Syzbot C repro mounts a crafted image; writeback then BUG()s. Userspace-triggerable if the caller can mount HFS (CONFIG_HFS_FS).

**Step 5.5: SEARCH FOR SIMILAR PATTERNS**
Record: HFS+ already special-cases reserved vs user CNIDs in hfsplus_iget() (fs/hfsplus/super.c). Classic HFS lacked that for catalog-instantiated inodes. Same class of bug, HFS-only fix.

---

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

**Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE?**
Record: Yes. BUG() still in hfs_write_inode() at fs/hfs/inode.c (lines 479–491), present since 2.6.12. Validation from this commit is already applied here (hfs_is_valid_cnid in hfs_fs.h, hfs_cat_validate_found_cnid in catalog.c). Introduced: original HFS port, not post-7.3.

**Step 6.2: CHECK FOR BACKPORT COMPLICATIONS**
Record: **Expected apply: clean / minor context** on trees that still have hfs_cat_find_brec, hfs_read_inode, hfs_file_lookup, hfs_fill_super. New code does not depend on inode_set_ctime_to_ts, set_default_d_op, or CNID-correction helpers. Constants live in include/linux/hfs_common.h here; older trees may still have them in fs/hfs/hfs.h — only a context/include issue, not a logic dependency.

**Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE**
Record: This is the fix (53c3c138d6727). No earlier equivalent in- tree. Not in v7.2.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

**Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY**
Record: **fs/hfs** — **PERIPHERAL** (legacy Mac HFS, CONFIG_HFS_FS, not the VFS core). Still a real on-disk filesystem; a BUG() on corrupted images is a kernel crash, not a cosmetic warning.

**Step 7.2: ASSESS SUBSYSTEM ACTIVITY**
Record: Actively maintained under Viacheslav Dubeyko (hfs-v7.3-tag1 and other recent HFS tags). Mature code with ongoing syzbot/hardening.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

**Step 8.1: DETERMINE WHO IS AFFECTED**
Record: **Config/driver-specific:** CONFIG_HFS_FS. Anyone who can mount HFS (including fuzzers, forensic mounts, old Mac volumes). Not universal.

**Step 8.2: DETERMINE THE TRIGGER CONDITIONS**
Record: Mount / use a **corrupted HFS image**. Syzbot has a C repro; 240k+ crashes over ~4 years. Not unprivileged without mount capability. Timing-independent once the bad inode is instantiated and dirtied (hfs_file_lookup does mark_inode_dirty on rsrc).

**Step 8.3: DETERMINE THE FAILURE MODE SEVERITY**
Record: **BUG() / invalid opcode in writeback kworker → oops.** **Severity: CRITICAL** (kernel crash). DoS, not a demonstrated privilege-escalation.

**Step 8.4: CALCULATE RISK-BENEFIT RATIO**
Record:
- **Benefit:** high for HFS users and any tree that enables HFS — stops a years-old reproducible BUG().
- **Risk:** low — +76 lines, HFS-only, reviewed, tested with QEMU repro; failure mode on bad images becomes -EIO / failed mount instead of oops.
- **Ratio:** strongly favors backport.

---

## PHASE 9: FINAL SYNTHESIS

**Step 9.1: COMPILE THE EVIDENCE**

**FOR:**
- Syzbot kernel BUG() since 2022, C repro, hundreds of thousands of crashes
- Crash in writeback (wb_workfn → hfs_write_inode)
- Small, contained HFS-only change (+76/-2)
- Maintainer Reviewed-by after v1–v5
- Bug in code since 2.6.12; no missing prerequisites in this tree
- Matches stable rules: real crash, obviously correct validation, no new API

**AGAINST:**
- HFS is a legacy/peripheral FS
- Needs ability to mount HFS (not unprivileged syscall-only)
- hfs_write_inode() BUG() remains as a backstop if another path instantiates a reserved CNID
- No Cc: stable (expected for this review queue)

**UNRESOLVED:**
- lore.kernel.org/stable search (HTTP 403)
- Whether every older stable series has identical hunk context (hfs_common.h vs hfs.h)

**Step 9.2: APPLY THE STABLE RULES CHECKLIST**
1. Obviously correct and tested? **PASS** — maintainer review, QEMU repro, syzbot
2. Fixes a real bug that affects users? **PASS** — reproducible BUG() on corrupted HFS
3. Important issue? **PASS** — kernel oops (CRITICAL)
4. Small and contained? **PASS** — 4 files, +76/-2, HFS only
5. No new features or APIs? **PASS** — validation only
6. Can apply to the local tree? **PASS** — code is present; patch is self-contained (already merged here as of 7.3-rc1)

**Step 9.3: CHECK FOR EXCEPTION CATEGORIES**
Record: Not ID/quirk/DT/docs. Ordinary **crash fix** on filesystem corruption.

**Step 9.4: MAKE YOUR DECISION**
This is a real, long-standing, syzbot-reproduced kernel BUG() on corrupted HFS catalog data. The fix is small, reviewed, and stops bad CNIDs from becoming inodes that writeback will crash on. That is appropriate for stable.

---

### What the commit solves and why it matters
On a corrupted HFS catalog, a thread lookup by CNID can be followed by a parent/name lookup that returns a **different** record. That record can carry a reserved CNID (0, 1, 5–15, …). Instantiating it and dirtying it (notably the resource-fork path, which previously ignored hfs_read_inode() errors) causes **writeback to BUG()** in hfs_write_inode(). Stable kernels that still ship HFS will oops the same way; rejecting the record with -EIO is the right user-visible behavior.

### Stable rules / risk
Surgical, HFS-only, no new APIs, maintainer-acked, fuzzer-proven. Residual risk is failing mount/lookup on already-invalid volumes that used to oops instead.

### Concerns
Older trees may need a trivial context tweak if CNID macros are still in fs/hfs/hfs.h. No semantic prerequisites. The remaining BUG() in hfs_write_inode() is intentional per the maintainer.

### Verification
- **[Phase 1]** Tags: syzbot Reported-by, Closes syzkaller URL, Reviewed-by Dubeyko, lore Link; no Fixes/Cc-stable
- **[Phase 2]** Diff: +76/-2 in catalog.c, hfs_fs.h, inode.c, super.c; validation + error propagation
- **[Phase 3]** git describe HEAD → v7.3-rc4-27-gf0100363d8c37; make kernelversion → 7.3.0-rc4
- **[Phase 3]** Commit 53c3c138d6727; git merge-base --is-ancestor 53c3c138d6727 HEAD → yes
- **[Phase 3]** git merge-base --is-ancestor 53c3c138d6727 v7.2 → not in v7.2; git describe --contains → v7.3-rc1~222^2~9
- **[Phase 3]** Blame: BUG() in hfs_write_inode from 1da177e4c3f41 (2.6.12-rc2)
- **[Phase 3]** hfs_read_inode already static int since 2.6.12; pre- fix hfs_file_lookup discarded its return value
- **[Phase 4]** b4 dig -c 53c3c138d6727 → msgid 20260708215636.73815-1; v1/v3/v4/v5; v5 applied
- **[Phase 4]** b4 dig -w: Dubeyko, Handa, fsdevel, syzbot
- **[Phase 4]** b4 dig -m: Slava “Looks good” + Reviewed-by; asked to leave hfs_write_inode unchanged
- **[Phase 4]** WebFetch syzbot: kernel BUG in hfs_write_inode, 2022-11-25, C repro, 243695 crashes
- **[Phase 4]** lore.kernel.org WebFetch: 403 — stable-list search UNVERIFIED
- **[Phase 5]** Callers: hfs_cat_find_brec only from hfs_fill_super; hfs_iget from dir lookup + mount; rsrc via hfs_file_lookup
- **[Phase 5]** inode_insert5() treats failed set() as NULL inode (verified fs/inode.c)
- **[Phase 6]** Local files already contain the new helpers; BUG() path still present
- **[Phase 8]** Failure mode: oops in kworker writeback, severity CRITICAL
- **UNVERIFIED:** stable@ discussion (lore 403); exact hunk context on every LTS series

**YES**

 fs/hfs/catalog.c | 41 ++++++++++++++++++++++++++++++++++++++++-
 fs/hfs/hfs_fs.h  | 19 +++++++++++++++++++
 fs/hfs/inode.c   | 13 ++++++++++++-
 fs/hfs/super.c   |  5 +++++
 4 files changed, 76 insertions(+), 2 deletions(-)
fs/hfs/catalog.c +40 -1
index ccdbbffaaf7c1..f3fd84cffed5f 100644
@@ -182,6 +182,40 @@ int hfs_cat_keycmp(const btree_key *key1, const btree_key *key2)
 			  key2->cat.CName.name, key2->cat.CName.len);
 }
 
+static int hfs_cat_validate_found_cnid(struct hfs_find_data *fd, u32 cnid)
+{
+	hfs_cat_rec rec;
+	u32 found_cnid;
+	int rec_len;
+
+	rec_len = fd->entrylength;
+	if (rec_len <= 0 || (size_t)rec_len > sizeof(rec))
+		return -EIO;
+
+	memset(&rec, 0, sizeof(rec));
+	hfs_bnode_read(fd->bnode, &rec, fd->entryoffset, rec_len);
+
+	switch (rec.type) {
+	case HFS_CDR_FIL:
+		if ((size_t)rec_len != sizeof(struct hfs_cat_file))
+			return -EIO;
+		found_cnid = be32_to_cpu(rec.file.FlNum);
+		break;
+	case HFS_CDR_DIR:
+		if ((size_t)rec_len != sizeof(struct hfs_cat_dir))
+			return -EIO;
+		found_cnid = be32_to_cpu(rec.dir.DirID);
+		break;
+	default:
+		return -EIO;
+	}
+
+	if (found_cnid != cnid)
+		return -EIO;
+
+	return 0;
+}
+
 /* Try to get a catalog entry for given catalog id */
 // move to read_super???
 int hfs_cat_find_brec(struct super_block *sb, u32 cnid,
@@ -208,7 +242,12 @@ int hfs_cat_find_brec(struct super_block *sb, u32 cnid,
 		return -EIO;
 	}
 	memcpy(fd->search_key->cat.CName.name, rec.thread.CName.name, len);
-	return hfs_brec_find(fd);
+
+	res = hfs_brec_find(fd);
+	if (res)
+		return res;
+
+	return hfs_cat_validate_found_cnid(fd, cnid);
 }
 
 static inline
fs/hfs/hfs_fs.h +19 -0
index 86b5ae62247be..724b28bb8c6c4 100644
@@ -156,6 +156,25 @@ extern int hfs_cat_move(u32 cnid, struct inode *src_dir,
 extern void hfs_cat_build_key(struct super_block *sb, btree_key *key,
 			      u32 parent, const struct qstr *name);
 
+/*
+ * Validate the CNID of a catalog record.
+ */
+static inline bool hfs_is_valid_cnid(u32 cnid, u8 type)
+{
+	if (likely(cnid >= HFS_FIRSTUSER_CNID))
+		return true;
+
+	switch (cnid) {
+	case HFS_ROOT_CNID:
+		return type == HFS_CDR_DIR;
+	case HFS_EXT_CNID:
+	case HFS_CAT_CNID:
+		return type == HFS_CDR_FIL;
+	default:
+		return false;
+	}
+}
+
 /* dir.c */
 extern const struct file_operations hfs_dir_operations;
 extern const struct inode_operations hfs_dir_inode_operations;
fs/hfs/inode.c +12 -1
index f1796e4b07e83..e815e9a8ac6f2 100644
@@ -365,6 +365,9 @@ static int hfs_read_inode(struct inode *inode, void *data)
 	rec = idata->rec;
 	switch (rec->type) {
 	case HFS_CDR_FIL:
+		if (!hfs_is_valid_cnid(be32_to_cpu(rec->file.FlNum), rec->type))
+			return -EIO;
+
 		if (!HFS_IS_RSRC(inode)) {
 			hfs_inode_read_fork(inode, rec->file.ExtRec, rec->file.LgLen,
 					    rec->file.PyLen, be16_to_cpu(rec->file.ClpSize));
@@ -386,6 +389,9 @@ static int hfs_read_inode(struct inode *inode, void *data)
 		inode->i_mapping->a_ops = &hfs_aops;
 		break;
 	case HFS_CDR_DIR:
+		if (!hfs_is_valid_cnid(be32_to_cpu(rec->dir.DirID), rec->type))
+			return -EIO;
+
 		inode->i_ino = be32_to_cpu(rec->dir.DirID);
 		inode->i_size = be16_to_cpu(rec->dir.Val) + 2;
 		HFS_I(inode)->fs_blocks = 0;
@@ -565,13 +571,18 @@ static struct dentry *hfs_file_lookup(struct inode *dir, struct dentry *dentry,
 	res = hfs_brec_read(&fd, &rec, sizeof(rec));
 	if (!res) {
 		struct hfs_iget_data idata = { NULL, &rec };
-		hfs_read_inode(inode, &idata);
+		res = hfs_read_inode(inode, &idata);
 	}
 	hfs_find_exit(&fd);
 	if (res) {
 		iput(inode);
 		return ERR_PTR(res);
 	}
+
+	if (is_bad_inode(inode)) {
+		iput(inode);
+		return ERR_PTR(-EIO);
+	}
 	HFS_I(inode)->rsrc_inode = dir;
 	HFS_I(dir)->rsrc_inode = inode;
 	igrab(dir);
fs/hfs/super.c +5 -0
index 97546d6b41f47..933aa04480899 100644
@@ -372,6 +372,11 @@ static int hfs_fill_super(struct super_block *sb, struct fs_context *fc)
 	if (!root_inode)
 		goto bail_no_root;
 
+	if (is_bad_inode(root_inode)) {
+		iput(root_inode);
+		goto bail_no_root;
+	}
+
 	set_default_d_op(sb, &hfs_dentry_operations);
 	res = -ENOMEM;
 	sb->s_root = d_make_root(root_inode);
Signature · 1 line
2.53.0
author maintainer
#86 lore raw

PATCH 1/1 PCI: cadence: Add missing MODULE_DEVICE_TABLE()

In reply to Sasha Levin

From: Pengpeng Hou <[email protected]>

[ Upstream commit 93aac16f1eb9a181f9bdde620b464f6cc5fa8369 ]

The driver has an OF match table wired to .of_match_table, but does not export the table with MODULE_DEVICE_TABLE().

Add the missing MODULE_DEVICE_TABLE(of, ...) entry so module alias information is generated for OF based module autoloading.

---

LLM Generated explanations, may be completely bogus:

# Stable backport analysis: PCI: cadence: Add missing MODULE_DEVICE_TABLE()

Local tree: **Linux 7.3.0-rc4** (v7.3-rc4-27-gf0100363d8c37). Verdict is for this checkout only.

Candidate: 93aac16f1eb9a181f9bdde620b464f6cc5fa8369

---

## PHASE 1: COMMIT MESSAGE FORENSICS

**Step 1.1 — Subject line**
Record: [PCI/cadence] [Add] missing MODULE_DEVICE_TABLE() so OF module aliases are generated

**Step 1.2 — Tags**
Record:
- Signed-off-by: Pengpeng Hou <[email protected]> (author)
- Signed-off-by: Manivannan Sadhasivam <[email protected]> (PCI controller maintainer; applied the patch)
- Reviewed-by: Aksh Garg <[email protected]>
- `Link:
https://patch.msgid.link/[email protected]`
- No Fixes:, no Reported-by:, no Cc: stable (absence is expected for this review)
- No syzbot / KASAN / crash report

**Step 1.3 — Body**
Record:
[Bug] OF match table is wired to .of_match_table but not exported via MODULE_DEVICE_TABLE().
[Symptom] depmod / udev / modprobe do not get of:N*T*Ccdns,cdns- pcie-host / cdns,cdns-pcie-ep aliases, so the module does not autoload.
[Version info] None in the message.
[Root cause] Missing alias publication, not a runtime logic error. The mailing-list body (mbox) states this is a source-level fix with no hardware reproducer.

**Step 1.4 — Hidden bug fix?**
Record: Not disguised. It is an explicit autoload/modalias fix. Same class as PCI: j721e: Fix module autoloading.

---

## PHASE 2: DIFF ANALYSIS

**Step 2.1 — Inventory**
Record:
[Files] drivers/pci/controller/cadence/pcie-cadence-plat.c (+1 / −0) [Functions] none changed; one statement added after cdns_plat_pcie_of_match[]
[Scope] single-file, one-line surgical change

**Step 2.2 — Code flow**
Record: Before: match table exists and is used for probe matching, but scripts/mod/file2alias.c never sees it, so the .ko has no OF aliases. After: MODULE_DEVICE_TABLE(of, cdns_plat_pcie_of_match) creates the __mod_of__cdns_plat_pcie_of_match alias (include/linux/module.h). Normal module-build path only; no probe/runtime behavior change.

**Step 2.3 — Bug mechanism**
Record: [Category] logic/correctness for modular OF drivers (missing userspace alias). [Mechanism] without the macro, a modular pcie- cadence-plat never autoloads from DT. Sibling Cadence drivers already export tables (pci-j721e.c, pci-sky1.c, pcie-sg2042.c).

**Step 2.4 — Fix quality**
Record: Obviously correct and minimal. Regression risk is effectively
none: it only adds module metadata. Does not change locking, probe, or APIs. Reviewer AI notes about probe return 0 and drvdata type mismatch are **pre-existing** and not introduced here.

---

## PHASE 3: GIT HISTORY

**Step 3.1 — Blame**
Record: Match table introduced in bd22885aa188f (“PCI: cadence:
Refactor driver to use as a core library”, 2019). Driver was builtin_platform_driver + bool Kconfig until 611627a4e5e4a (“PCI:
cadence: Add module support for platform controller driver”, 2025-11-14). That commit is in **v6.19**. Bug (missing table export for a loadable module) starts there.

**Step 3.2 — Fixes: tag**
Record: No Fixes: tag. The introducing commit is 611627a4e5e4a (module support). It **is** an ancestor of this tree.

**Step 3.3 — File history**
Record: Recent: HPA support, module support, then this one-liner. Standalone; not patch X/Y. No later revert on this file.

**Step 3.4 — Author**
Record: Pengpeng Hou also did e145af8c14474 PCI: spacemit: Add missing MODULE_DEVICE_TABLE() the same day. Applied by Manivannan Sadhasivam (PCI controller maintainer).

**Step 3.5 — Dependencies**
Record: Needs module_platform_driver + tristate Kconfig from 611627a4e5e4a. Both are in this 7.3 tree. Applies standalone here.

---

## PHASE 4: MAILING LIST / EXTERNAL

**Step 4.1 — Original discussion**
Record: b4 dig -c 93aac16f1eb9a →
https://patch.msgid.link/[email protected]
b4 dig -a: **v1 only**, 2026-07-04.
Thread (mbox): Aksh Garg Reviewed-by; Manivannan “Applied, thanks!” to 93aac16f1eb9a. No NAK, no stable nomination, no concern about this line.

**Step 4.2 — Recipients (b4 dig -w)**
Record: PCI maintainers (Lorenzo Pieralisi, Krzysztof Wilczyński, Manivannan Sadhasivam, Bjorn Helgaas), Rob Herring, linux-pci, linux- kernel.

**Step 4.3 — Bug report**
Record: None. Author did not claim a hardware reproducer.

**Step 4.4 — Related series**
Record: Same-day sibling PCI: spacemit: Add missing MODULE_DEVICE_TABLE(). Precedent in-tree: 9a7f144e18dc5 `PCI: j721e:
Fix module autoloading (Fixes: + Cc: stable`) — same one-line OF table export.

**Step 4.5 — Stable list**
Record: UNVERIFIED. lore.kernel.org returned a bot-check page; WebFetch of the msgid URL returned 403. No stable-list discussion was retrieved.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

**Step 5.1 — Functions**
Record: No function bodies changed. Data: cdns_plat_pcie_of_match[].
Driver: cdns_plat_pcie_driver / cdns_plat_pcie_probe.

**Step 5.2 — Callers**
Record: Probe is the platform-driver callback. Match table used only in this file. Triggered when DT has cdns,cdns-pcie-host or cdns,cdns- pcie-ep.

**Step 5.3 — Callees**
Record: Unchanged. MODULE_DEVICE_TABLE is a compile-time alias for file2alias.c.

**Step 5.4 — Reachability**
Record: Reachable on OF platforms that describe Cadence PCIe with those compatibles and build CONFIG_PCIE_CADENCE_PLAT=m. No in-tree .dts/.dtsi uses those strings (only DT binding examples). So the in- tree user set is small; out-of-tree / FPGA / IP reference boards may still use the generic compatible.

**Step 5.5 — Similar patterns**
Record: Same missing-table pattern already fixed for j721e, mvebu, qcom- ep, spacemit, and the other Cadence glue drivers in this directory.

---

## PHASE 6: LOCAL TREE CROSS-CHECK

**Step 6.1 — Does the buggy code exist here?**
Record: Yes. This tree has tristate PCIE_CADENCE_PLAT, module_platform_driver, and the OF table. Module support is in v6.19+. Without MODULE_DEVICE_TABLE, modular autoload is broken. (The one-line fix is present at line 166 of the current file; that is not used as “already selected” circular reasoning — it confirms the surrounding code matches the patch.)

**Step 6.2 — Backport difficulty**
Record: Clean apply on this tree: one line next to the existing table.

**Step 6.3 — Related fixes already here?**
Record: j721e/sky1/sg2042 already have MODULE_DEVICE_TABLE. Nothing else replaces this plat-driver export.

---

## PHASE 7: SUBSYSTEM CONTEXT

**Step 7.1**
Record: [drivers/pci/controller/cadence] [IMPORTANT for Cadence-IP SoCs; PERIPHERAL vs core mm/net]. PCIe host not coming up is serious for those boards, not universal.

**Step 7.2**
Record: Active PCI controller area (HPA, module support, several glue drivers). Plat driver itself is mature (2019) with occasional fixes.

---

## PHASE 8: IMPACT AND RISK

**Step 8.1 — Who is affected**
Record: Driver-specific / config-specific: CONFIG_PCIE_CADENCE_PLAT=m plus DT compatible cdns,cdns-pcie-*. Built-in builds are unaffected. No in-tree board DTS match; population is reference/FPGA/out-of-tree DT.

**Step 8.2 — Trigger**
Record: Boot (or coldplug) on matching DT with the driver as a module. Common for modular embedded images. Unprivileged users cannot trigger a crash; they just never get the controller unless something else loads the module.

**Step 8.3 — Failure mode**
Record: [Failure] module not autoloaded → PCIe host/endpoint never probes → downstream devices missing. [Severity] **MEDIUM** (functional miss, not oops/corruption). Workaround: modprobe or =y.

**Step 8.4 — Risk vs benefit**
Record: Benefit: hardware actually binds on modular kernels. Risk: very low (modinfo aliases only). Ratio: favorable. Same class as device-ID / autoload fixes that stable already takes (j721e was Cc: stable).

---

## PHASE 9: SYNTHESIS

**Step 9.1 — Evidence**

For:
- Real autoload bug on a driver this tree can build as a module
- One line, obviously correct, maintainer-applied, reviewed
- Sibling Cadence drivers already export tables; j721e’s identical fix was stable-tagged
- Zero runtime regression surface
- Fits “device ID / make existing hardware work” exception more than a feature

Against:
- No user report, no Fixes:/Cc: stable on this patch
- Author stated no hardware reproduction
- No in-tree DTS uses these compatibles
- Not a crash, UAF, or data-corruption bug
- Stable mailing-list history UNVERIFIED

Unresolved: whether anyone on stable@ already rejected or requested this (lore blocked).

**Step 9.2 — Stable rules (this tree)**
1. Obviously correct and tested? **PASS** — one documented macro; v1 applied as-is after Reviewed-by.
2. Real bug that affects users? **PASS** — modular OF autoload fails; users who =m this controller do not get PCIe without a manual load.
3. Important (crash/security/corruption/deadlock)? **PASS** at “oh, that’s not good” / device-ID-class — PCIe does not come up. Not CRITICAL.
4. Small and contained? **PASS** — +1 line, one file.
5. No new features or APIs? **PASS** — metadata for IDs that already exist.
6. Can apply to this tree? **PASS** — table, module_platform_driver, and tristate Kconfig are all here.

**Step 9.3 — Exception category**
Record: Closest to **device ID / hardware enablement**: publishing existing OF IDs for autoload, not a new driver.

**Step 9.4 — Decision**
This 7.3 tree can build the Cadence platform controller as a module. Without MODULE_DEVICE_TABLE(of, ...), userspace never sees the aliases and the host/endpoint driver does not autoload. That is a real, user- visible functional bug, a one-line contained fix, and the same pattern already sent to stable for pci-j721e. Risk is negligible. It should be included in this tree.

---

## What the commit solves (for stable users)

On kernels where CONFIG_PCIE_CADENCE_PLAT=m, udev/modprobe cannot match DT nodes cdns,cdns-pcie-host / cdns,cdns-pcie-ep to pcie- cadence-plat.ko. The controller never probes unless the module is loaded by hand. The patch only emits the standard OF aliases. No new ABI, no probe-path change.

Risk vs benefit: benefit is “PCIe works on modular images”; risk is alias-only. Backport on this tree is a clean one-line apply; prerequisite module support (611627a4e5e4a, v6.19) is already present.

---

## Verification

- [Phase 1] Parsed tags: author Hou, SOB+apply Manivannan Sadhasivam, Reviewed-by Aksh Garg, Link msgid; no Fixes/Reported-by/Cc:stable
- [Phase 2] Diff: +1 line MODULE_DEVICE_TABLE(of, cdns_plat_pcie_of_match) in pcie-cadence-plat.c
- [Phase 2] Confirmed macro in include/linux/module.h creates file2alias alias
- [Phase 3] git describe HEAD / make kernelversion: **7.3.0-rc4**
- [Phase 3] git blame: table from bd22885aa188f (2019); MODULE_DEVICE_TABLE line from 93aac16f1eb9a
- [Phase 3] Introducer of modular bug: 611627a4e5e4a (bool→tristate, builtin_platform_driver→module_platform_driver); first tag **v6.19**; git merge-base --is-ancestor 611627a4e5e4a HEAD true
- [Phase 3] git merge-base --is-ancestor 93aac16f1eb9a HEAD true (used only to confirm context, not as “already selected”)
- [Phase 3] No revert of this commit on the file after it
- [Phase 4] b4 dig -c/-a/-w/-m: v1 only; lore msgid above; PCI maintainers on To; Reviewed-by + Applied; no NAK
- [Phase 4] WebFetch lore URL: 403; lore search: bot wall. Stable-list discussion **UNVERIFIED**
- [Phase 5] git grep cdns_plat_pcie: confined to plat driver + header
+ sky1 using the of_data struct
- [Phase 5] git grep of compatibles in arch/: **no** dts/dtsi users; only DT binding examples
- [Phase 5] Sibling MODULE_DEVICE_TABLE already in j721e, sky1, sg2042
- [Phase 6] Local file has match table + module_platform_driver + tristate Kconfig; patch applies as a single added line
- [Phase 6] Precedent 9a7f144e18dc5 j721e autoload fix has Fixes: + Cc: stable
- [Phase 8] Failure mode: no autoload → PCIe missing; severity MEDIUM, not oops
- UNVERIFIED: whether this was discussed on stable@ (lore blocked)

**YES**

 drivers/pci/controller/cadence/pcie-cadence-plat.c | 1 +
 1 file changed, 1 insertion(+)
drivers/pci/controller/cadence/pcie-cadence-plat.c +1 -0
index 0456845dabb96..0f9cf2a9f0034 100644
@@ -167,6 +167,7 @@ static const struct of_device_id cdns_plat_pcie_of_match[] = {
 	},
 	{},
 };
+MODULE_DEVICE_TABLE(of, cdns_plat_pcie_of_match);
 
 static struct platform_driver cdns_plat_pcie_driver = {
 	.driver = {
Signature · 1 line
2.53.0
#87 lore raw

Re: [PATCH AUTOSEL 6.18-5.10] PCI: cadence: Add missing MODULE_DEVICE_TABLE()

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] PCI: cadence: MODULE_DEVICE_TABLE() added to non-modular built-in driver --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] PCI: cadence: MODULE_DEVICE_TABLE() added to non-modular built-in driver --

commit 47a5cb89a268b5f62186006942f7b1da4567a7f3
Author: Pengpeng Hou <[email protected]>

PCI: cadence: Add missing MODULE_DEVICE_TABLE()

This commit adds MODULE_DEVICE_TABLE(of, cdns_plat_pcie_of_match) to pcie-cadence-plat.c so that module alias information is generated for OF-based module autoloading.

drivers/pci/controller/cadence/pcie-cadence-plat.c static const struct of_device_id cdns_plat_pcie_of_match[] = { · line 173

Quoted 12 lines
drivers/pci/controller/cadence/pcie-cadence-plat.c +1 -0
index 0456845dabb96..0f9cf2a9f0034 100644
@@ -167,6 +167,7 @@ static const struct of_device_id cdns_plat_pcie_of_match[] = {
 	},
 	{},
 };
+MODULE_DEVICE_TABLE(of, cdns_plat_pcie_of_match);
 
 static struct platform_driver cdns_plat_pcie_driver = {
 	.driver = {

[Severity: Medium]
Can this driver actually be built as a loadable module in this tree?

Upstream commit 611627a4e5e4a ("PCI: cadence: Add module support for platform controller driver", merged in v6.19) converted the Kconfig symbols from bool to tristate and switched the driver to module_platform_driver(), but that prerequisite commit is not present in this v6.18 baseline.

In this tree, drivers/pci/controller/cadence/Kconfig defines the symbols as bool:

config PCIE_CADENCE_PLAT
bool

config PCIE_CADENCE_PLAT_HOST
bool "Cadence platform PCIe controller (host mode)"

config PCIE_CADENCE_PLAT_EP
bool "Cadence platform PCIe controller (endpoint mode)"

And drivers/pci/controller/cadence/pcie-cadence-plat.c registers cdns_plat_pcie_driver as a built-in driver without including linux/module.h, defining a .remove callback, or setting MODULE_LICENSE():

static struct platform_driver cdns_plat_pcie_driver = {
	.driver = {
		.name = "cdns-pcie",
		.of_match_table = cdns_plat_pcie_of_match,
		.pm	= &cdns_pcie_pm_ops,
	},
	.probe = cdns_plat_pcie_probe,
	.shutdown = cdns_plat_pcie_shutdown,
};

builtin_platform_driver(cdns_plat_pcie_driver);

Since pcie-cadence-plat can only be compiled built-in (never with -DMODULE), MODULE_DEVICE_TABLE(of, cdns_plat_pcie_of_match) preprocesses to nothing under !MODULE and relies on transitive inclusion of linux/module.h. Should this backport be dropped from this branch, or is commit 611627a4e5e4a also intended to be backported?

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1