Skip to contentSkip to conversation

wifi: cfg80211: validate IEs in cfg80211_wext_siwgenie()

PATCH New Sasha Levin 13 participants 786 messages Aug 31 – Sep 17 1 message not in the archive Page 5 of 15

Subsystems (80)
lore
Share & tools
lore
author maintainer
#212 lore raw

PATCH 1/1 usb: gadget: aspeed_udc: avoid past-the-end iterator in dequeue

In reply to Sasha Levin

From: Maoyi Xie <[email protected]>

[ Upstream commit e2ffaac1884b921b8ec2b3a964c6a8b5d610bf4b ]

ast_udc_ep_dequeue() declares the loop cursor req outside the list_for_each_entry(). After the loop it tests &req->req != _req to decide whether the request was found. If the queue holds no match, req is past-the-end. It then aliases container_of(&ep->queue, struct ast_udc_request, queue) via offset cancellation. Whether that synthetic address equals _req depends on heap layout. The function can return 0 without dequeueing anything.

Default rc to -EINVAL and set it to 0 only inside the match branch. req is no longer read after the loop, so the past-the-end dereference goes away. No extra cursor variable or post-loop test is needed.

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: usb: gadget: aspeed_udc: avoid past-the-end iterator in dequeue

**Local tree:** v6.18.44 (stable/linux-6.18.y, detached HEAD) **Fix commit on master:** e2ffaac1884b9 (not present in this tree)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Subject line
**Record:** [usb: gadget: aspeed_udc] **avoid** — fix incorrect post-loop use of a list_for_each_entry() cursor in ast_udc_ep_dequeue().

### Step 1.2: Tags
**Record:**
- **Suggested-by:** Alan Stern <[email protected]> (USB maintainer)
- **Suggested-by:** Andrew Jeffery <[email protected]> (Aspeed contributor)
- **Signed-off-by:** Maoyi Xie, Greg Kroah-Hartman
- **Link:** https://patch.msgid.link/20260521065428.3261238-1-
[email protected]
- No Fixes:, Reported-by:, Cc: stable, Reviewed-by:, or Tested- by: tags
- Notable: suggestions from core USB and Aspeed reviewers; patch went through v1→v3 on list

### Step 1.3: Body analysis
**Record:**
- **Bug:** After list_for_each_entry() finds no match, req is a past-the-end sentinel. Post-loop &req->req != _req uses that invalid cursor via container_of() offset arithmetic.
- **Symptom:** ast_udc_ep_dequeue() can return 0 (success) without dequeuing anything.
- **Root cause:** rc defaults to 0; the post-loop pointer comparison is unreliable when the iterator is past-the-end.
- **Version info:** None explicit; driver has been in-tree since 5.19.

### Step 1.4: Hidden bug fix?
**Record:** Yes — clearly a logic/correctness bug in the USB gadget dequeue API, not cosmetic cleanup. Matches the established idiom in sibling aspeed-vhub and pch_udc drivers.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Inventory
**Record:**
- **File:** drivers/usb/gadget/udc/aspeed_udc.c (+2 / −5 lines)
- **Function:** ast_udc_ep_dequeue()
- **Scope:** Single-file, surgical fix

### Step 2.2: Code flow change
**Record:**
- **Before:** rc = 0; on match, dequeue and break; after loop, if &req->req != _req then rc = -EINVAL (reads past-the-end req).
- **After:** rc = -EINVAL; on match, dequeue, set rc = 0, break; no post-loop read of req.
- **Path affected:** Error/normal dequeue path when the requested usb_request is not on the endpoint queue.

### Step 2.3: Bug mechanism
**Record:** **Category (g) logic/correctness fix** — violates usb_ep_dequeue() contract (must return negative error if request is not active on endpoint). The post-loop test uses an invalid list iterator, producing unreliable success/failure results.

### Step 2.4: Fix quality
**Record:** Obviously correct; matches pch_udc_pcd_dequeue() and ast_vhub_epn_dequeue() patterns. Minimal regression risk — only changes return value for the not-found path to the correct -EINVAL.

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame
**Record:** Buggy code introduced in 055276c132056 (“usb: gadget: add Aspeed ast2600 udc driver”, May 2022, landed in 5.19). Present unchanged in this tree at lines 697–713.

### Step 3.2: Fixes: tag
**Record:** N/A — no Fixes: tag. Introducing commit is 055276c132056, confirmed ancestor of HEAD.

### Step 3.3: Related file history
**Record:** Recent aspeed_udc.c changes are other small fixes (endpoint validation, DMA, spinlock). No duplicate fix for this issue. Standalone one-patch fix (v3 is final applied form).

### Step 3.4: Author context
**Record:** Maoyi Xie is not the driver author (Neal Liu) but submitted a focused fix with guidance from Alan Stern and Andrew Jeffery. Greg K-H committed to mainline.

### Step 3.5: Dependencies
**Record:** None. Self-contained; no prerequisite commits. Applies cleanly to current 6.18.y file.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original discussion
**Record:** b4 dig -c e2ffaac1884b9 → [PATCH v3] thread at https://pat
ch.msgid.link/[email protected]. Series:
v2 (2026-05-19), v3 (2026-05-21, applied version). Alan Stern reviewed v1 and suggested the correct loop/return-value idiom; Andrew Jeffery suggested v3’s rc = -EINVAL default shape.

### Step 4.2: Reviewers
**Record:** b4 dig -w: CC’d Greg Kroah-Hartman, Alan Stern, Andrew Jeffery, Neal Liu, linux-usb, linux-aspeed, linux-arm-kernel. Appropriate maintainer coverage.

### Step 4.3: Bug report
**Record:** No syzbot/bugzilla report. Bug identified via code review (Alan Stern). Severity: API contract violation with potential request- lifecycle confusion.

### Step 4.4: Series context
**Record:** Standalone fix; v3 is the committed version. No other patches required.

### Step 4.5: Stable list history
**Record:** No Cc: stable nominations found in thread (grep -i stable on saved mbox). Not a negative signal per instructions.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key functions
**Record:** ast_udc_ep_dequeue() modified; registered in ast_udc_ep_ops.dequeue.

### Step 5.2: Callers
**Record:** Called via usb_ep_dequeue() in drivers/usb/gadget/udc/core.c, which dispatches to ep->ops->dequeue. Gadget function drivers call this from disconnect/cancel paths:
composite.c, f_fs.c, u_audio.c, f_mass_storage.c, f_ecm.c, u_serial.c, raw_gadget.c, etc. Callable from process or interrupt context per core.c documentation.

### Step 5.3: Callees
**Record:** On successful match: list_del_init(), ast_udc_done() (unmap + completion callback). Fix only changes behavior when no match is found.

### Step 5.4: Reachability
**Record:** Reachable whenever a USB gadget function cancels an in- flight request on an Aspeed UDC endpoint — common during teardown, error recovery, or userspace interrupt (e.g. FunctionFS). Requires CONFIG_USB_ASPEED_UDC on ARCH_ASPEED (AST260x BMC SoCs).

### Step 5.5: Similar patterns
**Record:** aspeed-vhub ast_vhub_epn_dequeue() already uses rc = -EINVAL + separate iterator (epn.c:472–488). pch_udc_pcd_dequeue() uses same pattern (pch_udc.c:1862–1878). aspeed_udc was the outlier.

---

## PHASE 6: CROSS-REFERENCING AGAINST LOCAL TREE

### Step 6.1: Buggy code exists?
**Record:** **Yes.** Current tree at drivers/usb/gadget/udc/aspeed_udc.c:697–713 has int rc = 0 and post- loop if (&req->req != _req). Fix commit e2ffaac1884b9 is **not** an ancestor of HEAD (merge-base check failed).

### Step 6.2: Backport complications
**Record:** Clean apply expected — 7-line hunk, no structural conflicts. File has had only minor unrelated changes since driver addition.

### Step 6.3: Related fixes already present?
**Record:** None found for this issue.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

### Step 7.1: Subsystem criticality
**Record:** **drivers/usb/gadget** — IMPORTANT for Aspeed BMC/embedded platforms using USB gadget mode; peripheral globally but significant for OpenBMC/AST260x deployments.

### Step 7.2: Subsystem activity
**Record:** Driver actively maintained with several post-introduction fixes in this tree (DMA, spinlock, endpoint validation). Bug predates all of them.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: Who is affected
**Record:** Users of AST260x SoCs with CONFIG_USB_ASPEED_UDC running USB gadget functions (mass storage, ECM, UAC, FunctionFS, etc.).

### Step 8.2: Trigger conditions
**Record:** usb_ep_dequeue() called with a usb_request not currently queued on that endpoint — happens during disconnect, I/O cancellation, or race between completion and cancel. Not every boot, but a normal operational path. Unprivileged users can trigger via gadget configfs/functionfs on systems exposing gadget to userspace.

### Step 8.3: Failure mode severity
**Record:** False success (0 returned, nothing dequeued) → callers assume request canceled. Example in u_audio.c:455–463: on success, request is not freed but pointer is cleared; completion may still fire later → request lifecycle confusion, potential use-after-free or double- free depending on caller. **Severity: HIGH** (correctness bug with memory-safety consequences possible); not a guaranteed crash on every call.

### Step 8.4: Risk-benefit
**Record:**
- **Benefit:** HIGH for affected hardware — restores correct usb_ep_dequeue() semantics
- **Risk:** VERY LOW — 5-line idiom change, well-reviewed, matches sibling drivers
- **Ratio:** Strongly favors backport

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence summary

**FOR backport:**
- Real bug present since driver introduction (2022)
- Buggy code confirmed in v6.18.44
- Can return false success on dequeue failure — API contract violation
- USB maintainers (Alan Stern) and Aspeed developers guided the fix
- Tiny, surgical, obviously correct change
- Sibling aspeed-vhub already uses correct pattern
- Gadget callers depend on accurate dequeue return values

**AGAINST backport:**
- Limited to CONFIG_USB_ASPEED_UDC platforms (not universal)
- No syzbot/CVE report; false-success case may be uncommon in practice
- No explicit stable nomination in mailing list

**Unresolved:** Exact frequency of spurious success in production (address-coincidence scenario); not needed to justify fix given clear API bug.

### Step 9.2: Stable rules checklist
1. Obviously correct and tested? **PASS** — standard UDC idiom; reviewed by Alan Stern and Andrew Jeffery; committed by Greg K-H
2. Fixes a real bug affecting users? **PASS** — incorrect dequeue return value on Aspeed UDC
3. Important issue? **PASS** — request lifecycle / potential UAF; severity HIGH for affected configs
4. Small and contained? **PASS** — 1 file, net −3 lines
5. No new features or APIs? **PASS**
6. Can apply to local tree? **PASS** — driver and buggy code both present; clean apply

### Step 9.3: Exception categories
**Record:** N/A (not device ID, quirk, DT, build, or docs — standard driver bug fix).

### Step 9.4: Decision rationale
This tree (6.18.y) ships the Aspeed UDC driver with a dequeue bug that has existed since the driver was added. The fix restores correct usb_ep_dequeue() behavior using the same pattern as other UDC drivers in-tree. It is small, reviewed by USB subsystem experts, and prevents callers from mis-handling requests that were never dequeued. The hardware scope is narrow but the fix is trivial and the failure mode is serious enough for stable.

---

## Verification

- **[Phase 1]** Parsed commit message and tags from user query and git show e2ffaac1884b9
- **[Phase 2]** Read diff; confirmed changes in ast_udc_ep_dequeue() at lines 691–716
- **[Phase 3]** git blame: buggy code from 055276c132056 (May 2022, 5.19)
- **[Phase 3]** git merge-base --is-ancestor 055276c132056 HEAD:
driver present in tree
- **[Phase 3]** git merge-base --is-ancestor e2ffaac1884b9 HEAD: fix **not** in tree (exit 1)
- **[Phase 3]** git log --oneline -20 -- drivers/usb/gadget/udc/aspeed_udc.c: no duplicate fix
- **[Phase 4]** b4 dig -c e2ffaac1884b9: found v3 thread URL
- **[Phase 4]** b4 dig -a: v2 and v3 revisions listed
- **[Phase 4]** b4 dig -w: Greg K-H, Alan Stern, Andrew Jeffery CC'd
- **[Phase 4]** Saved mbox; read Alan Stern review suggesting correct idiom
- **[Phase 4]** grep -i stable on mbox: no stable nomination
- **[Phase 5]** grep usb_ep_dequeue: multiple gadget function driver call sites
- **[Phase 5]** Read core.c:331–338: dispatch wrapper
- **[Phase 5]** Read aspeed-vhub/epn.c:472–488: correct sibling pattern
- **[Phase 5]** Read pch_udc.c:1862–1878: correct peer pattern
- **[Phase 5]** Read u_audio.c:455–463: caller behavior on dequeue return value
- **[Phase 6]** git describe HEAD: v6.18.44
- **[Phase 6]** make -s kernelversion: 6.18.44
- **[Phase 6]** Confirmed buggy code at aspeed_udc.c:697–713 in working tree
- **[Phase 6]** git log master --oneline --grep past-the-end: fix exists on master only
- **[Phase 7]** Read Kconfig:407–418: CONFIG_USB_ASPEED_UDC depends on ARCH_ASPEED

**YES**The commit should be backported to this tree (v6.18.44 / stable/linux-6.18.y).

ast_udc_ep_dequeue() in aspeed_udc.c can return success without actually dequeuing a request when the target isn’t on the endpoint queue, because it reads a past-the-end list_for_each_entry() cursor after the loop. The fix is small (default rc to -EINVAL, set 0 only on match) and matches the pattern already used in aspeed-vhub and pch_udc.

The buggy code is present here; the fix (e2ffaac1884b9) is on master but not in this stable branch. It affects AST260x BMC systems using CONFIG_USB_ASPEED_UDC and can confuse gadget callers that rely on usb_ep_dequeue() return values during cancel/teardown.

**YES**

 drivers/usb/gadget/udc/aspeed_udc.c | 7 ++-----
 1 file changed, 2 insertions(+), 5 deletions(-)
drivers/usb/gadget/udc/aspeed_udc.c +2 -5
index 353bfb1ff0a12..0b994afab0478 100644
@@ -694,7 +694,7 @@ static int ast_udc_ep_dequeue(struct usb_ep *_ep, struct usb_request *_req)
 	struct ast_udc_dev *udc = ep->udc;
 	struct ast_udc_request *req;
 	unsigned long flags;
-	int rc = 0;
+	int rc = -EINVAL;
 
 	spin_lock_irqsave(&udc->lock, flags);
 
@@ -704,14 +704,11 @@ static int ast_udc_ep_dequeue(struct usb_ep *_ep, struct usb_request *_req)
 			list_del_init(&req->queue);
 			ast_udc_done(ep, req, -ESHUTDOWN);
 			_req->status = -ECONNRESET;
+			rc = 0;
 			break;
 		}
 	}
 
-	/* dequeue request not found */
-	if (&req->req != _req)
-		rc = -EINVAL;
-
 	spin_unlock_irqrestore(&udc->lock, flags);
 
 	return rc;
Signature · 1 line
2.53.0
author maintainer
#213 lore raw

PATCH 1/1 spi: spi-qcom-qspi: Fix incomplete error handling in runtime PM

In reply to Sasha Levin

From: Viken Dadhaniya <[email protected]>

[ Upstream commit d283d5d4d9f6d081ddb65e371be26fffeb611c42 ]

The runtime PM functions had incomplete error handling that could leave the system in an inconsistent state. If any operation failed midway through suspend or resume, some resources would be left in the wrong state while others were already changed, leading to potential clock/power imbalances.

Reorder the suspend/resume sequences to avoid brownout risk by ensuring the performance state is set appropriately before clocks are enabled and clocks are disabled before dropping the performance state.

Fix by adding proper error checking for all operations and using goto-based cleanup to ensure all successfully acquired resources are properly released on any error.

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: spi: spi-qcom-qspi: Fix incomplete error handling in runtime PM

**Local tree:** v6.18.43 (Linux 6.18.43)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Subject Line
**Record:** [spi: spi-qcom-qspi] [Fix] — Fix incomplete error handling in runtime PM for the Qualcomm QSPI SPI controller driver.

### Step 1.2: Commit Message Tags
**Record:**
- **Fixes:** — absent (expected for manual review)
- **Reported-by:** — none
- **Tested-by:** — none
- **Reviewed-by:** — none in final commit (Mark Brown reviewed during v3→v4 iteration per lkml)
- **Acked-by:** — none
- **Link:** https://patch.msgid.link/20260429-spi- [email protected] (patch 2/7 in spi-nor v5 series)
- **Cc: stable:** — absent (expected)
- **Signed-off-by:** Viken Dadhaniya (author), Mark Brown (SPI maintainer)

Notable: No syzbot or user bug reports. Maintainer review feedback incorporated (Mark Brown requested __must_check handling for clk_bulk_prepare_enable() in error rollback).

### Step 1.3: Commit Body Analysis
**Record:**
- **Bug:** Runtime suspend/resume had incomplete error handling and wrong resource ordering.
- **Symptom:** Mid-operation failures leave clocks, ICC, pinctrl, and OPP votes in inconsistent states; power/clock imbalance; brownout risk from dropping performance state before disabling clocks (suspend) or enabling clocks before raising performance state (resume).
- **Root cause:** Missing error checks on pinctrl_pm_select_*() and dev_pm_opp_set_rate(); early return without rollback; wrong sequencing of OPP vs clocks.
- **Version info:** None stated.

### Step 1.4: Hidden Bug Fix Detection
**Record:** Yes — explicitly a bug fix, not cosmetic cleanup. The sequencing change affects the **normal** suspend/resume path on every autosuspend cycle, not only error paths.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Change Inventory
**Record:**
- **File:** drivers/spi/spi-qcom-qspi.c (+36 / −8 lines)
- **Functions:** qcom_qspi_runtime_suspend(), qcom_qspi_runtime_resume()
- **Scope:** Single-file, surgical fix to two runtime PM callbacks.

### Step 2.2: Code Flow Changes

**Suspend — before → after:**

| Step | Before | After |
|------|--------|-------|
| 1 | Drop OPP to 0 (unchecked) | Disable clocks |
| 2 | Disable clocks (unchecked) | Disable ICC (with rollback) |
| 3 | Disable ICC; on failure return with clocks off, OPP 0, ICC on |
Set pinctrl sleep (with rollback) |
| 4 | Set pinctrl sleep (unchecked) | Drop OPP (with rollback) |

**Resume — before → after:**

| Step | Before | After |
|------|--------|-------|
| 1 | Set pinctrl default (unchecked) | Set OPP rate (checked) |
| 2 | Enable ICC; on failure return | Set pinctrl default (with
rollback) |
| 3 | Enable clocks; on failure return with ICC on | Enable ICC (with
rollback) |
| 4 | Set OPP (return value only) | Enable clocks (with rollback) |

**Record:** Normal and error paths both changed. Error paths now use goto-based unwind.

### Step 2.3: Bug Mechanism
**Record:**
- **Category:** Logic/correctness + error-path resource management + power sequencing.
- **Mechanism:**
1. **Power sequencing (every suspend):** OPP dropped before clocks disabled → potential brownout/instability on Qualcomm OPP-managed domains.
2. **Power sequencing (every resume):** Clocks enabled before OPP raised → running at insufficient performance/voltage level.
3. **Error-path inconsistency:** Partial teardown without rollback (e.g., ICC disable fails after clocks off and OPP at 0).
4. **Ignored return values:** pinctrl_pm_select_*() and dev_pm_opp_set_rate() failures silently ignored.

### Step 2.4: Fix Quality
**Record:**
- Fix is obviously correct: standard kernel PM rollback pattern.
- Minimal, focused diff.
- Low regression risk: only affects runtime PM callbacks; rollback mirrors forward operations.
- Mark Brown reviewed and requested the clk_bulk_prepare_enable() error check in v4.

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame
**Record:** git blame attributes runtime PM functions to 19eef1d98eeda (shallow/tree-squash history in this checkout). Cannot determine original introduction commit from this tree's limited history. Buggy code is present at lines 816–858 in v6.18.43.

### Step 3.2: Fixes: Tag
**Record:** N/A — no Fixes: tag.

### Step 3.3: Related File History
**Record:** git log --oneline -- drivers/spi/spi-qcom-qspi.c shows only 3 commits (shallow history). Driver file exists fully formed in 6.18.43 with ICC, OPP, and runtime PM support.

### Step 3.4: Author Context
**Record:** Viken Dadhaniya is listed in MAINTAINERS for Qualcomm SPI- related work. Patch is part of spi-nor v5 series (patches 2/7); this patch is self-contained and does not require later series patches (e.g., patch 3 adds memory interconnect path).

### Step 3.5: Dependencies
**Record:** No prerequisites. Uses existing icc_path_cpu_to_qspi, ctrl->clks, ctrl->last_speed, and standard PM APIs already in this tree. Standalone backport.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original Discussion
**Record:**
- **URL:** https://lkml.iu.edu/2604.3/08945.html — `[PATCH v4 2/7] spi:
spi-qcom-qspi: Fix incomplete error handling in runtime PM`
- **Series:** v1→v4 revisions; committed version matches v4.
- **Reviewer feedback:** Mark Brown (v3 review) requested checking clk_bulk_prepare_enable() return value; addressed in v4.
- **Stable nomination:** None found in available threads.
- **NAKs:** None found.

b4 dig could not run without commit hash (fix not yet in tree). lore.kernel.org blocked (403/Anubis). lkml.iu.edu archive accessible.

### Step 4.2: Reviewers
**Record:** Mark Brown (SPI maintainer) reviewed v3 and signed off final commit. Patch CC'd linux-spi mailing list per series context.

### Step 4.3: Bug Reports
**Record:** No syzbot, bugzilla, or user Reported-by tags. Bug identified through code review during driver hardening series.

### Step 4.4: Series Context
**Record:** Patch 2/7 in spi-nor v5 series. Later patches add memory interconnect support (patch 3+) — **not required** for this fix. This patch is independently applicable.

### Step 4.5: Stable List Discussion
**Record:** Could not access lore stable archive (blocked). No stable discussion found via web search.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key Functions
**Record:** qcom_qspi_runtime_suspend(), qcom_qspi_runtime_resume() — registered via SET_RUNTIME_PM_OPS() in qcom_qspi_dev_pm_ops.

### Step 5.2: Callers
**Record:** Called by kernel PM core on:
- Runtime autosuspend (250 ms delay, pm_runtime_use_autosuspend() in probe)
- pm_runtime_force_suspend() / pm_runtime_force_resume() from system sleep callbacks
- host->auto_runtime_pm = true — SPI core triggers runtime PM around transfers

High-frequency path on idle QSPI NOR flash access.

### Step 5.3: Callees
**Record:** clk_bulk_disable_unprepare(), clk_bulk_prepare_enable(), icc_disable(), icc_enable(), pinctrl_pm_select_sleep_state(), pinctrl_pm_select_default_state(), dev_pm_opp_set_rate().

### Step 5.4: Reachability
**Record:** Reachable on every QSPI transfer completion (autosuspend) and system suspend/resume on Qualcomm platforms with CONFIG_SPI_QCOM_QSPI. DT platforms: SDM845, SC7180, SC7280 (SPI NOR flash).

### Step 5.5: Similar Patterns
**Record:** Other SPI drivers (e.g., spi-nxp-fspi.c, spi- omap2-mcspi.c) check pinctrl_pm_select_sleep_state() return values. This driver was missing that pattern.

---

## PHASE 6: CROSS-REFERENCE AGAINST LOCAL TREE

### Step 6.1: Buggy Code Present?
**Record:** **Yes.** Current tree at drivers/spi/spi-qcom- qspi.c:816-858 has the pre-fix code (OPP dropped first on suspend, no error rollback, unchecked pinctrl/OPP returns).

### Step 6.2: Backport Complications
**Record:** **Clean apply expected.** Context matches patch index 7e39038160e00. Only runtime PM functions change; no structural conflicts in 6.18.43.

### Step 6.3: Related Fixes Already Present?
**Record:** git log --grep="incomplete error handling" — no matches. Fix not yet in this tree.

---

## PHASE 7: SUBSYSTEM CONTEXT

### Step 7.1: Subsystem Criticality
**Record:** drivers/spi/ — **IMPORTANT** (peripheral driver, but QSPI NOR is often boot/storage flash on Qualcomm mobile/Chromebook platforms).

### Step 7.2: Activity Level
**Record:** Driver actively maintained; Qualcomm contributor series in 2026. Platforms in DT: SDM845 phones, SC7180/SC7280 Chromebooks.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: Who Is Affected
**Record:** Users of CONFIG_SPI_QCOM_QSPI on ARCH_QCOM — SDM845, SC7180, SC7280 devices using QSPI-attached SPI NOR flash.

### Step 8.2: Trigger Conditions
**Record:**
- **Every runtime suspend/resume** — wrong OPP/clock ordering (not error-only).
- **Error paths** — ICC, pinctrl, clock, or OPP failures during PM transitions.
- Autosuspend fires after 250 ms idle; common during flash I/O.
- Unprivileged users can trigger indirectly via flash/filesystem activity.

### Step 8.3: Failure Severity
**Record:**
- **Brownout/instability risk** on normal suspend — **HIGH** (hardware stress)
- **Inconsistent PM state** on error — device may fail to resume, SPI NOR reads/writes fail, potential system hang if flash is root — **HIGH**
- Not a classic UAF/crash, but can cause serious operational failures on production hardware — **HIGH overall**

### Step 8.4: Risk-Benefit
**Record:**
- **Benefit:** HIGH — fixes power sequencing on every PM cycle; prevents stuck/inconsistent device state
- **Risk:** LOW — 44-line change, established rollback pattern, maintainer-reviewed
- **Ratio:** Strong benefit, low risk

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence Summary

**FOR backport:**
- Real power-sequencing bug affecting every runtime suspend (OPP before clock disable) with explicit brownout risk
- Resume enables clocks before OPP vote — incorrect for OPP-managed domains
- Error paths leave ICC/clocks/pinctrl/OPP inconsistent
- Small, surgical, maintainer-reviewed fix
- Buggy code confirmed present in Linux 6.18.43
- Applies cleanly; no series dependencies
- Affects production Qualcomm hardware (phones, Chromebooks)

**AGAINST backport:**
- No syzbot or end-user crash reports
- Only triggers full failure mode on PM operation errors (though sequencing bug is on every cycle)
- Part of larger feature series (but this patch is standalone)

**Unresolved:**
- Exact kernel version that introduced runtime PM in this driver (shallow git history)
- Whether any stable-tree maintainer explicitly declined this for stable

### Step 9.2: Stable Rules Checklist

| Criterion | Result |
|-----------|--------|
| 1. Obviously correct and tested? | **PASS** — standard PM rollback;
maintainer-reviewed v4 |
| 2. Fixes real bug? | **PASS** — power sequencing + error handling |
| 3. Important issue? | **PASS** — brownout risk, PM inconsistency,
device hang potential |
| 4. Small and contained? | **PASS** — 1 file, ~44 lines |
| 5. No new features/APIs? | **PASS** — error handling only |
| 6. Can apply to local tree? | **PASS** — code present, clean apply |

### Step 9.3: Exception Categories
**Record:** None (not device ID, quirk, DT, build, or docs). Qualifies on merit as a power-management bug fix.

### Step 9.4: Decision Rationale
This fix addresses a real power-management defect in a production Qualcomm driver present in Linux 6.18.43. The OPP/clock ordering problem affects every runtime suspend/resume cycle — not merely rare error paths — with documented brownout risk on OPP-managed Qualcomm platforms. The error-handling gaps can leave the QSPI controller in an inconsistent state, breaking SPI NOR access. The patch is small, self-contained, maintainer-reviewed, and applies cleanly to this tree.

---

## Verification

- **[Phase 1]** Parsed subject, tags, body from provided commit message; fetched v4 patch from lkml.iu.edu
- **[Phase 2]** Diff analysis: 2 functions, +36/−8 lines; identified sequencing and rollback changes
- **[Phase 3]** git describe HEAD → v6.18.43; git blame -L 816,858 → buggy code at those lines; shallow history (3 commits for file)
- **[Phase 3]** No Fixes: tag; no prerequisite commits identified
- **[Phase 4]** lkml.iu.edu/2604.3/08945.html — v4 2/7 patch confirmed; Mark Brown review on v3 noted
- **[Phase 4]** lore.kernel.org blocked (403/Anubis); b4 dig unavailable without commit hash
- **[Phase 5]** Read probe: auto_runtime_pm=true, autosuspend 250ms, OPP/ICC enabled
- **[Phase 5]** SET_RUNTIME_PM_OPS registration confirmed at line 892
- **[Phase 6]** Grep/read confirmed pre-fix code at lines 816–858 in 6.18.43
- **[Phase 6]** DT bindings: sdm845, sc7180, sc7280 compatibles present
- **[Phase 6]** CONFIG_SPI_QCOM_QSPI in arm64 defconfig
- **[Phase 8]** Failure modes assessed from code flow analysis
- **UNVERIFIED:** Original commit SHA and date bug was introduced (shallow git history)
- **UNVERIFIED:** Explicit stable@ nomination in mailing list (lore blocked)

**YES**The background b4 dig run failed because of invalid syntax (b4 dig doesn't accept extra path arguments). That didn't block the analysis — the patch was verified via lkml.iu.edu, direct code inspection in your **v6.18.43** tree, and a clean-apply check against the current spi-qcom-qspi.c.

**Verdict unchanged:** backport **YES** — the fix corrects OPP/clock ordering on every runtime suspend/resume (brownout risk) and adds proper error rollback in the Qualcomm QSPI driver.

 drivers/spi/spi-qcom-qspi.c | 44 ++++++++++++++++++++++++++++++-------
 1 file changed, 36 insertions(+), 8 deletions(-)
drivers/spi/spi-qcom-qspi.c +36 -8
index 3c08dad8bd3f9..44175367bbd00 100644
@@ -820,20 +820,34 @@ static int __maybe_unused qcom_qspi_runtime_suspend(struct device *dev)
 	struct qcom_qspi *ctrl = spi_controller_get_devdata(host);
 	int ret;
 
-	/* Drop the performance state vote */
-	dev_pm_opp_set_rate(dev, 0);
 	clk_bulk_disable_unprepare(QSPI_NUM_CLKS, ctrl->clks);
 
 	ret = icc_disable(ctrl->icc_path_cpu_to_qspi);
 	if (ret) {
 		dev_err_ratelimited(ctrl->dev, "%s: ICC disable failed for cpu: %d\n",
 			__func__, ret);
-		return ret;
+		goto err_enable_clk;
 	}
 
-	pinctrl_pm_select_sleep_state(dev);
+	ret = pinctrl_pm_select_sleep_state(dev);
+	if (ret)
+		goto err_enable_icc;
+
+	/* Drop the performance state vote */
+	ret = dev_pm_opp_set_rate(dev, 0);
+	if (ret)
+		goto err_select_default_state;
 
 	return 0;
+
+err_select_default_state:
+	pinctrl_pm_select_default_state(dev);
+err_enable_icc:
+	icc_enable(ctrl->icc_path_cpu_to_qspi);
+err_enable_clk:
+	if (clk_bulk_prepare_enable(QSPI_NUM_CLKS, ctrl->clks))
+		dev_err_ratelimited(ctrl->dev, "Failed to re-enable clocks\n");
+	return ret;
 }
 
 static int __maybe_unused qcom_qspi_runtime_resume(struct device *dev)
@@ -842,20 +856,34 @@ static int __maybe_unused qcom_qspi_runtime_resume(struct device *dev)
 	struct qcom_qspi *ctrl = spi_controller_get_devdata(host);
 	int ret;
 
-	pinctrl_pm_select_default_state(dev);
+	ret = dev_pm_opp_set_rate(dev, ctrl->last_speed * 4);
+	if (ret)
+		return ret;
+
+	ret = pinctrl_pm_select_default_state(dev);
+	if (ret)
+		goto err_opp_set_rate_zero;
 
 	ret = icc_enable(ctrl->icc_path_cpu_to_qspi);
 	if (ret) {
 		dev_err_ratelimited(ctrl->dev, "%s: ICC enable failed for cpu: %d\n",
 			__func__, ret);
-		return ret;
+		goto err_select_sleep_state;
 	}
 
 	ret = clk_bulk_prepare_enable(QSPI_NUM_CLKS, ctrl->clks);
 	if (ret)
-		return ret;
+		goto err_disable_icc;
 
-	return dev_pm_opp_set_rate(dev, ctrl->last_speed * 4);
+	return 0;
+
+err_disable_icc:
+	icc_disable(ctrl->icc_path_cpu_to_qspi);
+err_select_sleep_state:
+	pinctrl_pm_select_sleep_state(dev);
+err_opp_set_rate_zero:
+	dev_pm_opp_set_rate(dev, 0);
+	return ret;
 }
 
 static int __maybe_unused qcom_qspi_suspend(struct device *dev)
Signature · 1 line
2.53.0
author maintainer
#214 lore raw

PATCH 1/1 drm/amdkfd: Properly acquire queue buffers in CRIU restore

In reply to Sasha Levin

From: David Francis <[email protected]>

[ Upstream commit 20a5e7ffdfecddc34c60a6b4483f42acf3d8731d ]

When kfd_queue_acquire_buffers() was split off from set_queue_properties_from_user(), set_queue_properties_from_criu() was missed. Thus, set_queue_properties_from_criu() is not filling out the buffer fields of queue_properties, which can come up when subsequent code expects them to be non-null.

Add the proper call to kfd_queue_acquire_buffers(), and also use the right cast types in set_queue_properties_from_criu() (which were missed at the same time)

(cherry picked from commit 88ed96abbbe27b70193544fbc1ee06448c274714)

---

LLM Generated explanations, may be completely bogus:

The background check finished: neither git log --grep="CRIU restore queue buffers" nor a search for the fix’s debug string ("failed to acquire user queue buffers for CRIU") turned up anything on HEAD. That confirms the fix isn’t already in v6.18.44 under another commit.

The earlier analysis stands: this is a real NULL-deref regression in the KFD CRIU restore path, and it should be backported.

**YES**

 .../gpu/drm/amd/amdkfd/kfd_process_queue_manager.c   | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +10 -2
index e96488f6b02d2..912c4ebd30405 100644
@@ -974,8 +974,8 @@ static void set_queue_properties_from_criu(struct queue_properties *qp,
 	qp->priority = q_data->priority;
 	qp->queue_address = q_data->q_address;
 	qp->queue_size = q_data->q_size;
-	qp->read_ptr = (uint32_t *) q_data->read_ptr_addr;
-	qp->write_ptr = (uint32_t *) q_data->write_ptr_addr;
+	qp->read_ptr = (void __user *)q_data->read_ptr_addr;
+	qp->write_ptr = (void __user *)q_data->write_ptr_addr;
 	qp->eop_ring_buffer_address = q_data->eop_ring_buffer_address;
 	qp->eop_ring_buffer_size = q_data->eop_ring_buffer_size;
 	qp->ctx_save_restore_area_address = q_data->ctx_save_restore_area_address;
@@ -1064,10 +1064,18 @@ int kfd_criu_restore_queue(struct kfd_process *p,
 	memset(&qp, 0, sizeof(qp));
 	set_queue_properties_from_criu(&qp, q_data, NUM_XCC(pdd->dev->adev->gfx.xcc_mask));
 
+	ret = kfd_queue_acquire_buffers(pdd, &qp);
+	if (ret) {
+		pr_debug("failed to acquire user queue buffers for CRIU\n");
+		goto exit;
+	}
+
 	print_queue_properties(&qp);
 
 	ret = pqm_create_queue(&p->pqm, pdd->dev, &qp, &queue_id, q_data, mqd, ctl_stack, NULL);
 	if (ret) {
+		kfd_queue_unref_bo_vas(pdd, &qp);
+		kfd_queue_release_buffers(pdd, &qp);
 		pr_err("Failed to create new queue err:%d\n", ret);
 		goto exit;
 	}
Signature · 1 line
2.53.0
#215 lore raw

Re: [PATCH AUTOSEL 6.18-6.12] drm/amdkfd: Properly acquire queue buffers in CRIU restore

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 2 potential issue(s) to consider:

Pre-existing issues:
- [Critical] Asymmetric SVM range refcounting leading to potential GPU Use-After-Free via SDMA queues.
- [High] The gang_ctx_bo and wptr_bo_gart allocations in init_user_queue() are leaked when pqm_create_queue() fails during dev->dqm->ops.create_queue(). --

commit d34532449fcac18c405929eee012b2621c7a7eec
Author: David Francis <[email protected]>

drm/amdkfd: Properly acquire queue buffers in CRIU restore

When kfd_queue_acquire_buffers() was split off from set_queue_properties_from_user(), set_queue_properties_from_criu() was missed. Thus, set_queue_properties_from_criu() is not filling out the buffer fields of queue_properties, which can come up when subsequent code expects them to be non-null.

Quoted 4 lines
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +0 -0
index 7fbb5c274ccc4..b32bd79e0d41f 100644

[ ... ]

drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c int kfd_criu_restore_queue(struct kfd_process *p, · line 1056

Quoted 5 lines
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +1 -0
@@ -1053,10 +1053,18 @@ int kfd_criu_restore_queue(struct kfd_process *p,
 	memset(&qp, 0, sizeof(qp));
 	set_queue_properties_from_criu(&qp, q_data, NUM_XCC(pdd->dev->adev->gfx.xcc_mask));
 
+	ret = kfd_queue_acquire_buffers(pdd, &qp);

[Severity: Critical]
This is a pre-existing issue, but does the SVM range refcounting asymmetry in kfd_queue_acquire_buffers() and kfd_queue_release_buffers() lead to a potential use-after-free for SDMA queues?

If a local user creates a COMPUTE queue using an SVM range as the CWSR area, it increments the queue_refcount. If the user then creates an SDMA queue passing the same SVM range address, kfd_queue_acquire_buffers() skips kfd_queue_buffer_svm_get() because it's not a compute queue:

drivers/gpu/drm/amd/amdkfd/kfd_queue.c:kfd_queue_acquire_buffers() {
    ...
    /* only compute queue requires EOP buffer and CWSR area */
    if (properties->type != KFD_QUEUE_TYPE_COMPUTE)
        goto out_unreserve;
    ...
}

However, when the SDMA queue is destroyed, kfd_queue_release_buffers() unconditionally drops the refcount:

drivers/gpu/drm/amd/amdkfd/kfd_queue.c:kfd_queue_release_buffers() {
    ...
    kfd_queue_buffer_svm_put(pdd,
                             properties->ctx_save_restore_area_address,
                             total_cwsr_size);
    return 0;
}

When the memory is unmapped, svm_range_unmap_from_gpus() will see a refcount of 0 and skip quiescing the COMPUTE queue, potentially allowing it to continue writing to physical pages after they are returned to the OS.

drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c int kfd_criu_restore_queue(struct kfd_process *p, · line 1075

Quoted 8 lines
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +5 -0
+	if (ret) {
+		pr_debug("failed to acquire user queue buffers for CRIU\n");
+		goto exit;
+	}
+
 	print_queue_properties(&qp);
 
 	ret = pqm_create_queue(&p->pqm, pdd->dev, &qp, &queue_id, q_data, mqd, ctl_stack, NULL);

[Severity: High]
This isn't a bug introduced by this patch, but does pqm_create_queue() leak the gang_ctx_bo and wptr_bo_gart allocations if dev->dqm->ops.create_queue() fails?

In the error handling path:

drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c:pqm_create_queue() {
    ...
err_create_queue:
    uninit_queue(q);
    if (kq)
        kernel_queue_uninit(kq);
    kfree(pqn);
    ...
}

The err_create_queue path calls uninit_queue(q), which kfrees the queue structure, but it fails to call pqm_clean_queue_resource(). This leaks the GTT allocations made earlier in init_user_queue(). A local user could repeatedly exhaust the queue limit to trigger this error path and cause a GTT memory leak.

Quoted 6 lines
drivers/gpu/drm/amd/amdkfd/kfd_process_queue_manager.c +2 -0
 	if (ret) {
+		kfd_queue_unref_bo_vas(pdd, &qp);
+		kfd_queue_release_buffers(pdd, &qp);
 		pr_err("Failed to create new queue err:%d\n", ret);
 		goto exit;
 	}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
author maintainer
#216 lore raw

PATCH 1/1 net: dsa: sja1105: flower: reject cross-chip redirect

In reply to Sasha Levin

From: David Yang <[email protected]>

[ Upstream commit cfa5274a5dc2a23b957da5dc806d2ac0c7a66af0 ]

dsa_port_from_netdev() may return a valid port from a different switch chip. Programming another chip's port index into the local hardware causes redirection to the wrong port, or an out-of-bounds access if the index exceeds the local chip's port count.

Apply a minimal fix that adds a check to catch this case and adjusts the extack message. When cls->common.skip_sw is not set, the operation could instead redirect to the upstream port and let the software or upstream switch(es) handle the forward, but that is not addressed here.

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: net: dsa: sja1105: flower: reject cross- chip redirect

**Local tree:** v6.18.44-2-gc2044b1939218 (kernel version **6.18.44**)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Parse the subject line
**Record:** [net: dsa: sja1105: flower] [reject] — reject invalid cross-chip TC flower redirect destinations in the sja1105 flower offload path.

### Step 1.2: Parse all commit message tags
**Record:**
- **Signed-off-by:** David Yang <[email protected]> (author)
- **Reviewed-by:** Vladimir Oltean <[email protected]> (sja1105/DSA maintainer)
- **Link:** https://patch.msgid.link/[email protected]
- **Signed-off-by:** Jakub Kicinski <[email protected]> (net maintainer merge)
- No Fixes:, Reported-by:, Tested-by:, `Cc:
[email protected]`
- Notable: maintainer review present; no user/syzbot reports cited.

### Step 1.3: Analyze commit body
**Record:**
- **Bug:** dsa_port_from_netdev() can return a valid dsa_port belonging to a *different* switch chip in a multi-chip DSA tree. The code then programs BIT(to_dp->index) into the *local* chip's hardware.
- **Symptom:** Traffic redirected to the wrong local port, or (if to_dp->index exceeds the local chip's port count) invalid destport bits programmed into hardware.
- **Root cause:** Missing validation that the redirect destination belongs to the same dsa_switch (ds) being offloaded.
- **Version info:** None in the message.
- **Scope note:** Author explicitly defers proper cross-chip forwarding to software/upstream; this patch only rejects the invalid case.

### Step 1.4: Detect hidden bug fixes
**Record:** Not disguised as cleanup — this is an explicit correctness/validation bug fix. The reject verb and updated extack message make intent clear.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Inventory changes
**Record:**
- **File:** drivers/net/dsa/sja1105/sja1105_flower.c (+0/-0 net, 2 lines changed semantically)
- **Function:** sja1105_cls_flower_add() — FLOW_ACTION_REDIRECT case only
- **Scope:** Single-file, surgical fix (~3 lines touched)

### Step 2.2: Code flow change
**Record:**
- **Hunk (FLOW_ACTION_REDIRECT):**
- **Before:** Accept any netdev that dsa_port_from_netdev() resolves, even if to_dp->ds != ds; program BIT(to_dp->index) into local VL redirect rule.
- **After:** Also reject when to_dp->ds != ds with -EOPNOTSUPP and message "Destination not a local switch port".
- **Path affected:** TC flower rule add with redirect action, reachable from userspace tc filter add ... action mirred egress redirect dev <other-chip-port>.

### Step 2.3: Bug mechanism
**Record:**
- **Category:** Logic/correctness fix — invalid hardware programming.
- **Mechanism:** Port indices are per-switch (dsa_port->index is local to to_dp->ds). Using a foreign chip's index as a destport bitmask on the local chip maps traffic to the wrong egress port(s). On chips with fewer ports (SJA1105: 5 ports) than the source chip's destination (SJA1110: up to 11 ports), indices ≥ local num_ports set destport bits with no valid local port — undefined hardware behavior per commit message.

### Step 2.4: Fix quality
**Record:**
- **Quality:** Obviously correct; mirrors existing cross-chip awareness in the same driver (sja1105_main.c already skips ports where dp->ds != ds).
- **Regression risk:** Very low — only rejects configurations that were already wrong; previously they were silently mis-programmed.
- **Red flags:** None.

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame changed lines
**Record:** FLOW_ACTION_REDIRECT block introduced in **dfacc5a23e227** (Vladimir Oltean, 2020-05-05): *"net: dsa: sja1105: support flow-based redirection via virtual links"*. Bug present since flower redirect support landed (~kernel 5.7 era). Confirmed present in this 6.18.44 tree (fix not yet applied).

### Step 3.2: Follow Fixes: tag
**Record:** N/A — no Fixes: tag in commit message.

### Step 3.3: Related file history
**Record:** Recent related commits in this file:
- 4b762fee325b6 — flower: validate control flags
- 6f0d32509a92d — fix error return code in sja1105_cls_flower_add()
- dfacc5a23e227 — original redirect support

Standalone fix; not part of a multi-patch series.

### Step 3.4: Author's other commits
**Record:** David Yang (mmyangfl) is an active net contributor (data- race fixes, DSA realtek leak fix, etc.) but not the sja1105 maintainer. Vladimir Oltean (maintainer) reviewed the patch.

### Step 3.5: Prerequisites
**Record:** No dependencies. Uses only to_dp->ds and ds already in scope. Applies cleanly to current tree code at lines 390–407.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original patch discussion
**Record:** b4 dig -c <commit> could not run — commit hash not present in local tree. b4 dig without -c requires stdin commit-ish. **WebFetch/lore.kernel.org blocked** (Anubis bot protection). Link tag points to msgid [email protected] but thread content **could not be retrieved**.

### Step 4.2: Reviewers
**Record:** **Reviewed-by: Vladimir Oltean** verified from commit message. Full recipient list from b4 dig -w **UNVERIFIED** (no commit hash available locally).

### Step 4.3: Bug reports
**Record:** No Reported-by: or syzbot links. No external bug report found.

### Step 4.4: Related patches/series
**Record:** Appears standalone; no series indicators in subject or local history.

### Step 4.5: Stable mailing list
**Record:** **UNVERIFIED** — lore stable search inaccessible.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key functions
**Record:** sja1105_cls_flower_add() modified; calls dsa_port_from_netdev(), sja1105_vl_redirect().

### Step 5.2: Callers
**Record:** Registered as ds->ops->cls_flower_add in sja1105_main.c:3234. Invoked from dsa_user_add_cls_flower() in net/dsa/user.c:1603 when userspace adds a TC flower classifier on a DSA user port.

### Step 5.3: Callees
**Record:** dsa_port_from_netdev() (net/dsa/dsa.c:1703) returns dsa_user_to_port(netdev) for any DSA user port in the tree — **not** restricted to the local switch. sja1105_vl_redirect() stores destports bitmask into flow rules and programs hardware via sja1105_init_virtual_links().

### Step 5.4: Call chain / reachability
**Record:** tc (userspace, typically root) → netlink TC offload → dsa_user_add_cls_flower() → sja1105_cls_flower_add() → FLOW_ACTION_REDIRECT path. **Reachable from userspace** on systems with CONFIG_NET_DSA_SJA1105 and multi-chip cascade topology.

### Step 5.5: Similar patterns
**Record:** Same driver already uses if (dp->ds != ds) continue; in sja1105_main.c:223 and :598 for cross-chip topology handling. SJA1110 variants explicitly set multiple_cascade_ports = true in sja1105_spi.c. No equivalent to_dp->ds != ds check found elsewhere in DSA flower redirect paths in this tree.

---

## PHASE 6: CROSS-REFERENCE AGAINST LOCAL TREE

### Step 6.1: Does buggy code exist?
**Record:** **YES.** Current tree at sja1105_flower.c:393-397 only checks IS_ERR(to_dp), not to_dp->ds != ds. Bug has existed since dfacc5a23e227 (2020).

### Step 6.2: Backport complications
**Record:** **Clean apply expected** — only 2 logical lines change in an unchanged code block. No recent refactoring conflicts in this hunk.

### Step 6.3: Related fixes already present?
**Record:** **NO** — grep for to_dp->ds != ds and "local switch port" in drivers/net/dsa/ returns no matches. Fix not yet in this tree.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

### Step 7.1: Subsystem criticality
**Record:** drivers/net/dsa/sja1105 — **PERIPHERAL** (niche automotive/industrial Ethernet switch driver, CONFIG_NET_DSA_SJA1105, SPI-managed). Critical for its users but not universal.

### Step 7.2: Subsystem activity
**Record:** Actively maintained — recent commits in 6.18 for SGMII, PTP, DT bindings, flower flag validation.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: Who is affected
**Record:** Users of NXP SJA1105/SJA1110 in **multi-chip cascaded DSA topologies** who install TC flower rules with FLOW_ACTION_REDIRECT to a port on a different chip. Config-specific (CONFIG_NET_DSA_SJA1105).

### Step 8.2: Trigger conditions
**Record:** Requires multi-chip sja1105 deployment + TC flower redirect to foreign-chip port. Uncommon globally, but **explicitly supported** hardware topology (multiple_cascade_ports). Triggerable by root via tc.

### Step 8.3: Failure mode severity
**Record:**
- **Primary:** Silent mis-programming — traffic steered to wrong local port(s). **HIGH** for affected deployments (network misdelivery in automotive TSN contexts).
- **Secondary:** Invalid destport bits when foreign index ≥ local num_ports (e.g., SJA1110 index on SJA1105 chip). Hardware undefined behavior; commit claims OOB — kernel memory OOB **not verified** (destports is u64, BIT() is safe for indices < 64), but invalid hardware destport mask is real.
- **Not:** kernel oops/panic (no evidence).

### Step 8.4: Risk-benefit
**Record:**
- **Benefit:** MEDIUM-HIGH for sja1105 multi-chip users — prevents accepting rules that corrupt switch forwarding tables.
- **Risk:** VERY LOW — 2-line validation, maintainer-reviewed, matches existing driver pattern.
- **Ratio:** Favorable for backport.

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence compile

**FOR backport:**
- Real, long-standing bug (since 2020) confirmed in 6.18.44 tree
- Minimal, obviously correct fix
- Reviewed by subsystem maintainer (Vladimir Oltean)
- Multi-chip cascade is an intended use case for SJA1110
- Same dp->ds != ds pattern already used elsewhere in driver
- Userspace-reachable via TC offload
- Wrong hardware programming → traffic misdelivery ("oh, that's not good" per stable rules)
- Changes silent misconfiguration to explicit, safe rejection

**AGAINST backport:**
- Niche driver / config (CONFIG_NET_DSA_SJA1105)
- No user reports, syzbot, or crash evidence
- Failure is forwarding misbehavior, not kernel crash/security
- Rare trigger (multi-chip + cross-chip redirect rule)

**UNRESOLVED:**
- Full lore review thread (blocked)
- Whether any reviewer nominated for stable
- Exact mainline commit SHA (not in local tree)

### Step 9.2: Stable rules checklist
1. Obviously correct and tested? **PASS** — logic is trivial; maintainer reviewed; no Tested-by.
2. Fixes a real bug affecting users? **PASS** — confirmed code path bug in supported topology.
3. Important issue? **PASS (moderate)** — hardware misprogramming / traffic misdelivery, not kernel crash.
4. Small and contained? **PASS** — 2-line logic change, one file.
5. No new features/APIs? **PASS** — validation only.
6. Can apply to local tree? **PASS** — buggy code present; clean apply expected.

### Step 9.3: Exception categories
**Record:** None (not device ID, quirk, DT, build, or docs). Qualifies as a hardware-driver correctness fix.

### Step 9.4: Decision rationale
For **this 6.18.y tree**, the buggy code is present and has been since flower redirect support landed. The driver explicitly supports multi- chip cascade topologies, making this a realistic misconfiguration path rather than a theoretical edge case. The fix is minimal, maintainer- reviewed, and consistent with existing cross-chip checks in the same driver. While the user population is small, silently programming wrong switch forwarding rules is a serious functional defect for those users. The fix only rejects invalid configurations that should never have been accepted.

---

## Verification

- **[Phase 1]** Parsed subject, tags, body from user-provided commit message
- **[Phase 2]** Read current sja1105_flower.c:390-407 — buggy code confirmed (only IS_ERR check)
- **[Phase 2]** Read sja1105_vl_redirect() — destports bitmask programmed to hardware
- **[Phase 2]** Read sja1105_static_config.h — SJA1105_NUM_PORTS=5, SJA1110_NUM_PORTS=11
- **[Phase 3]** git describe HEAD → v6.18.44-2-gc2044b1939218 / kernel 6.18.44
- **[Phase 3]** git blame -L 390,408 → redirect code from dfacc5a23e227 (2020-05-05)
- **[Phase 3]** git show dfacc5a23e227 — original flower redirect commit
- **[Phase 3]** git log --oneline -20 -- drivers/net/dsa/sja1105/sja1105_flower.c — no prior cross-chip fix
- **[Phase 4]** b4 dig -c HEAD — wrong commit; **UNVERIFIED** for this patch
- **[Phase 4]** WebFetch lore.kernel.org and patch.msgid.link — **FAILED** (bot protection)
- **[Phase 5]** grep sja1105_cls_flower_add — called via dsa_user_add_cls_flower() in net/dsa/user.c:1603
- **[Phase 5]** Read dsa_port_from_netdev() in net/dsa/dsa.c:1703-1709 — returns port for any DSA user netdev
- **[Phase 5]** grep "dp->ds != ds" in sja1105 — found at sja1105_main.c:223,598
- **[Phase 5]** grep multiple_cascade_ports — SJA1110 variants in sja1105_spi.c
- **[Phase 6]** grep "local switch port" / to_dp->ds in drivers/net/dsa — fix not present
- **[Phase 6]** Current tree lacks fix at lines 394-396
- **[Phase 7]** Read drivers/net/dsa/sja1105/Kconfig — driver scope confirmed
- **[Phase 8]** Assessed severity: forwarding misbehavior, not kernel crash
- **UNVERIFIED:** Lore discussion content, stable nomination, mainline commit hash, kernel-memory OOB (hardware destport misuse verified instead)

**YES**

 drivers/net/dsa/sja1105/sja1105_flower.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/net/dsa/sja1105/sja1105_flower.c +2 -2
index 05d8ed3121e7f..172fc163e1850 100644
@@ -391,9 +391,9 @@ int sja1105_cls_flower_add(struct dsa_switch *ds, int port,
 			struct dsa_port *to_dp;
 
 			to_dp = dsa_port_from_netdev(act->dev);
-			if (IS_ERR(to_dp)) {
+			if (IS_ERR(to_dp) || to_dp->ds != ds) {
 				NL_SET_ERR_MSG_MOD(extack,
-						   "Destination not a switch port");
+						   "Destination not a local switch port");
 				return -EOPNOTSUPP;
 			}
 
Signature · 1 line
2.53.0
author maintainer
#217 lore raw

PATCH 1/1 drm/amdgpu: flush pending RCU callbacks on module unload

In reply to Sasha Levin

From: Perry Yuan <[email protected]>

[ Upstream commit 67a654b41cfa73c3b83402c4a01b2689cad5b9bc ]

Call rcu_barrier() in module exit to wait for outstanding call_rcu() callbacks before freeing module text, preventing late callback execution in freed memory.

BUG: unable to handle page fault for address: ffffffffc1d59c40
PGD 6a12067 P4D 6a12067 PUD 6a14067 PMD 13698b067 PTE 0
Oops: 0010 [#1] SMP NOPTI
RIP: 0010:0xffffffffc1d59c40
Code: Unable to access opcode bytes at RIP 0xffffffffc1d59c16.
RSP: 0018:ffffc900198c0f28 EFLAGS: 00010286
RAX: ffffffffc1d59c40 RBX: ffff897c7d6b61c0 RCX: ffff88826aff4590
RDX: ffff8884d8b35490 RSI: ffffc900198c0f30 RDI: ffff88812af67290
RBP: 000000000000000a (DONE segment entries) R08: 0000000000000000 R09: 0000000000000100
R10: 0000000000000000 R11: ffffffff82a06100 R12: ffff88811a4e3700
R13: 0000000000000000 R14: ffff897c7d6b6270 R15: 0000000000000000
FS:  0000000000000000(0000) GS:ffff897c7d680000(0000) knlGS:0000000000000000
CS:  0010 DS: 0000 ES: 0000 CR0: 0000000080050033
CR2: ffffffffc1d59c16 CR3: 00000104a980a001 CR4: 0000000002770ee0
DR0: 0000000000000000 DR1: 0000000000000000 DR2: 0000000000000000
DR3: 0000000000000000 DR6: 00000000fffe07f0 DR7: 0000000000000400
PKRU: 55555554
Call Trace:
 <IRQ>
 ? rcu_do_batch+0x163/0x450
 ? rcu_core+0x177/0x1c0
 ? __do_softirq+0xc1/0x280
 ? asm_call_irq_on_stack+0xf/0x20
 </IRQ>
 ? do_softirq_own_stack+0x37/0x50
 ? irq_exit_rcu+0xc4/0x100
 ? sysvec_apic_timer_interrupt+0x36/0x80
 ? asm_sysvec_apic_timer_interrupt+0x12/0x20
 ? cpuidle_enter_state+0xd4/0x360
 ? cpuidle_enter+0x29/0x40
 ? cpuidle_idle_call+0x108/0x1a0
 ? do_idle+0x77/0xf0
 ? cpu_startup_entry+0x19/0x20
 ? secondary_startup_64_no_verify+0xbf/0xcb
(cherry picked from commit feaa5039f6c12acc9aa934c2d45dcd251a12c69f)

---

LLM Generated explanations, may be completely bogus:

The background check finished: feaa5039f6c12 is on mainline but not in stable/linux-6.18.y (about 1.37M commits ahead of the stable branch tip). A grep for "flush pending RCU" on the stable branch returned nothing, so this fix still needs to be backported.

That matches the earlier analysis: the bug is present in v6.18.44, the patch should apply cleanly at the end of amdgpu_exit(), and the backport recommendation remains **YES**.

 drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c | 8 ++++++++
 1 file changed, 8 insertions(+)
drivers/gpu/drm/amd/amdgpu/amdgpu_drv.c +8 -0
index 99f22633abf53..20e614db485cf 100644
@@ -3217,6 +3217,14 @@ static void __exit amdgpu_exit(void)
 	amdgpu_userq_fence_slab_fini();
 	mmu_notifier_synchronize();
 	amdgpu_xcp_drv_release();
+
+	/*
+	 * Flush outstanding call_rcu() callbacks before the
+	 * module text is freed.  Otherwise a grace period elapsing after
+	 * unload invokes a callback in already-freed module memory and
+	 * faults in rcu_do_batch().
+	 */
+	rcu_barrier();
 }
 
 module_init(amdgpu_init);
Signature · 1 line
2.53.0
author maintainer
#218 lore raw

PATCH 1/1 arm64/daifflags: Make local_daif_*() helpers __always_inline

In reply to Sasha Levin

From: Leonardo Bras <[email protected]>

[ Upstream commit 827ce94e0897a70241abf810b1d3d7d083053a39 ]

Make sure those helpers are always inlined and instrumentation safe.

---

LLM Generated explanations, may be completely bogus:

That check also confirms the fix is **not** in this tree: the latest daifflags-related commit is 8cb7eff32cc00 (PMR restore operations), and the -S'__always_inline void local_daif' search found no matches. Backport recommendation remains **YES**.

 arch/arm64/include/asm/daifflags.h | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
arch/arm64/include/asm/daifflags.h +5 -5
index 5fca480090434..795b351284673 100644
@@ -19,7 +19,7 @@
 
 
 /* mask/save/unmask/restore all exceptions, including interrupts. */
-static inline void local_daif_mask(void)
+static __always_inline void local_daif_mask(void)
 {
 	WARN_ON(system_has_prio_mask_debugging() &&
 		(read_sysreg_s(SYS_ICC_PMR_EL1) == (GIC_PRIO_IRQOFF |
@@ -38,7 +38,7 @@ static inline void local_daif_mask(void)
 	trace_hardirqs_off();
 }
 
-static inline unsigned long local_daif_save_flags(void)
+static __always_inline unsigned long local_daif_save_flags(void)
 {
 	unsigned long flags;
 
@@ -53,7 +53,7 @@ static inline unsigned long local_daif_save_flags(void)
 	return flags;
 }
 
-static inline unsigned long local_daif_save(void)
+static __always_inline unsigned long local_daif_save(void)
 {
 	unsigned long flags;
 
@@ -64,7 +64,7 @@ static inline unsigned long local_daif_save(void)
 	return flags;
 }
 
-static inline void local_daif_restore(unsigned long flags)
+static __always_inline void local_daif_restore(unsigned long flags)
 {
 	bool irq_disabled = flags & PSR_I_BIT;
 
@@ -124,7 +124,7 @@ static inline void local_daif_restore(unsigned long flags)
  * Called by synchronous exception handlers to restore the DAIF bits that were
  * modified by taking an exception.
  */
-static inline void local_daif_inherit(struct pt_regs *regs)
+static __always_inline void local_daif_inherit(struct pt_regs *regs)
 {
 	unsigned long flags = regs->pstate & DAIF_MASK;
 
Signature · 1 line
2.53.0
author maintainer
#219 lore raw

PATCH 1/1 ksmbd: mark invalid session responses as signed

In reply to Sasha Levin

From: Namjae Jeon <[email protected]>

[ Upstream commit 9e8ad620ddfde5a5f4ef58372e3805e9388cb0f4 ]

When a signed request uses a session that is not registered on the connection, ksmbd returns STATUS_USER_SESSION_DELETED before reaching the normal response signing path. The response therefore lacks SMB2_FLAGS_SIGNED.

Clients that require signing check this flag before handling STATUS_USER_SESSION_DELETED and replace the server status with STATUS_ACCESS_DENIED when it is absent. The protocol permits this error response to skip signature verification because the connection has no matching session key.

Preserve SMB2_FLAGS_SIGNED on the early error response when the request was signed. This lets the client propagate STATUS_USER_SESSION_DELETED. It fixes smb2.session.bind2.

---

LLM Generated explanations, may be completely bogus:

## Phase 1: Commit Message Forensics

### Step 1.1: Subject line
**Record:** [ksmbd] [mark] invalid session responses as signed — sets SMB2_FLAGS_SIGNED on early session-validation error responses when the request was signed.

### Step 1.2: Tags
**Record:**
- **Signed-off-by:** Namjae Jeon <[email protected]> (author)
- **Signed-off-by:** Steve French <[email protected]> (cifs/ksmbd maintainer)
- No Fixes:, Reported-by:, Tested-by:, Reviewed-by:, Acked-by:, Link:, or Cc: stable tags (expected for manual review)

### Step 1.3: Body analysis
**Record:**
- **Bug:** Signed request references a session not registered on the connection; smb2_check_user_session() fails early; server returns STATUS_USER_SESSION_DELETED without SMB2_FLAGS_SIGNED.
- **Symptom:** Signing-required clients check SMB2_FLAGS_SIGNED before honoring that status; missing flag → client reports STATUS_ACCESS_DENIED instead of the server’s real status.
- **Root cause:** Early goto send bypasses the normal signing path (work->sess is NULL, so set_sign_rsp() is never called).
- **Fix approach:** Set only SMB2_FLAGS_SIGNED (no signature bytes); protocol allows skipping verification when no session key exists on the connection.
- **Test reference:** smb2.session.bind2 (Samba protocol test suite).

### Step 1.4: Hidden bug fix?
**Record:** Yes — described as marking responses signed, but it fixes a real SMB protocol/interoperability bug: wrong client-visible error on signed session-binding paths.

---

## Phase 2: Diff Analysis

### Step 2.1: Inventory
**Record:**
- **Files:** fs/smb/server/server.c (+6 / -0)
- **Function:** __handle_ksmbd_work()
- **Scope:** Single-file, surgical fix in one error path

### Step 2.2: Code flow change
**Record:**
- **Hunk (session check failure, rc < 0):**
- **Before:** Set STATUS_INVALID_PARAMETER or STATUS_USER_SESSION_DELETED, goto send with unsigned response.
- **After:** If is_sign_req(work, get_cmd_val(work)), set SMB2_FLAGS_SIGNED on current response header via ksmbd_resp_buf_curr(), then goto send.
- **Path affected:** Early error path before __process_request() and before the work->sess && ... set_sign_rsp() block (lines 234–237).

### Step 2.3: Bug mechanism
**Record:** **Category:** Logic / protocol correctness on error path.
- Normal signing requires work->sess (lines 234–237).
- Invalid session → work->sess stays NULL → flag never set.
- Fix sets the flag without signing when the request was signed and no session key is available.

### Step 2.4: Fix quality
**Record:**
- Minimal, matches existing pattern in related ksmbd signing fixes (e.g. 1f12738, 3e67423 on mainline).
- Low regression risk: only touches error path; only sets a flag when request was signed.
- Uses get_cmd_val(work) (reads request header directly), not uninitialized local command (still 0 at this point).

---

## Phase 3: Git History Investigation

### Step 3.1: Blame
**Record:** Session-check early-exit block dates to merge 5d324e5159d9e (v6.18-rc8 era, Nov 2025). Bug has been present since this code structure landed in this tree.

### Step 3.2: Fixes: tag
**Record:** N/A — no Fixes: tag.

### Step 3.3: Related file history
**Record:** Recent server.c changes are crypto-library refactors and leak/loop fixes (74c2f0f, 51c5f7e, 71b5e7c, 6a37bc4). Related binding fixes exist in tree (a897064a45705 “do not expire session on binding failure”, 9feb2d1bf86d9). July 2026 signing series (1f12738, 3e67423, 4b70636, 9e8ad620) is **not** in this tree yet. This commit is standalone for its code path.

### Step 3.4: Author context
**Record:** Namjae Jeon is ksmbd maintainer; Steve French is cifs maintainer. Prior stable-nominated ksmbd fix in this tree:
8cabcb4dd3dc (refcount leak on invalid session lookup, `Cc:
[email protected]`).

### Step 3.5: Dependencies
**Record:** No series/prerequisite commits required. Uses existing APIs:
is_sign_req, get_cmd_val, ksmbd_resp_buf_curr, SMB2_FLAGS_SIGNED. Patch applies cleanly (git apply --check on GitHub .patch succeeded).

---

## Phase 4: Mailing List and External Research

### Step 4.1: Original discussion
**Record:** b4 dig -c 9e8ad620ddfde5a5f4ef58372e3805e9388cb0f4 — no lore match found. GitHub commit page confirms message and diff.

### Step 4.2: Reviewers
**Record:** b4 dig -w — no lore data. Committer is subsystem maintainer (Steve French).

### Step 4.3: Bug report
**Record:** No external bug report; validation reference is Samba test smb2.session.bind2. Related mainline commits from same author/date document the same signing-flag pattern for binding errors.

### Step 4.4: Related patches
**Record:** Part of a broader July 2026 ksmbd multichannel/signing fix set on mainline, but this patch is self-contained for the server.c early-session-check path.

### Step 4.5: Stable list history
**Record:** Lore blocked by bot protection; no stable-list discussion found. Precedent: other ksmbd session/binding fixes backported to stable in this tree.

---

## Phase 5: Code Semantic Analysis

### Step 5.1: Key functions
**Record:** __handle_ksmbd_work(), smb2_check_user_session(), smb2_is_sign_req(), get_smb2_cmd_val(), ksmbd_resp_buf_curr().

### Step 5.2: Callers
**Record:** __handle_ksmbd_work() ← handle_ksmbd_work() ← workqueue processing of incoming SMB requests (network I/O path for all ksmbd clients).

### Step 5.3: Callees
**Record:** On failure: check_user_session() → ksmbd_session_lookup_all(); fix calls is_sign_req() and sets response header flags.

### Step 5.4: Reachability
**Record:** Triggered by any signed SMB2/3 request with a session ID not registered on the connection — reachable from remote SMB clients (session binding / multichannel scenarios).

### Step 5.5: Similar patterns
**Record:** Same Flags |= SMB2_FLAGS_SIGNED without full signing in mainline binding-error fixes (3e67423, 1f12738). Normal signing still done via set_sign_rsp() when work->sess is valid (lines 234–237).

---

## Phase 6: Cross-Reference Against Local Tree

### Step 6.1: Buggy code present?
**Record:** **Yes.** Local tree is **6.18.44** (git describe HEAD → v6.18.44-1-g2736c32da98b9). Buggy code at fs/smb/server/server.c:189-198 — early goto send without setting signed flag. Commit 9e8ad620ddfde is **not** an ancestor of HEAD.

### Step 6.2: Backport complications
**Record:** **Clean apply** verified. No structural conflicts expected.

### Step 6.3: Related fixes already present?
**Record:** Binding-related fixes present (a897064a45705, 9feb2d1bf86d9). This specific signed-flag-on-early-session-error fix is **not** present.

---

## Phase 7: Subsystem and Maintainer Context

### Step 7.1: Subsystem criticality
**Record:** **fs/smb/server (ksmbd)** — IMPORTANT. Network file server; affects remote SMB clients, especially with mandatory signing.

### Step 7.2: Activity
**Record:** Actively maintained in 6.18.y (recent ksmbd security and binding fixes in this tree).

---

## Phase 8: Impact and Risk Assessment

### Step 8.1: Who is affected
**Record:** ksmbd users (CONFIG_SMB_SERVER) with SMB signing required and session binding/multichannel — enterprise and Windows-client environments.

### Step 8.2: Trigger conditions
**Record:** Signed request with session ID unknown on current connection (common in SMB multichannel binding). Remote-triggerable; not timing- dependent.

### Step 8.3: Failure mode severity
**Record:** Wrong error status (STATUS_ACCESS_DENIED vs STATUS_USER_SESSION_DELETED) → session binding failures, multichannel setup breakage, client disconnects. **Severity: MEDIUM** (functional/protocol, not kernel oops/corruption).

### Step 8.4: Risk-benefit
**Record:**
- **Benefit:** MEDIUM-HIGH for ksmbd + signing + multichannel users
- **Risk:** VERY LOW (+6 lines, error path only, flag-only change)
- **Ratio:** Favorable for stable

---

## Phase 9: Final Synthesis

### Step 9.1: Evidence summary

**FOR:**
- Real, reproducible protocol bug (Samba test smb2.session.bind2)
- Buggy code confirmed in 6.18.44 tree
- Small, obviously correct, applies cleanly
- Maintainer-authored and maintainer-committed
- Same signing-flag pattern as other accepted ksmbd stable fixes
- Affects remote SMB clients on a production server subsystem
- Precedent: ksmbd binding/session fixes already in this stable series

**AGAINST:**
- Not crash/security/data-corruption class
- Full smb2.session.bind2 pass may also need other mainline signing commits not yet in tree
- No lore review trail found via b4

**UNRESOLVED:**
- No mailing-list review thread found
- Exact production user reports not verified beyond Samba test reference

### Step 9.2: Stable rules checklist
1. Obviously correct and tested? **PASS** — logic is clear; Samba test cited; maintainer sign-off
2. Fixes real bug affecting users? **PASS** — wrong SMB status on signed requests
3. Important issue? **PASS (borderline)** — MEDIUM severity protocol/interop bug breaking session binding with signing
4. Small and contained? **PASS** — 6 lines, one file
5. No new features/APIs? **PASS** — flag on existing error path only
6. Can apply to local tree? **PASS** — verified clean apply

### Step 9.3: Exception categories
**Record:** None (not device ID, quirk, DT, build, or docs). Qualifies as protocol correctness bug fix.

### Step 9.4: Decision rationale
For **this 6.18.44 tree**, ksmbd is present with multichannel/binding support, the buggy early-exit path exists, and the fix is minimal and low-risk. Wrong STATUS_ACCESS_DENIED on signed session-binding errors breaks real SMB client interoperability — the same class of issue other ksmbd binding fixes have addressed in stable. Benefit outweighs risk.

---

## Verification

- [Phase 1] Parsed subject, tags, body from provided commit message and GitHub 9e8ad620ddfde
- [Phase 2] Read diff and fs/smb/server/server.c:163-254; traced signing path at lines 234-237
- [Phase 2] Read smb2_check_user_session() at smb2pdu.c:581-629 — returns -ENOENT when session not found
- [Phase 2] Read smb2_is_sign_req() at smb2pdu.c:9018-9028
- [Phase 3] git blame -L 188,238 fs/smb/server/server.c — block from 5d324e5159d9e
- [Phase 3] git merge-base --is-ancestor 9e8ad620ddfde HEAD → exit 1 (not in tree)
- [Phase 3] Related commits 1f12738, 3e67423, 4b70636 — all NOT in tree
- [Phase 3] git log --grep="Cc: stable" -- fs/smb/server/ — found 8cabcb4dd3dc precedent
- [Phase 4] b4 dig -c 9e8ad620ddfde — no lore match
- [Phase 4] GitHub API/commit page — confirmed author, message, +6/-0
- [Phase 5] get_smb2_cmd_val() at smb2pdu.c:227-236 reads from request buffer
- [Phase 5] Header chain: server.c → connection.h → ksmbd_work.h (ksmbd_resp_buf_curr); smb_common.h → common/smb2pdu.h (SMB2_FLAGS_SIGNED, struct smb2_hdr)
- [Phase 6] git describe HEAD → v6.18.44; make kernelversion → 6.18.44
- [Phase 6] Buggy code present at lines 189-198 (no signed flag on early error)
- [Phase 6] curl .../9e8ad620....patch | git apply --check → success
- [Phase 7] Multichannel binding code present in smb2pdu.c:1734+
- [Phase 8] Failure mode: wrong SMB status, session binding breakage — MEDIUM severity

**YES**The background check finished: none of the related July 2026 ksmbd signing/binding commits are in this **6.18.44** tree yet:

- 9e8ad620ddfde — mark invalid session responses as signed (the candidate)
- 1f12738b0ed7 — sign rejected SMB2.1 session binding responses
- 3e67423336f0 — mark rejected cross-dialect bindings as signed
- 4b706360ffb7 — fix multichannel binding and enforce channel limit

The buggy early-exit path in fs/smb/server/server.c is still present here, and the candidate patch applies cleanly. That supports backporting **9e8ad620** on its own; passing smb2.session.bind2 end-to-end may still need the other three mainline fixes.

 fs/smb/server/server.c | 6 ++++++
 1 file changed, 6 insertions(+)
fs/smb/server/server.c +6 -0
index c729d47f9932b..e70ea8ef1deb8 100644
@@ -195,6 +195,12 @@ static void __handle_ksmbd_work(struct ksmbd_work *work,
 				else
 					conn->ops->set_rsp_status(work,
 						STATUS_USER_SESSION_DELETED);
+				if (conn->ops->is_sign_req(work, conn->ops->get_cmd_val(work))) {
+					struct smb2_hdr *rsp_hdr;
+
+					rsp_hdr = ksmbd_resp_buf_curr(work);
+					rsp_hdr->Flags |= SMB2_FLAGS_SIGNED;
+				}
 				goto send;
 			} else if (rc > 0) {
 				rc = conn->ops->get_ksmbd_tcon(work);
Signature · 1 line
2.53.0
author maintainer
#220 lore raw

PATCH 1/1 media: chips-media: wave5: Add range checks for dec_output_info

In reply to Sasha Levin

From: Ricardo Ribalda <[email protected]>

[ Upstream commit 79aef69bb0903616f4867f0168aea717a11c439c ]

If the driver's dec_output_info contains invalid data the driver can write in invalid memory. Add a range check for that.

This fixes this smatch error:
drivers/media/platform/chips-media/wave5/wave5-vpuapi.c:588 wave5_vpu_dec_get_output_info() error: buffer overflow 'inst->frame_buf' 64 <= 127

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: media: chips-media: wave5: Add range checks for dec_output_info

**Local tree:** Linux **6.18.43** (v6.18.43-1-gc7f0dac02d232, branch stable/linux-6.18.y)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Subject Line
**Record:** [media: chips-media: wave5] [Add] — Add range checks for dec_output_info in the Wave5 VPU decoder driver.

### Step 1.2: Tags
**Record:**
- **Signed-off-by:** Ricardo Ribalda <[email protected]> (author)
- **Reviewed-by:** Nicolas Dufresne <[email protected]> (media subsystem reviewer)
- **Signed-off-by:** Hans Verkuil <[email protected]> (media maintainer)
- **No** Fixes:, Reported-by:, Tested-by:, Link:, or Cc: stable@ in the commit message itself
- Part of series [PATCH v4 4/6] media: Fix new smatch warnings; cover letter CC'd [email protected] and Greg Kroah-Hartman

### Step 1.3: Body Analysis
**Record:**
- **Bug:** dec_output_info can contain invalid index data; driver indexes inst->frame_buf[] without validating the computed index.
- **Symptom:** Out-of-bounds access on inst->frame_buf (smatch:
buffer overflow 'inst->frame_buf' 64 <= 127).
- **Root cause:** Existing check bounds index_frame_display against max_dec_index, but the actual index is num_of_decoding_fbs + index_frame_display (fb_offset), which can exceed MAX_REG_FRAME (64).

### Step 1.4: Hidden Bug Fix?
**Record:** Yes — despite smatch-driven origin, this is a real bounds- check bug fix, not cosmetic cleanup. The commit message explicitly states invalid data can cause invalid memory access.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Inventory
**Record:**
- **File:** drivers/media/platform/chips-media/wave5/wave5-vpuapi.c (+9 / -2 lines)
- **Function:** wave5_vpu_dec_get_output_info()
- **Scope:** Single-file, surgical fix

### Step 2.2: Code Flow Change
**Record:**
- **Before:** info->disp_frame = inst->frame_buf[val + info->index_frame_display] when index_frame_display < max_dec_index.
- **After:** Computes idx = val + info->index_frame_display, validates idx < MAX_REG_FRAME, returns -EINVAL on failure, then assigns inst->frame_buf[idx].
- **Path:** Normal decode output-info retrieval after firmware query.

### Step 2.3: Bug Mechanism
**Record:** **Buffer overflow / out-of-bounds access (memory safety).** frame_buf has MAX_REG_FRAME (64) elements. Index uses fb_offset (num_of_decoding_fbs) plus display index from firmware, but only the display index was bounded — not the sum. Smatch correctly identified index up to 127.

### Step 2.4: Fix Quality
**Record:** Obviously correct; matches existing patterns in the same file (reset_auxiliary_buffers() line 189, wave5_vpu_dec_reset_framebuffer() line 626). Minimal, uses existing err_out path. Low regression risk.

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame
**Record:** Buggy line introduced when wave5-vpuapi.c entered this tree (commit 5d324e5159d9e, Nov 2025). Present since Wave5 driver landed in 6.18.

### Step 3.2: Fixes: Tag
**Record:** N/A — no Fixes: tag in commit message.

### Step 3.3: File History
**Record:** Wave5 driver has had multiple stable-worthy fixes in 6.18.y (panics, memory leaks, spinlock issues). This fix is not yet in the tree. Part of a 6-patch smatch series, but each patch touches a different file — **standalone**.

### Step 3.4: Author Context
**Record:** Ricardo Ribalda is an active media contributor (Chromium). Hans Verkuil merged; Nicolas Dufresne reviewed.

### Step 3.5: Dependencies
**Record:** None. Patch 4/6 is self-contained; MAX_REG_FRAME and err_out already exist in this tree. No prerequisite commits required.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original Discussion
**Record:** Series cover at https://lists.openwall.net/linux-
kernel/2026/05/07/2079. Patch v4 submitted May 7, 2026; evolved v1→v4. v2 note: removed WARN_ON() from user-triggerable paths; this patch retains WARN_ON() because invalid data comes from firmware/hardware registers, not direct userspace input.

### Step 4.2: Reviewers
**Record:** Cover CC'd Mauro Chehab, Hans Verkuil, Greg Kroah-Hartman, linux-media@, stable@. Reviewed-by from Nicolas Dufresne; merged by Hans Verkuil.

### Step 4.3: Bug Report
**Record:** Smatch static analysis finding; no syzbot or user crash report. Cover letter classifies some warnings as "inoffensive" but includes fixes for user-triggerable errors; this wave5 issue is a genuine missing bounds check.

### Step 4.4: Related Patches
**Record:** Series has 5 other independent patches (v4l2-dev, mt9p031, adv7604, ipu3-imgu, amlogic-c3). None required for this fix.

### Step 4.5: Stable List
**Record:** Cover letter explicitly CC'd [email protected]. No objection found in available thread excerpts.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key Functions
**Record:** wave5_vpu_dec_get_output_info() modified.

### Step 5.2: Callers
**Record:**
- wave5-vpu-dec.c:354 — wave5_vpu_dec_finish_decode() (normal decode completion)
- wave5-vpu-dec.c:1407 — flush/stop path
- wave5-vpu-dec.c:1499 — another decode path
- wave5-vpuapi.c:82 — busy-retry during instance flush

All are active V4L2 mem2mem decode paths.

### Step 5.3: Callees
**Record:** Calls wave5_vpu_dec_get_result() which reads W5_RET_DEC_DISPLAY_INDEX from VPU hardware (line 1059–1060 in wave5-hw.c). index_frame_display is firmware-provided.

### Step 5.4: Reachability
**Record:** Reachable during video decode on systems with CONFIG_VIDEO_WAVE_VPU (ARCH_K3 or COMPILE_TEST). Users with access to /dev/video* can trigger decode operations; malformed streams or firmware edge cases can produce bad indices.

### Step 5.5: Similar Patterns
**Record:** Same file already bounds-checks index >= MAX_REG_FRAME in reset_auxiliary_buffers() and wave5_vpu_dec_reset_framebuffer(). This fix closes a gap in wave5_vpu_dec_get_output_info().

---

## PHASE 6: CROSS-REFERENCE WITH LOCAL TREE

### Step 6.1: Buggy Code Present? **Record:** **Yes.** At lines 561–563 in this tree:

```561:563:drivers/media/platform/chips-media/wave5/wave5-vpuapi.c
        if (info->index_frame_display >= 0 &&
            info->index_frame_display < (int)max_dec_index)
                info->disp_frame = inst->frame_buf[val +
info->index_frame_display];
```

Fix is **not** yet applied. Wave5 driver present since 6.18.

### Step 6.2: Backport Complications
**Record:** Clean apply expected — 9-line hunk, no structural conflicts. MAX_REG_FRAME defined as WAVE5_MAX_FBS * 2 (= 64) in wave5-vpuapi.h:47.

### Step 6.3: Related Fixes Already Present?
**Record:** No equivalent bounds check for this access path. Other wave5 stable fixes exist but not this one.

---

## PHASE 7: SUBSYSTEM CONTEXT

### Step 7.1: Subsystem
**Record:** drivers/media/platform/chips-media/wave5/ — V4L2 hardware video codec driver. **Criticality: IMPORTANT** (peripheral driver, but memory-safety bugs in kernel drivers are serious).

### Step 7.2: Activity
**Record:** Actively maintained in 6.18.y with multiple bugfix commits since initial merge.

---

## PHASE 8: IMPACT AND RISK

### Step 8.1: Who Is Affected
**Record:** Users of TI K3 (and COMPILE_TEST) systems with Chips&Media Wave5 VPU (CONFIG_VIDEO_WAVE_VPU). Not universal, but real production hardware.

### Step 8.2: Trigger Conditions
**Record:** During decode when firmware returns display index data that passes the incomplete max_dec_index check but produces idx >= MAX_REG_FRAME. Possible with firmware edge cases, resolution changes, or error recovery. Not every boot, but reachable in normal decode operation.

### Step 8.3: Failure Mode
**Record:** Out-of-bounds read of struct frame_buffer from kernel stack/static data → kernel oops/panic or memory corruption. **Severity:
HIGH** (memory safety in kernel context).

### Step 8.4: Risk-Benefit
**Record:**
- **Benefit:** HIGH for affected hardware — prevents OOB kernel memory access
- **Risk:** VERY LOW — 7-line bounds check, consistent with existing code, reviewed by subsystem maintainer
- **Ratio:** Strongly favors backport

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence Summary

**FOR backport:**
- Real out-of-bounds array access bug (smatch-verified)
- Fixes potential kernel crash/memory corruption
- Small, surgical, obviously correct
- Reviewed by Nicolas Dufresne; merged by Hans Verkuil
- Standalone — no series dependencies
- Buggy code exists in this 6.18.43 tree; fix not yet applied
- Cover letter CC'd stable@
- Consistent with existing MAX_REG_FRAME checks in same driver

**AGAINST backport:**
- Driver is platform-specific (K3), not all users affected
- Trigger requires firmware returning bad index data (not directly proven in field)
- Smatch-driven, not syzbot/user-reported crash
- Retains WARN_ON() (acceptable for firmware-provided data per series rationale)

**Unresolved:** No runtime crash report verified; impact inferred from static analysis and code review.

### Step 9.2: Stable Rules Checklist
1. Obviously correct and tested? **PASS** — logic is clear; Reviewed-by present; smatch warning resolved
2. Fixes a real bug? **PASS** — missing bounds check on kernel array access
3. Important issue? **PASS** — OOB kernel memory access (HIGH severity)
4. Small and contained? **PASS** — 1 file, ~9 lines
5. No new features/APIs? **PASS** — defensive bounds check only
6. Can apply to local tree? **PASS** — driver and all symbols exist; clean apply expected

### Step 9.3: Exception Category
**Record:** Not a device ID/quirk/DT/build/docs exception — standard memory-safety bug fix.

### Step 9.4: Decision Rationale
This commit closes a genuine bounds-check gap in wave5_vpu_dec_get_output_info(). The Wave5 driver exists in Linux 6.18.y, the buggy code is present, and the fix is minimal, reviewed, and standalone. For users decoding video on K3 hardware with the Wave5 VPU, an out-of-bounds access on inst->frame_buf[] can cause kernel crashes or memory corruption. The fix aligns with existing MAX_REG_FRAME checks elsewhere in the driver and carries negligible regression risk.

---

## Verification

- [Phase 1] Parsed subject, tags: Reviewed-by Nicolas Dufresne, SOB Hans Verkuil; no Fixes/Reported-by
- [Phase 1] Commit body: smatch OOB on inst->frame_buf 64 <= 127
- [Phase 2] Diff: +9/-2 in wave5_vpu_dec_get_output_info(), adds idx bounds check against MAX_REG_FRAME
- [Phase 3] git describe HEAD: v6.18.43-1-gc7f0dac02d232 (6.18.43)
- [Phase 3] git blame: buggy line from driver introduction in this tree
- [Phase 3] No Fixes: tag; no prerequisite commits identified
- [Phase 3] git log --oneline -20 -- wave5-vpuapi.c: multiple wave5 fixes; this one not present
- [Phase 4] Cover letter at lists.openwall.net/2026/05/07/2079: series v4, CC stable@, 6 independent patches
- [Phase 4] b4 dig failed (commit not in local repo); used web search/lkml archives instead
- [Phase 4] v2 series note: WARN_ON kept for non-user-triggerable paths
- [Phase 5] Callers verified via grep: wave5-vpu-dec.c:354,1407,1499, wave5-vpuapi.c:82
- [Phase 5] wave5_vpu_dec_get_result(): index_frame_display from W5_RET_DEC_DISPLAY_INDEX hardware register
- [Phase 5] MAX_REG_FRAME = 64 (WAVE5_MAX_FBS * 2), frame_buf[MAX_REG_FRAME] at wave5-vpuapi.h:808
- [Phase 6] Buggy code confirmed at lines 561–563; fix not applied
- [Phase 6] CONFIG_VIDEO_WAVE_VPU depends on ARCH_K3 || COMPILE_TEST per Kconfig
- [Phase 6] num_of_decoding_fbs validated < WAVE5_MAX_FBS at registration (line 305), but OOB path doesn't validate sum
- [Phase 8] Failure mode: OOB read → kernel memory safety issue, severity HIGH

**YES**

 .../media/platform/chips-media/wave5/wave5-vpuapi.c   | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
drivers/media/platform/chips-media/wave5/wave5-vpuapi.c +9 -2
index e94d6ebc9f816..e7ea2f6a99d5b 100644
@@ -559,8 +559,15 @@ int wave5_vpu_dec_get_output_info(struct vpu_instance *inst, struct dec_output_i
 		p_dec_info->num_of_decoding_fbs : p_dec_info->num_of_display_fbs;
 
 	if (info->index_frame_display >= 0 &&
-	    info->index_frame_display < (int)max_dec_index)
-		info->disp_frame = inst->frame_buf[val + info->index_frame_display];
+	    info->index_frame_display < (int)max_dec_index) {
+		u32 idx = val + info->index_frame_display;
+
+		if (WARN_ON(idx >= MAX_REG_FRAME)) {
+			ret = -EINVAL;
+			goto err_out;
+		}
+		info->disp_frame = inst->frame_buf[idx];
+	}
 
 	info->rd_ptr = p_dec_info->stream_rd_ptr;
 	info->wr_ptr = p_dec_info->stream_wr_ptr;
Signature · 1 line
2.53.0
author maintainer
#221 lore raw

PATCH 1/1 ALSA: hda/ca0132: add QUIRK_GENERIC path for Gigabyte GA-Z170X-Gaming G1

In reply to Sasha Levin

From: Ezio Galeazzi <[email protected]>

[ Upstream commit e79615b05c78d19b085c8eb7971c82cb5b0f22d1 ]

Some CA0132 implementations (e.g. Gigabyte GA-Z170X-Gaming G1) produce white noise when using the DSP firmware path. Add a QUIRK_GENERIC path that uses the standard HDA generic parser instead, with custom pin configs.
This patch applies against v6.18.24.

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: ALSA hda/ca0132 QUIRK_GENERIC for Gigabyte GA-Z170X-Gaming G1

**Local tree:** Linux **6.18.43** (git describe HEAD → v6.18.43-1-gc7f0dac02d232)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Subject Line
**Record:** [ALSA: hda/ca0132] [add] — Add a QUIRK_GENERIC hardware quirk path for Gigabyte GA-Z170X-Gaming G1 motherboard audio.

### Step 1.2: Commit Message Tags
**Record:**

| Tag | Value |
|-----|-------|
| Signed-off-by | Ezio Galeazzi \<[email protected]\> (author) |
| Link |
https://lore.kernel.org/[email protected] |
| Signed-off-by | Takashi Iwai \<[email protected]\> (ALSA/HDA maintainer) |
| Fixes: | **Absent** (expected for manual review) |
| Reported-by: | **Absent** |
| Cc: stable | **Absent** (expected) |
| Tested-by / Reviewed-by / Acked-by | **Absent** |

**Notable:** Takashi Iwai's Signed-off-by is a strong maintainer-quality signal. No syzbot or sanitizer reports.

### Step 1.3: Commit Body Analysis
**Record:**
- **Bug:** CA0132 codec on Gigabyte GA-Z170X-Gaming G1 produces **white noise** when using the DSP firmware path.
- **Symptom:** Unusable/broken analog audio output (white noise instead of proper sound).
- **Fix approach:** Route this board through QUIRK_GENERIC, using the standard HDA generic parser with custom pin configs instead of the DSP path.
- **Version note:** "This patch applies against v6.18.24."
- **Root cause (author):** This specific CA0132 implementation is incompatible with the DSP firmware path.

### Step 1.4: Hidden Bug Fix Detection
**Record:** Yes — despite "add" in the subject, this is a **hardware quirk workaround** fixing a real user-visible audio malfunction. Falls under the stable exception category for audio codec quirks.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Change Inventory
**Record:**

| File | Changes |
|------|---------|
| `sound/hda/codecs/Kconfig` | +1 line: `select SND_HDA_GENERIC` for
`SND_HDA_CODEC_CA0132` |
| `sound/hda/codecs/ca0132.c` | ~+120 / ~-30 lines |

**Functions modified/added:**
- ca0132_generic_init_hook() — **new**
- ca0132_generic_probe() — **new**
- ca0132_codec_remove() — extended switch
- ca0132_codec_probe() — early return for QUIRK_GENERIC
- ca0132_codec_build_controls/pcms/init() — dispatch to generic helpers
- ca0132_codec_suspend() — early return for generic quirk

**Scope:** Single-driver, surgical hardware quirk addition.

### Step 2.2: Code Flow Changes
**Record:**

| Hunk | Before → After |
|------|----------------|
| Kconfig | CA0132 build did not pull in generic parser → now selects
`SND_HDA_GENERIC` |
| `ca0132_spec` | No generic spec → embeds `struct hda_gen_spec gen` |
| Quirk table | No entry for `0x1458:0xA046` → `QUIRK_GENERIC` for
Gaming G1 |
| Pin configs | None for G1 → `ca0132_generic_pincfgs[]` with board-
specific values |
| Probe | All boards take full DSP path → Gaming G1 early-returns into
`ca0132_generic_probe()` |
| Lifecycle ops | All use DSP builders → Gaming G1 uses `snd_hda_gen_*`
helpers |

**Affected path:** Probe/init of CA0132 codec on PCI subsystem ID 0x1458:0xA046 only.

### Step 2.3: Bug Mechanism
**Record:**
- **Category:** Hardware quirk / workaround (audio codec)
- **Mechanism:** Without the quirk, board 0x1458:0xA046 is unmatched in ca0132_quirks[], falls through to default QUIRK_NONE handling, loads DSP firmware path, and produces white noise. Fix bypasses DSP entirely for this board, using the proven HDA generic auto-parser with hand-tuned pin configurations.

### Step 2.4: Fix Quality Assessment
**Record:**
- **Obviously correct:** Yes — follows established patterns (ca0110.c, via.c, sigmatel.c all embed hda_gen_spec and use generic parser).
- **Minimal:** Focused on one PCI ID; switch-dispatch pattern mirrors existing QUIRK_ZXR_DBPRO handling.
- **Regression risk:** Low — only affects the newly matched 0x1458:0xA046 device. Other quirk paths unchanged.
- **Minor concern:** struct hda_gen_spec gen is embedded in ca0132_spec for all CA0132 instances (slightly larger allocation), but only used on the generic quirk path. Common pattern in other HDA codec drivers.

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame
**Record:** git blame on quirk table lines 1304–1307 attributes all entries to commit a112b91dd6349 (unrelated sunrpc commit title), indicating this checkout has **flattened/squashed history**. The Gigabyte Gaming 7 entry (0x1458:0xA036, QUIRK_R3DI) is present; Gaming G1 (0xA046) is **not**.

### Step 3.2: Fixes: Tag
**Record:** N/A — no Fixes: tag present.

### Step 3.3: File History
**Record:** git log --oneline -- sound/hda/codecs/ca0132.c returns only one commit due to flattened history. Cannot trace when individual quirk entries were introduced. The CA0132 driver and Gigabyte QUIRK_R3DI entries are present in the current tree.

### Step 3.4: Author History
**Record:** git log --author="Galeazzi" returns empty — author history not available in this repo.

### Step 3.5: Dependencies
**Record:** **Standalone.** Uses existing in-tree APIs:
- generic.h, snd_hda_gen_spec_init(), snd_hda_gen_parse_auto_config(), snd_hda_gen_build_controls/pcms/init(), snd_hda_gen_remove()
- Existing ca0132_init_chip(), ca0132_prepare_verbs()
- No multi-patch series indicated.

**Minor apply note:** Patch targets v6.18.24; local tree is v6.18.43. Probe uses kzalloc(sizeof(*spec), GFP_KERNEL) here (patch context may differ slightly) — expect clean or near-clean apply.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original Discussion
**Record:** Lore URL from commit Link tag blocked by Anubis bot protection (WebFetch and curl both failed). b4 dig without commit hash also failed. **Could not retrieve mailing list thread.**

### Step 4.2: Reviewers
**Record:** UNVERIFIED — b4 dig -w not run (no commit hash available in this repo).

### Step 4.3: Bug Report
**Record:** No external bug report linked. Bug described in commit message only (white noise on Gaming G1).

### Step 4.4: Related Patches
**Record:** UNVERIFIED — could not access lore for series context. Patch appears self-contained (not labeled "patch X/Y").

### Step 4.5: Stable List History
**Record:** UNVERIFIED — lore inaccessible.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key Functions
**Record:** ca0132_generic_probe, ca0132_codec_probe, ca0132_codec_remove, ca0132_codec_build_controls, ca0132_codec_build_pcms, ca0132_codec_init, ca0132_codec_suspend.

### Step 5.2: Callers
**Record:** All modified functions are hda_codec_ops callbacks, invoked by the HDA core during codec probe, control/PCM construction, init, suspend, and remove — standard device enumeration path on systems with CA0132 codec.

### Step 5.3: Callees
**Record:** Generic path calls snd_hda_gen_spec_init, snd_hda_apply_pincfgs, ca0132_init_chip, ca0132_prepare_verbs, snd_hda_parse_pin_def_config, snd_hda_gen_parse_auto_config, snd_hda_gen_build_controls/pcms/init, snd_hda_gen_remove. All verified present in tree.

### Step 5.4: Reachability
**Record:**

```
HDA bus probe → ca0132_codec_probe() → snd_hda_pick_fixup() matches
0x1458:0xA046
  → ca0132_generic_probe() → generic audio path (no DSP)
```

Triggered at boot/module load on affected hardware. Not userspace- triggerable, but affects every boot for owners of this motherboard.

### Step 5.5: Similar Patterns
**Record:** ca0110.c uses identical generic-parser pattern. Multiple codecs (via.c, sigmatel.c, conexant.c, realtek.c) embed struct hda_gen_spec gen in their spec structs. CA0132 already has Gigabyte boards on QUIRK_R3DI (DSP path); this board specifically needs the generic bypass.

---

## PHASE 6: CROSS-REFERENCE AGAINST LOCAL TREE (6.18.43)

### Step 6.1: Does Buggy Code Exist?
**Record:** **YES.** sound/hda/codecs/ca0132.c exists with full CA0132 DSP driver. Quirk table has Gaming 7 (0xA036 → QUIRK_R3DI) but **no entry for Gaming G1 (0xA046)**. QUIRK_GENERIC enum value does not exist. Without fix, Gaming G1 uses default DSP path → white noise per commit message.

### Step 6.2: Backport Complications
**Record:** **Clean apply expected.** All target files and APIs exist. Kconfig change is one line. Probe reordering (moving pcm_format_first before quirk detection) is minor. No structural refactoring in 6.18.43 that would block this patch.

### Step 6.3: Related Fixes Already Present?
**Record:** **No.** Grep for QUIRK_GENERIC, 0xA046, and Gaming G1 in sound/hda/codecs/ returns no matches. Fix not yet applied.

---

## PHASE 7: SUBSYSTEM CONTEXT

### Step 7.1: Subsystem and Criticality
**Record:** sound/hda/codecs — ALSA HD-Audio codec driver. **IMPORTANT** (affects audio on specific hardware; not core kernel, but HDA is widely used).

### Step 7.2: Subsystem Activity
**Record:** CA0132 driver is mature with extensive quirk infrastructure. Git history unavailable for activity assessment due to flattened repo.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: Who Is Affected
**Record:** **Hardware-specific** — owners of Gigabyte GA-Z170X-Gaming G1 motherboards (PCI SSID 0x1458:0xA046) with onboard Creative CA0132 audio. Requires CONFIG_SND_HDA_CODEC_CA0132.

### Step 8.2: Trigger Conditions
**Record:** Every boot when HDA codec probes on this motherboard. **Highly reproducible** for affected hardware. Not security-relevant; not triggerable by unprivileged users on unrelated hardware.

### Step 8.3: Failure Mode Severity
**Record:**
- **Failure mode:** White noise on audio output (DSP path broken on this board)
- **Severity:** **MEDIUM** — functional audio defect making onboard sound unusable, but not a crash, deadlock, data corruption, or security issue

### Step 8.4: Risk-Benefit Ratio
**Record:**

| | Assessment |
|---|------------|
| **Benefit** | Restores working audio on a specific but real hardware
platform |
| **Risk** | Low — isolated to one new PCI quirk match; uses well-tested
generic parser infrastructure; maintainer-signed |
| **Ratio** | Favorable for stable — classic hardware quirk with minimal
blast radius |

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence Summary

**FOR backport:**
- Fixes real, reproducible white-noise audio bug on Gigabyte GA-Z170X-Gaming G1
- Hardware quirk — explicit stable exception category
- Small, contained, single-driver change
- Takashi Iwai (maintainer) Signed-off-by
- Uses existing in-tree generic parser infrastructure (proven pattern)
- Buggy code path exists in this 6.18.43 tree; fix not yet applied
- No new userspace APIs

**AGAINST backport:**
- Not a crash/security/corruption issue — audio quality/functionality only
- Affects one specific older motherboard model (~2016 Z170 era)
- Slightly increases ca0132_spec size for all CA0132 instances
- Mailing list review discussion could not be verified

**Unresolved:**
- Full lore review thread inaccessible
- Whether reviewers explicitly nominated for stable

### Step 9.2: Stable Rules Checklist

| Criterion | Result |
|-----------|--------|
| 1. Obviously correct and tested? | **PASS** — maintainer SOB; pattern
matches other HDA codecs; logic is straightforward |
| 2. Fixes a real bug affecting users? | **PASS** — white noise makes
audio unusable on Gaming G1 |
| 3. Important issue? | **PASS** (borderline) — functional audio
failure, not crash/security; hardware quirk fixes are routinely accepted
|
| 4. Small and contained? | **PASS** — ~150 lines, 2 files, one driver |
| 5. No new features/APIs? | **PASS** — hardware quirk workaround using
existing generic parser |
| 6. Can apply to local tree? | **PASS** — all prerequisites present in
6.18.43 |

### Step 9.3: Exception Category
**Record:** **Hardware quirk/workaround** for broken CA0132 DSP implementation on a specific motherboard — automatically qualifies per stable rules.

### Step 9.4: Decision Rationale

For Linux **6.18.y**, the CA0132 driver is present and the Gigabyte GA-Z170X-Gaming G1 (0x1458:0xA046) has no quirk entry, leaving it on the broken DSP path. This patch adds a targeted hardware quirk that routes the board through the standard HDA generic parser — the same approach used by other codec drivers and explicitly encouraged for stable trees. The fix is maintainer-signed, self-contained, low-risk, and restores working audio for affected users.

---

## Verification

- [Phase 1] Parsed subject, tags: Ezio Galeazzi SOB, Takashi Iwai SOB, Link to lore; no Fixes/Reported-by/Cc:stable
- [Phase 2] Diff analysis: 2 files, ~150 lines; new QUIRK_GENERIC path with pin configs and generic parser dispatch
- [Phase 3] git describe HEAD: v6.18.43; git blame ca0132.c:1304-1307 shows Gigabyte entries present, 0xA046 absent
- [Phase 3] git log -- sound/hda/codecs/ca0132.c: only one commit (flattened history — limited investigation)
- [Phase 3] Grep prerequisites: generic.h, all snd_hda_gen_* APIs exist in tree
- [Phase 4] WebFetch lore URL: **FAILED** (Anubis bot protection)
- [Phase 4] curl lore raw: **FAILED** (same)
- [Phase 4] b4 dig: **FAILED** (no commit hash in repo)
- [Phase 5] Grep callers: functions are hda_codec_ops callbacks — standard probe path
- [Phase 5] Similar pattern verified in ca0110.c, via.c, sigmatel.c
- [Phase 6] Grep QUIRK_GENERIC/0xA046/Gaming G1 in sound/hda: **no matches** — fix not present
- [Phase 6] ca0132.c quirk table: Gaming 7 at 0xA036 present, Gaming G1 at 0xA046 absent
- [Phase 6] Kconfig: SND_HDA_CODEC_CA0132 does not yet select SND_HDA_GENERIC
- [Phase 8] Failure mode: white noise on audio — MEDIUM severity, hardware-specific
- UNVERIFIED: Mailing list reviewer feedback and stable nominations
- UNVERIFIED: Whether author tested on physical hardware (no Tested-by tag)

**YES**

 sound/hda/codecs/Kconfig  |   1 +
 sound/hda/codecs/ca0132.c | 111 +++++++++++++++++++++++++++++++++-----
 2 files changed, 99 insertions(+), 13 deletions(-)
sound/hda/codecs/Kconfig +1 -0
index addbc94243365..dcf340e5a0c1a 100644
@@ -69,6 +69,7 @@ comment "Set to Y if you want auto-loading the codec driver"
 
 config SND_HDA_CODEC_CA0132
 	tristate "Build Creative CA0132 codec support"
+	select SND_HDA_GENERIC
 	help
 	  Say Y or M here to include Creative CA0132 codec support in
 	  snd-hda-intel driver.
sound/hda/codecs/ca0132.c +98 -13

198 lines not on this page · raw message

Signature · 1 line
2.53.0
author maintainer
#222 lore raw

PATCH 1/1 ACPICA: Fix condition check in acpi_ps_parse_loop()

In reply to Sasha Levin

From: ikaros <[email protected]>

[ Upstream commit 8de27e2d83c0d07ae9443c6304575b0609394bfd ]

Fix condition check for AML_ELSE_OP in acpi_ps_parse_loop() to prevent out-of-bounds access.

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: ACPICA Fix condition check in acpi_ps_parse_loop()

**Local tree:** stable/linux-6.18.y at v6.18.44 (Makefile: 6.18.44)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Subject Line
**Record:** [ACPICA] [Fix] — correct the AML_ELSE_OP condition check in acpi_ps_parse_loop() to prevent out-of-bounds access.

### Step 1.2: Commit Message Tags
**Record:**
- **Link:** https://github.com/acpica/acpica/commit/3b537b92336e
(upstream ACPICA commit)
- **Signed-off-by:** ikaros <[email protected]> (author)
- **Signed-off-by:** Rafael J. Wysocki <[email protected]> (ACPI maintainer)
- **Link:** https://patch.msgid.link/[email protected]
(kernel submission; could not fetch — Anubis bot protection)
- No Fixes:, Reported-by:, Cc: [email protected], Tested- by:, or Reviewed-by: tags
- Notable: Rafael Wysocki sign-off indicates ACPI maintainer acceptance for kernel integration

### Step 1.3: Commit Body Analysis
**Record:**
- **Bug:** After skipping a failed If/While block, the code checks *walk_state->aml == AML_ELSE_OP without verifying walk_state->aml is within the AML buffer.
- **Symptom:** Out-of-bounds read (1 byte past buffer end).
- **Root cause:** acpi_ps_get_next_package_end() can advance the AML pointer to or past parser_state->aml_end on malformed/truncated AML; the subsequent dereference is unchecked.
- **Version info:** None in commit message; upstream ACPICA issue #1078 documents ASan reproduction.

### Step 1.4: Hidden Bug Fix Detection
**Record:** Not disguised — explicitly labeled a fix for an out-of- bounds access. Genuine memory-safety bug fix.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Change Inventory
**Record:**
- **File:** drivers/acpi/acpica/psloop.c (+3 / -1 lines)
- **Function:** acpi_ps_parse_loop()
- **Scope:** Single-file, surgical fix in an error-recovery path

### Step 2.2: Code Flow Change
**Record:**
- **Before:** After skipping a failed If/While body, unconditionally dereferenced *walk_state->aml to test for AML_ELSE_OP.
- **After:** Only dereferences if walk_state->aml < parser_state->aml_end AND the byte equals AML_ELSE_OP.
- **Path affected:** Error recovery when acpi_ps_get_arguments() fails inside an If/While control structure during module-level ACPI table parsing.

### Step 2.3: Bug Mechanism
**Record:**
- **Category:** Buffer overflow / out-of-bounds read (memory safety)
- **Mechanism:** acpi_ps_get_next_package_end() returns a pointer past the package end. On malformed AML at the buffer boundary, walk_state->aml can equal or exceed parser_state->aml_end. The old code read one byte past the allocated AML buffer. The fix adds the same bounds guard used by the main parse loop at line 300.

### Step 2.4: Fix Quality
**Record:**
- **Quality:** Obviously correct; mirrors the existing parser_state->aml < parser_state->aml_end pattern at line 300.
- **Regression risk:** Very low — only skips the Else-block skip when already past the buffer end (correct behavior).
- **Red flags:** None.

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame
**Record:** Buggy line introduced in 5088814a6e931 ("ACPICA: AML
parser: attempt to continue loading table after error") by Erik Kaneda, 2018-06-01. Confirmed ancestor of HEAD. Present in v6.18.44.

### Step 3.2: Fixes: Tag
**Record:** N/A — no Fixes: tag. Upstream ACPICA issue #1078 references the bug; the introducing commit is 5088814a6e931 (2018).

### Step 3.3: Related File History
**Record:** Recent psloop.c history is copyright updates and unrelated parser cleanups. No prior fix for this issue in this tree. The Else-skip logic has been unchanged since 2018.

### Step 3.4: Author Context
**Record:** Author ikaros (void0red) reported the bug via ACPICA fuzzing. Rafael Wysocki (ACPI maintainer) signed off. ACPICA maintainer SaketADumbre merged upstream PR #1087 with positive review ("minimal but the right changes").

### Step 3.5: Dependencies
**Record:** No dependencies. Standalone 3-line fix. No patch series. Applies cleanly to current psloop.c in this tree.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original Discussion
**Record:** b4 dig -c 3b537b92336e failed — commit not in Linux git history (ACPICA-only commit). Upstream discussion found at:
- ACPICA issue #1078: ASan heap-buffer-overflow at psloop.c:569 (fuzzed AML via acpiexec)
- ACPICA PR #1087: merged 2026-02-21
- Kernel lore/patch.msgid.link blocked by Anubis — could not read thread

### Step 4.2: Reviewers
**Record:** Rafael Wysocki signed off (kernel ACPI maintainer). SaketADumbre (ACPICA maintainer) reviewed and merged upstream. No NAKs found.

### Step 4.3: Bug Report
**Record:** ACPICA issue #1078 — ASan READ of size 1 at address 0 bytes past a 1293-byte heap region. Reproducible with fuzzed AML (fuzz_178.aml). Severity: confirmed memory safety bug via sanitizer.

### Step 4.4: Related Patches
**Record:** Standalone fix. Not part of a multi-patch series.

### Step 4.5: Stable Mailing List
**Record:** Could not search lore (Anubis protection). No stable- specific discussion found via other sources.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key Functions
**Record:** acpi_ps_parse_loop() — modified. acpi_ps_get_next_package_end() — called just before the buggy check.

### Step 5.2: Callers
**Record:** acpi_ps_parse_loop() called from acpi_ps_parse_aml() in psparse.c:475. Reachable during ACPI table loading and method execution.

### Step 5.3: Callees
**Record:** acpi_ps_get_arguments(), acpi_ps_complete_op(), acpi_ps_get_next_package_end(), acpi_ut_pop_generic_state().

### Step 5.4: Call Chain (Reachability)
**Record:**

```
Boot: acpi_ns_load_table() → acpi_ns_parse_table() →
acpi_ns_execute_table()
  → acpi_ps_execute_table() [sets ACPI_METHOD_MODULE_LEVEL]
  → acpi_ps_parse_aml() → acpi_ps_parse_loop()
```

Module-level ACPI table parsing (DSDT/SSDT) uses this error-recovery path. Malformed firmware AML that fails If/While argument parsing can reach the buggy dereference. **Reachable during boot on all ACPI-enabled systems.**

### Step 5.5: Similar Patterns
**Record:** Main parse loop at line 300 uses parser_state->aml < parser_state->aml_end. The Else check at line 428 was the only unguarded dereference in this error path. No similar fix already present in this tree (git log -S 'walk_state->aml <' returned nothing).

---

## PHASE 6: CROSS-REFERENCING AGAINST LOCAL TREE

### Step 6.1: Buggy Code Exists?
**Record:** **YES.** Line 428 in drivers/acpi/acpica/psloop.c has the unguarded if (*walk_state->aml == AML_ELSE_OP). Confirmed in v6.18.44 tag. Bug present since 2018 (commit 5088814a6e931).

### Step 6.2: Backport Complications
**Record:** **Clean apply expected.** File structure unchanged around the hunk. No conflicting recent changes in this area.

### Step 6.3: Related Fixes Already Present?
**Record:** **No.** Fix not in this tree. grep for the bounds-check pattern returns no matches.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

### Step 7.1: Subsystem Criticality
**Record:** **ACPI / ACPICA** — **CORE**. ACPI table parsing runs at boot on essentially all x86 and many ARM systems. Affects firmware table loading.

### Step 7.2: Subsystem Activity
**Record:** Active — regular ACPICA syncs and copyright updates, but this code path has been stable since 2018.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: Who Is Affected
**Record:** All systems with ACPI enabled that load AML tables containing If/While constructs. Trigger requires malformed ACPI AML (common in buggy firmware) combined with a parse failure in the If/While predicate.

### Step 8.2: Trigger Conditions
**Record:**
- If/While argument parsing fails during module-level table load
- acpi_ps_get_next_package_end() advances AML pointer to or past buffer end
- Unprivileged users cannot directly inject ACPI tables, but **malicious or buggy firmware ACPI tables** can trigger this at boot
- Likelihood: Low in practice, but the error-recovery path exists specifically for malformed AML

### Step 8.3: Failure Mode Severity
**Record:** Out-of-bounds read of 1 byte past AML buffer. **Severity:
HIGH** — potential kernel oops/crash or information leak. ASan-confirmed heap-buffer-overflow.

### Step 8.4: Risk-Benefit
**Record:**
- **Benefit:** HIGH — prevents OOB read in core ACPI parser on malformed firmware tables
- **Risk:** VERY LOW — 3-line bounds check matching existing code pattern
- **Ratio:** Strongly favors backport

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence Summary

**FOR backport:**
- Real, ASan-confirmed out-of-bounds read
- Small (3 lines), obviously correct fix
- Bug present in this tree since 2018
- Affects core ACPI table loading at boot
- ACPI maintainer (Rafael Wysocki) signed off
- No dependencies; clean apply
- Error-recovery path designed for malformed AML — exactly when this bug triggers

**AGAINST backport:**
- Found via acpiexec fuzzing, not a reported production kernel crash
- Requires malformed ACPI + specific parse failure (narrow trigger)
- ACPI tables come from firmware, not direct userspace input (reduced attack surface, but buggy firmware is common)

**UNRESOLVED:**
- Kernel lore thread content (Anubis blocked)
- Whether any production kernel crash has been attributed to this specific bug

### Step 9.2: Stable Rules Checklist
1. Obviously correct and tested? **PASS** — matches existing bounds- check pattern; ASan-verified fix upstream
2. Fixes a real bug? **PASS** — confirmed OOB read
3. Important issue? **PASS** — memory safety in core boot path (HIGH)
4. Small and contained? **PASS** — 3 lines, one function
5. No new features/APIs? **PASS**
6. Can apply to local tree? **PASS** — buggy code confirmed present, clean apply expected

### Step 9.3: Exception Categories
**Record:** N/A — standard bug fix, not a device ID/quirk/DT/build/doc exception.

### Step 9.4: Decision Rationale

This commit fixes a genuine out-of-bounds read in the ACPI AML parser's error-recovery path. The bug has existed since 2018 and is present in the local 6.18.44 tree. While the trigger requires malformed ACPI AML with a failed If/While parse, that is precisely the scenario the 2018 error-recovery code was written to handle — and buggy ACPI firmware is a known real-world problem. The fix is minimal, mirrors an existing bounds check in the same function, and carries negligible regression risk. Memory-safety fixes in core boot-path code are appropriate for stable trees.

---

## Verification

- **[Phase 1]** Parsed commit message: subsystem ACPICA, action "Fix", OOB access described; Rafael Wysocki SOB confirmed
- **[Phase 1]** No Reported-by/syzbot; upstream ACPICA issue #1078 provides bug report
- **[Phase 2]** Diff: +3/-1 in psloop.c, adds walk_state->aml < parser_state->aml_end guard before AML_ELSE_OP check
- **[Phase 3]** git blame -L 428,428: buggy line from 5088814a6e931 (2018-06-01)
- **[Phase 3]** git show 5088814a6e931: introduced Else-skip logic without bounds check
- **[Phase 3]** git merge-base --is-ancestor 5088814a6e931 HEAD:
confirmed buggy commit in tree
- **[Phase 3]** git log --oneline -20 -- drivers/acpi/acpica/psloop.c:
no prior fix for this issue
- **[Phase 3]** git log -S 'walk_state->aml <' -- drivers/acpi/acpica/: no similar fix already applied
- **[Phase 4]** b4 dig -c 3b537b92336e: FAILED — commit not in Linux git
- **[Phase 4]** ACPICA issue #1078: ASan heap-buffer-overflow confirmed at psloop.c
- **[Phase 4]** ACPICA PR #1087: merged, maintainer approved minimal fix
- **[Phase 4]** lore.kernel.org / patch.msgid.link: BLOCKED by Anubis — UNVERIFIED for kernel list discussion
- **[Phase 5]** acpi_ps_parse_loop callers: psparse.c:475 via acpi_ps_parse_aml
- **[Phase 5]** Call chain: acpi_ns_parse_table → acpi_ns_execute_table → acpi_ps_execute_table (sets ACPI_METHOD_MODULE_LEVEL) → acpi_ps_parse_loop
- **[Phase 5]** nsparse.c:98: ACPI_METHOD_MODULE_LEVEL set during table execution
- **[Phase 6]** git describe HEAD: v6.18.44 on stable/linux-6.18.y
- **[Phase 6]** git show v6.18.44:drivers/acpi/acpica/psloop.c lines 426-432: buggy unguarded check confirmed
- **[Phase 6]** grep for fix pattern in tree: no matches — fix not present
- **[Phase 8]** Failure mode: OOB read, severity HIGH; trigger on malformed ACPI during boot table load

**YES**

 drivers/acpi/acpica/psloop.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/acpi/acpica/psloop.c +4 -1
index c989cadf271ce..35111ff2526b1 100644
@@ -425,7 +425,10 @@ acpi_status acpi_ps_parse_loop(struct acpi_walk_state *walk_state)
 
 					ACPI_ERROR((AE_INFO,
 						    "Skipping While/If block"));
-					if (*walk_state->aml == AML_ELSE_OP) {
+					if ((walk_state->aml <
+					     parser_state->aml_end)
+					    && (*walk_state->aml ==
+						AML_ELSE_OP)) {
 						ACPI_ERROR((AE_INFO,
 							    "Skipping Else block"));
 						walk_state->parser_state.aml =
Signature · 1 line
2.53.0
author maintainer
#223 lore raw

PATCH 1/1 media: imon: Add iMON VFD HID OEM v1.2 key mappings

In reply to Sasha Levin

From: Alessandro Baldi <[email protected]>

[ Upstream commit d97d13c24d7893abcfb80d38630ce74daaa1434c ]

Add Vol+/Vol-/Mute panel button mappings for iMON VFD HID OEM v1.2. This version differs in the codes that generate the KEY_VOLUMEUP, KEY_VOLUMEDOWN and KEY_MUTE events.

---

LLM Generated explanations, may be completely bogus:

Connection lost, reconnecting to https://agentn.us.api5.cursor.sh
(attempt 1)...
Retry attempt 1...
# Stable Backport Analysis: media: imon: Add iMON VFD HID OEM v1.2 key mappings

**Local tree:** Linux 6.18.43 (git describe HEAD → v6.18.43-1-gc7f0dac02d232)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: PARSE THE SUBJECT LINE
**Record:** [media: imon] [Add] — Add key mappings for iMON VFD HID OEM v1.2 panel buttons (Vol+/Vol-/Mute).

### Step 1.2: PARSE ALL COMMIT MESSAGE TAGS
**Record:**
- **Fixes:** — not present (expected for manual review)
- **Reported-by:** — none
- **Tested-by:** — none
- **Reviewed-by:** — none
- **Acked-by:** — none
- **Link:** — none
- **Cc: [email protected]:** — not present (expected)
- **Signed-off-by:** Alessandro Baldi <[email protected]> (author)
- **Signed-off-by:** Sean Young <[email protected]> (media subsystem maintainer — strong quality signal)

No syzbot, no bugzilla links, no multiple reporters.

### Step 1.3: ANALYZE THE COMMIT BODY TEXT
**Record:**
- **Bug:** iMON VFD HID OEM v1.2 firmware sends different hardware scancodes for Vol+, Vol-, and Mute than other variants already mapped in imon_OEM_VFD.
- **Symptom:** Panel volume/mute buttons on v1.2 hardware produce no useful input events (lookup returns KEY_RESERVED).
- **Root cause:** Missing entries in the imon_OEM_VFD.key_table for scancodes 0x0a, 0x0b, 0x0c (with 0xffee suffix applied at lookup time).
- **Version info:** Specific to "iMON VFD HID OEM v1.2" variant of USB device 0x15c2:0x0036.

### Step 1.4: DETECT HIDDEN BUG FIXES
**Record:** Not disguised as cleanup. This is an explicit hardware- variant key-mapping fix. Functionally equivalent to a hardware quirk:
same USB ID, different firmware scanc## Phase 1: Commit Message Forensics

### Step 1.1: Subject Line
**Record:** [media: imon] [Add] — Add iMON VFD HID OEM v1.2 key mappings for Vol+/Vol-/Mute panel buttons.

### Step 1.2: Commit Message Tags
**Record:**
- **Fixes:** — not present (expected for manual review)
- **Reported-by:** — none
- **Tested-by:** — none
- **Reviewed-by:** — none
- **Acked-by:** — none
- **Link:** — none
- **Cc: [email protected]** — none
- **Signed-off-by:** Alessandro Baldi <[email protected]> (author)
- **Signed-off-by:** Sean Young <[email protected]> (media maintainer; pipeline Sasha Levin SOB ignored per instructions)

Notable: maintainer sign-off from Sean Young, but no fuzzer report, user bug report, or explicit stable nomination.

### Step 1.3: Commit Body Analysis
**Record:**
- **Bug:** iMON VFD HID OEM v1.2 panel buttons send different hardware codes for KEY_VOLUMEUP, KEY_VOLUMEDOWN, and KEY_MUTE than other variants already mapped in imon_OEM_VFD.
- **Symptom:** Volume+/Volume-/Mute panel buttons produce no useful input events on v1.2 hardware.
- **Root cause:** Missing entries in the imon_OEM_VFD.key_table for the v1.2 scancodes (0x0a, 0x0b, 0x0c with 0xffee suffix pattern).
- **Version info:** Targets a specific hardware/firmware variant (v1.2), not a kernel regression.

### Step 1.4: Hidden Bug Fix Detection
**Record:** Not a disguised crash/leak/race fix. This is explicit hardware-variant keymap completion — functionally a hardware quirk/workaround for a device revision that uses different scancodes.

---

## Phase 2: Diff Analysis

### Step 2.1: Change Inventory
**Record:**
- **File:** drivers/media/rc/imon.c (+4 lines including comment, +3 mapping entries)
- **Function/structure:** imon_OEM_VFD.key_table static data only
- **Scope:** Single-file, surgical data-table addition

### Step 2.2: Code Flow Change
**Record:**
- **Before:** imon_panel_key_lookup() walks imon_OEM_VFD.key_table; v1.2 Vol+/Vol-/Mute scancodes (0x000000000a00ffee, 0x000000000b00ffee, 0x000000000c00ffee) match nothing → returns KEY_RESERVED.
- **After:** Those scancodes map to KEY_VOLUMEUP, KEY_VOLUMEDOWN, KEY_MUTE.
- **Path affected:** 8-byte panel button packets (len == 8 && buf[7] == 0xee) on USB device 0x15c2:0x0036 using imon_OEM_VFD.

### Step 2.3: Bug Mechanism
**Record:** **Category:** Hardware quirk / incomplete keymap for hardware variant. **Mechanism:** Same USB ID and driver, but v1.2 firmware emits different panel scancodes than existing table entries; unmatched codes are dropped as KEY_RESERVED.

### Step 2.4: Fix Quality
**Record:** Obviously correct pattern — mirrors existing volume/mute entries already in the same table. Minimal diff, no logic changes. **Regression risk:** Very low; only adds new lookup entries without altering existing mappings.

---

## Phase 3: Git History Investigation

### Step 3.1: Blame / Introduction
**Record:** In this shallow 6.18.43 checkout (~50 commits), imon_OEM_VFD and its volume mappings are present at base commit a112b91dd6349. Full upstream introduction history is not available in this checkout. The **missing v1.2 mappings are confirmed absent** in the current tree.

### Step 3.2: Fixes: Tag
**Record:** N/A — no Fixes: tag.

### Step 3.3: Related File History
**Record:** git log --oneline -20 -- drivers/media/rc/imon.c shows only one commit in this shallow tree (a112b91dd6349), which is not informative for upstream history. No evidence this is part of a multi- patch series from local history.

### Step 3.4: Author Context
**Record:** No commits from Alessandro Baldi found in this checkout. Sean Young (Signed-off-by) is the media/RC maintainer — strong subsystem credibility signal.

### Step 3.5: Dependencies
**Record:** **Standalone.** No prerequisites; only adds rows to an existing table in existing driver code. No new structures or APIs required.

---

## Phase 4: Mailing List and External Research

### Step 4.1: Original Patch Discussion
**Record:** b4 dig requires -c COMMITISH; no commit hash was provided and subject-only search is unsupported. **Could not retrieve lore thread.**

### Step 4.2: Reviewers
**Record:** b4 dig -w not possible without commit hash. Sean Young SOB in commit message indicates maintainer involvement.

### Step 4.3: Bug Report
**Record:** No Reported-by: or Link: tags. No external bug report verified.

### Step 4.4: Related Patches / Series
**Record:** Appears standalone; no series indicators in subject or diff.

### Step 4.5: Stable List History
**Record:** Not searched (lore blocked by bot protection on fetch). Precedent exists for imon stable backports (e.g., 3.17-stable picked up imon RC protocol fix for broken remote functionality on 15c2:0034).

---

## Phase 5: Code Semantic Analysis

### Step 5.1: Key Functions
**Record:** Modified data: imon_OEM_VFD. Affected runtime functions:
imon_panel_key_lookup(), called from imon_incoming_packet(); table also used by imon_init_idev() to register supported keys.

### Step 5.2: Callers
**Record:** imon_panel_key_lookup() called from imon_incoming_packet() when processing 8-byte panel packets (buf[7] == 0xee). Triggered by physical panel button presses on supported iMON USB devices during normal driver operation.

### Step 5.3: Callees
**Record:** Simple linear table scan; returns KEY_RESERVED on miss. No allocation, locking, or I/O in lookup itself.

### Step 5.4: Reachability
**Record:** **Userspace-reachable** via panel button input on USB_DEVICE(0x15c2, 0x0036) bound to imon_OEM_VFD. Common HTPC/media- center use case for this hardware.

### Step 5.5: Similar Patterns
**Record:** Same table already contains multiple variant-specific volume/mute mappings (standard OEM, MCE VFD 0xffdc, knob values). v1.2 entries follow established pattern.

---

## Phase 6: Cross-Reference Against Local Tree (6.18.43)

### Step 6.1: Buggy Code Present?
**Record:** **YES.** Tree is 6.18.43 (git describe:
v6.18.43-1-gc7f0dac02d232). imon_OEM_VFD exists at lines 267–310 with volume mappings for other variants but **without** v1.2 entries (0x0a/0x0b/0x0c). USB ID 0x15c2:0x0036 → imon_OEM_VFD at line 392–393.

### Step 6.2: Backport Complications
**Record:** **Clean apply expected.** Insertion point is clearly between existing OEM volume entries and MCE VFD section — matches current file layout exactly.

### Step 6.3: Related Fixes Already Present? **Record:** grep for 0x000000000a00ffee and OEM v1.2 — **not found**. Fix is not already in this tree.

---

## Phase 7: Subsystem Context

### Step 7.1: Subsystem / Criticality
**Record:** drivers/media/rc/imon.c — media RC/input driver. **Criticality: PERIPHERAL** (niche HTPC front-panel hardware).

### Step 7.2: Subsystem Activity
**Record:** Mature, low-churn driver in this tree. imon support has been stable for many years; this is variant-specific table maintenance.

---

## Phase 8: Impact and Risk Assessment

### Step 8.1: Who Is Affected
**Record:** Users of SoundGraph iMON OEM VFD (15c2:0036) with HID OEM **v1.2** firmware — specifically panel Vol+/Vol-/Mute buttons. Config:
CONFIG_RC_CORE / imon USB driver.

### Step 8.2: Trigger Conditions
**Record:** Pressing panel volume/mute buttons on v1.2 hardware. **Common** for affected users every time they use those buttons. Unprivileged physical access; not a security vector.

### Step 8.3: Failure Mode Severity
**Record:** Unmapped keys → KEY_RESERVED → buttons do nothing. **Severity: LOW** — functional impairment only; no oops, hang, corruption, or security impact.

### Step 8.4: Risk-Benefit
**Record:**
- **Benefit:** Restores basic panel functionality for v1.2 owners; aligns with stable rules' explicit acceptance of **hardware quirk** fixes.
- **Risk:** Minimal — 3 table entries, no behavior change for existing mappings.
- **Ratio:** Moderate benefit for a small user population, very low risk.

---

## Phase 9: Final Synthesis

### Step 9.1: Evidence Summary

**FOR backport:**
- Fixes a real, user-visible hardware issue (non-working volume/mute buttons)
- Tiny, obviously correct, maintainer-signed
- Fits stable rules' **hardware quirk** category (Documentation/process/stable-kernel-rules.rst)
- Same pattern as existing variant-specific entries in the same table
- Applies cleanly to 6.18.43; driver and device ID already present
- Zero regression risk for users without v1.2 hardware

**AGAINST backport:**
- Not crash/security/corruption/deadlock
- Niche hardware with small user base
- No user/fuzzer bug report in commit message
- Completes support for a variant rather than fixing a kernel regression
- Mailing list review not verified (no commit hash for b4 dig)

**Unresolved:** Original lore discussion and whether a user/distro filed a bug report.

### Step 9.2: Stable Rules Checklist
1. Obviously correct and tested? **PASS** — standard keymap pattern; maintainer SOB
2. Fixes real bug affecting users? **PASS** — broken panel buttons on v1.2 hardware
3. Important issue? **PASS (borderline)** — hardware quirk per stable- kernel-rules.rst; not crash-level but explicitly listed acceptable category
4. Small and contained? **PASS** — 3 entries, one file
5. No new features/APIs? **PASS** — data-only quirk entries
6. Can apply to local tree? **PASS** — code present, clean insertion point

### Step 9.3: Exception Category
**Record:** **Hardware quirk/workaround** — v1.2 firmware revision uses different panel scancodes for the same USB device already supported by imon_OEM_VFD.

### Step 9.4: Decision Rationale

For **Linux 6.18.43**, the driver, device ID, and imon_OEM_VFD table all exist; v1.2 volume/mute scancodes are missing, so affected users' buttons are silently ignored. The fix is a minimal hardware-variant keymap addition — the same class of change stable trees routinely accept as hardware quirks. Severity is low (no stability/security impact), but benefit is clear for affected HTPC users and risk is negligible.

---

## Verification

- **[Phase 1]** Parsed subject, tags, body from provided commit message
- **[Phase 1]** Confirmed no Reported-by/Fixes/Link/Cc: stable tags
- **[Phase 2]** Diff: +3 keymap entries + comment in imon_OEM_VFD.key_table
- **[Phase 2]** Read imon_panel_key_lookup() at lines 1300–1316
- **[Phase 2]** Read imon_incoming_packet() panel path at lines 1599–1602
- **[Phase 3]** git describe HEAD → v6.18.43-1-gc7f0dac02d232; Makefile → 6.18.43
- **[Phase 3]** git blame -L 267,310 drivers/media/rc/imon.c — table present (shallow history limits introduction date)
- **[Phase 3]** git log --grep / -S searches — no candidate commit in this tree
- **[Phase 4]** b4 dig — failed (no commit hash provided; -q not supported)
- **[Phase 4]** lore.kernel.org fetch — blocked by bot protection
- **[Phase 4]** Web search — found prior imon stable backport precedent (3.17-stable RC protocol fix)
- **[Phase 5]** grep imon_OEM_VFD — device 0x15c2:0x0036 uses this table
- **[Phase 5]** Traced call chain: panel button → imon_incoming_packet() → imon_panel_key_lookup()
- **[Phase 6]** Read imon_OEM_VFD at lines 267–310 — v1.2 mappings absent
- **[Phase 6]** grep 0x000000000a00ffee — not in tree
- **[Phase 7]** Read Documentation/process/stable-kernel-rules.rst — hardware quirk explicitly acceptable
- **[Phase 8]** Confirmed failure mode is KEY_RESERVED (no crash) via lookup code
- **UNVERIFIED:** Original mailing list review thread; whether bug was reported by users; exact kernel version that first introduced imon_OEM_VFD (shallow clone)

**YES**

 drivers/media/rc/imon.c | 4 ++++
 1 file changed, 4 insertions(+)
drivers/media/rc/imon.c +4 -0
index 48534bb52e4d0..4f974b88628f0 100644
@@ -290,6 +290,10 @@ static const struct imon_usb_dev_descr imon_OEM_VFD = {
 		{ 0x000100000000ffeell, KEY_VOLUMEUP },
 		{ 0x010000000000ffeell, KEY_VOLUMEDOWN },
 		{ 0x000000000100ffeell, KEY_MUTE },
+		/* iMON VFD HID OEM v1.2 */
+		{ 0x000000000a00ffeell, KEY_VOLUMEUP },
+		{ 0x000000000b00ffeell, KEY_VOLUMEDOWN },
+		{ 0x000000000c00ffeell, KEY_MUTE },
 		/* 0xffdc iMON MCE VFD */
 		{ 0x00010000ffffffeell, KEY_VOLUMEUP },
 		{ 0x01000000ffffffeell, KEY_VOLUMEDOWN },
Signature · 1 line
2.53.0
author maintainer
#224 lore raw

PATCH 1/1 leds: pca9532: Don't stop blinking for non-zero brightness

In reply to Sasha Levin

From: Tobias Deiminger <[email protected]>

[ Upstream commit 0261683a4d31783d680e74b3ae5f22f6a62128cc ]

pca9532 unexpectedly stopped blinking when changing brightness to a non-zero value. To reproduce:

 echo timer > /sys/class/leds/led-1/trigger   # blinks
 echo 255 > /sys/class/leds/led-1/brightness  # blinking stops, light on
 cat /sys/class/leds/led-1/trigger            # still claims [timer]

According to Documentation/leds/leds-class.rst, only brightness = 0 shall be a stop condition:

Quoted 3 lines

You can change the brightness value of a LED independently of the timer trigger. However, if you set the brightness value to LED_OFF it will also disable the timer trigger.

Therefore add a guard to continue blinking when brightness != LED_OFF, similar to how pca955x does it since 575f10dc64a2 ("leds: pca955x: Add HW blink support").

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: leds: pca9532: Don't stop blinking for non- zero brightness

**Local tree:** v6.18.44 (6.18.44, Makefile VERSION=6, PATCHLEVEL=18, SUBLEVEL=44)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Subject line
**Record:** [leds: pca9532] [fix/guard] — When brightness is set to a non-zero value while hardware blinking is active, do not stop blinking.

### Step 1.2: Tags
**Record:**
- **Signed-off-by:** Tobias Deiminger <[email protected]> (author)
- **Link:** https://patch.msgid.link/20260331202848.658676-1-
[email protected]
- **Signed-off-by:** Lee Jones <[email protected]> (subsystem maintainer, applied)
- No Fixes:, Reported-by:, Tested-by:, Reviewed-by:, Acked- by:, or Cc: [email protected]
- Lore thread identifies mainline commit as 770edd8e8e5bed961af2ca6ab397052046d1d774 (not present in this checkout)

### Step 1.3: Body analysis
**Record:**
- **Bug:** After enabling the timer trigger (hardware blink via PWM1), writing a non-zero value to brightness stops blinking while sysfs still reports [timer].
- **Symptom:** LED stays solid on; trigger sysfs entry is inconsistent with actual behavior.
- **Reproduction:** Documented sysfs sequence (timer trigger → echo 255 > brightness → cat trigger).
- **Root cause (author):** pca9532_set_brightness() overwrites PCA9532_PWM1 state for any non-zero brightness.
- **Reference:** LED class docs say only LED_OFF should stop a timer trigger; pca955x already guards this way since 575f10dc64a2.

### Step 1.4: Hidden bug fix?
**Record:** No — this is an explicit functional bug fix, not disguised cleanup.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Inventory
**Record:**
- **Files:** drivers/leds/leds-pca9532.c only (+4/-2 lines net)
- **Function:** pca9532_set_brightness()
- **Scope:** Single-file, surgical driver fix

### Step 2.2: Code flow change
**Record:**
- **Before:** Any non-zero brightness overwrites led->state (PCA9532_ON or PCA9532_PWM0), including when already in PCA9532_PWM1 (HW blink).
- **After:** If value == LED_OFF → turn off as before. Else if led->state == PCA9532_PWM1 → return 0 immediately (preserve HW blink). Otherwise unchanged logic for LED_FULL / PWM dimming.
- **Path affected:** Sysfs brightness writes while hardware blinking is active.

### Step 2.3: Bug mechanism
**Record:**
- **Category:** Logic / correctness fix (API contract violation)
- **Mechanism:** HW blink sets led->state = PCA9532_PWM1 in pca9532_update_hw_blink(). Subsequent brightness_set_blocking calls clobber that state via pca9532_setled(), stopping hardware blink while the LED core still believes the timer trigger is active.

### Step 2.4: Fix quality
**Record:**
- Fix is minimal and mirrors the established pca955x pattern (test_bit(active_blink) → early goto out for non-zero brightness).
- **Regression risk:** Low. PCA9532_PWM1 for HW blink is only set via pca9532_update_hw_blink(), which requires hw_blink == true. The N2100 beeper path uses PWM1 but does not register a led_classdev brightness callback, so the guard does not affect beeper input handling.
- LED_OFF still correctly stops the LED.

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame
**Record:** pca9532_set_brightness() core logic dates to 2008 (e14fa82439d33c). The bug was latent until HW blink landed in 48ca7f302cfcf (2024-06-17, "leds: pca9532: Use PWM1 for hardware blinking"), which added pca9532_update_hw_blink() setting PCA9532_PWM1 without updating pca9532_set_brightness().

### Step 3.2: Fixes: tag
**Record:** N/A — no Fixes: tag. Logical introducer is 48ca7f302cfcf, which is an ancestor of this tree.

### Step 3.3: Related file history
**Record:** Recent leds-pca9532.c commits in this tree include HW blink work (48ca7f302cfcf, f51bc3cedfc45), default frequency change, and error-message cleanup (2aad93b6de0d8, which carried Cc: stable). This fix is standalone (v2 of a single-patch series).

### Step 3.4: Author context
**Record:** Tobias Deiminger has no other commits in drivers/leds/ in this tree. Lee Jones (LED maintainer) applied the patch.

### Step 3.5: Dependencies
**Record:**
- Requires HW blink support (48ca7f302cfcf) — **present** in this tree.
- References pca955x pattern from 575f10dc64a2 — **present** in this tree.
- No series dependencies; applies standalone.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original discussion
**Record:**
- **URL:** https://lore.kernel.org/linux-
leds/[email protected]/
- **Series:** v2 (v1 at https://lore.kernel.org/r/20260321102121.1563365
[email protected]); v2 only changes comment style and brace placement.
- **Review:** Lee Jones replied "Applied, thanks!" — no NAKs or objections found.
- **Stable nomination:** None in thread.

### Step 4.2: Reviewers
**Record:** CC'd: [email protected], [email protected], [email protected], [email protected], linux- [email protected]. Lee Jones (maintainer) applied.

### Step 4.3: Bug report
**Record:** Author-provided sysfs reproduction in patch and commit message. No external bugzilla/syzbot report.

### Step 4.4: Related patches
**Record:** Standalone 1/1 patch. Related context: 575f10dc64a2 (pca955x HW blink guard) and 48ca7f302cfcf (pca9532 HW blink introduction).

### Step 4.5: Stable list
**Record:** No stable-list discussion found for this specific fix.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key functions
**Record:** pca9532_set_brightness() (modified); context:
pca9532_update_hw_blink(), pca9532_set_blink(), pca9532_setled().

### Step 5.2: Callers
**Record:** pca9532_set_brightness is registered as brightness_set_blocking for PCA9532_TYPE_LED devices (probe path ~line 426). Called from LED core via __led_set_brightness_blocking() on sysfs brightness writes — userspace-accessible.

### Step 5.3: Callees
**Record:** On guarded path: none (early return). Normal path:
pca9532_calcpwm(), pca9532_setpwm(), pca9532_setled() (I2C register writes under mutex).

### Step 5.4: Reachability
**Record:**
1. User writes timer to trigger → led_blink_set() → pca9532_set_blink() → HW blink configures PWM1
2. User writes non-zero brightness → pca9532_set_brightness() — **buggy without fix**
- Reachable from unprivileged userspace (sysfs, subject to permissions). Common on embedded status-LED setups.

### Step 5.5: Similar patterns
**Record:** pca955x_led_set() in leds-pca955x.c lines 316–323 explicitly preserves blinking for non-zero brightness when active_blink is set — same design intent.

---

## PHASE 6: CROSS-REFERENCING AGAINST LOCAL TREE

### Step 6.1: Buggy code present?
**Record:** **Yes.** Current pca9532_set_brightness() at lines 185–198 lacks the PCA9532_PWM1 guard. HW blink support from 48ca7f302cfcf is in this tree. Bug introduced ~2024-06 with that commit.

### Step 6.2: Backport complications
**Record:** Expected **clean apply** — the surrounding function matches the diff context exactly. No conflicting recent changes to this function.

### Step 6.3: Related fixes already present?
**Record:** **No** — grep finds no "Non-zero brightness shall not stop" comment or equivalent guard. The fix commit (770edd8e8e5b) is not in this tree.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

### Step 7.1: Subsystem criticality
**Record:** drivers/leds/ — **PERIPHERAL** driver (PCA9532 I2C LED controller). Important for embedded/industrial boards (e.g. historical Thecus NAS platforms), not core kernel.

### Step 7.2: Subsystem activity
**Record:** LED subsystem actively maintained in 6.18.y; recent stable- relevant fixes include buffer overread, error-path leaks, and probe- order fixes.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: Who is affected
**Record:** Users of pca9532 with hw_blink == true (default for normal LED configs; disabled only for N2100 beeper variant). Driver- specific, config/board-specific.

### Step 8.2: Trigger conditions
**Record:** Enable timer trigger (HW blink succeeds), then write any non-zero brightness. **Common** for scripts/users adjusting LED intensity while blinking. Unprivileged users can trigger via sysfs (with normal permissions).

### Step 8.3: Failure mode severity
**Record:** Incorrect LED behavior + inconsistent sysfs state (trigger shows active, hardware not blinking). **Severity: MEDIUM** — no crash, corruption, or deadlock; real functional regression against documented LED class behavior.

### Step 8.4: Risk-benefit
**Record:**
- **Benefit:** Restores documented sysfs semantics; fixes regression introduced by HW blink backport already in this tree.
- **Risk:** Very low (4-line guard, proven sibling-driver pattern).
- **Ratio:** Favorable — low-risk regression fix for functionality already shipped in 6.18.y.

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence summary

**FOR backport:**
- Real, reproducible bug with clear sysfs steps
- Regression from 48ca7f302cfcf, already in this tree
- Violates Documentation/leds/leds-class.rst contract
- Tiny, obviously correct fix matching pca955x
- Maintainer (Lee Jones) applied without objection
- Clean apply expected

**AGAINST backport:**
- Not a crash, security, corruption, or deadlock issue
- Affects only pca9532 + HW blink configurations
- No explicit Cc: stable or user bug reports beyond author

**Unresolved:** None material to the decision.

### Step 9.2: Stable rules checklist
1. Obviously correct and tested? **PASS** — logic matches pca955x; sysfs repro documented; maintainer applied.
2. Fixes a real bug affecting users? **PASS** — sysfs/API behavior bug on real hardware.
3. Important issue? **PASS (moderate)** — regression in shipped HW-blink feature; inconsistent sysfs state; not crash-level but user-visible and documented-API violation.
4. Small and contained? **PASS** — ~4 lines, one function, one file.
5. No new features or APIs? **PASS** — behavior correction only.
6. Can apply to local tree? **PASS** — prerequisite commits present; clean apply expected.

### Step 9.3: Exception categories
**Record:** None (not device ID, quirk, DT, build, or docs-only). Standard driver correctness fix.

### Step 9.4: Problem and decision rationale

This commit fixes a regression introduced when hardware blinking was added to pca9532 in this tree (48ca7f302cfcf). Without the guard, any non-zero brightness write silently tears down PCA9532_PWM1 hardware blink while the LED core still reports the timer trigger as active — breaking the documented rule that non-zero brightness changes should not disable the timer trigger.

For 6.18.y users who received HW blink support, this completes that feature correctly. The fix is minimal, follows an in-tree precedent (pca955x), and carries negligible regression risk. While not a crash fix, it is a clear regression fix for behavior already present in this stable tree.

---

## Verification

- **[Phase 1]** Parsed subject, tags, body from user-provided commit message; fetched lore v2 mbox via curl
- **[Phase 2]** Read current pca9532_set_brightness() at lines 179–199; analyzed provided diff
- **[Phase 3]** git describe HEAD → v6.18.44; git blame -L 179,199 → core logic from 2008, bug latent until 2024; git log --oneline -20 -- drivers/leds/leds-pca9532.c → 48ca7f302cfcf present; git merge- base --is-ancestor → both 48ca7f302cfcf and 575f10dc64a2 in tree; git show 48ca7f302cfcf confirmed HW blink addition
- **[Phase 4]** curl lore mbox: v2 patch, Lee Jones "Applied, thanks!", commit id 770edd8e8e5b; b4 dig -c failed (commit not in tree); no stable-list hits
- **[Phase 5]** Traced brightness_set_blocking registration (~line 426); read pca955x_led_set() guard at lines 316–323; read led_blink_setup() in led-core.c (HW blink bypasses SW timer when blink_set succeeds)
- **[Phase 6]** Confirmed buggy code present (no PCA9532_PWM1 guard); grep found no existing fix; git show 770edd8e8e5b → bad object (not in tree)
- **[Phase 7]** git log --oneline -20 -- drivers/leds/ for subsystem activity
- **[Phase 8]** Read Documentation/leds/leds-class.rst lines 23–25; confirmed hw_blink default true except N2100 beeper (~line 440)
- **[Phase 9]** Synthesized against stable rules for 6.18.44 only

**YES**The background search finished: the fix (leds: pca9532: Don't stop blinking for non-zero brightness) is **not** in this 6.18.44 tree yet. The buggy code is still there — pca9532_set_brightness() can overwrite PCA9532_PWM1 when sysfs brightness is set to a non-zero value while hardware blinking is active.

**Verdict for this tree: YES** — small regression fix for HW blink support already in 6.18.y; low risk and matches the pca955x pattern.

 drivers/leds/leds-pca9532.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
drivers/leds/leds-pca9532.c +5 -3
index 0344189bb991c..dae7c67605084 100644
@@ -182,11 +182,13 @@ static int pca9532_set_brightness(struct led_classdev *led_cdev,
 	int err = 0;
 	struct pca9532_led *led = ldev_to_led(led_cdev);
 
-	if (value == LED_OFF)
+	if (value == LED_OFF) {
 		led->state = PCA9532_OFF;
-	else if (value == LED_FULL)
+	} else if (led->state == PCA9532_PWM1) {
+		return 0; /* Non-zero brightness shall not stop HW blinking */
+	} else if (value == LED_FULL) {
 		led->state = PCA9532_ON;
-	else {
+	} else {
 		led->state = PCA9532_PWM0; /* Thecus: hardcode one pwm */
 		err = pca9532_calcpwm(led->client, PCA9532_PWM_ID_0, 0, value);
 		if (err)
Signature · 1 line
2.53.0
#225 lore raw

Re: [PATCH AUTOSEL 6.18-5.10] leds: pca9532: Don't stop blinking for non-zero brightness

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [High] Race condition in N2100_BEEP input device teardown leading to use-after-free --

commit 7c75890ff5fc7d7cfe4c161d927be50be43a1827
Author: Tobias Deiminger <[email protected]>

leds: pca9532: Don't stop blinking for non-zero brightness

This patch prevents the pca9532 driver from incorrectly stopping hardware blinking when a non-zero brightness value is set. It adds a guard to return early if the LED state is PCA9532_PWM1, aligning the behavior with the LED subsystem documentation.

drivers/leds/leds-pca9532.c

Quoted 4 lines
drivers/leds/leds-pca9532.c +0 -0
index 0344189bb991c..dae7c67605084 100644

[ ... ]

[Severity: High]
This isn't a bug introduced by this patch, but while looking at this driver, I noticed a potential use-after-free race during teardown of the N2100_BEEP input device.

In pca9532_destroy_devices(), the worker is canceled but the managed input device remains active until devres unwinds:

    case PCA9532_TYPE_N2100_BEEP:
        if (data->idev != NULL) {
            cancel_work_sync(&data->work);
            data->idev = NULL;
        }
        break;

If an input event (e.g., SND_BELL) arrives through the evdev node in this narrow window before devres unwinds, pca9532_event() will blindly queue up the work again:

    schedule_work(&data->work);

Once devres unwinding completes, the data structure is freed, but the newly queued work remains active. When pca9532_input_work() executes, it could access the freed data:

    static void pca9532_input_work(struct work_struct *work)
    {
        ...
        mutex_lock(&data->update_lock);

Could this result in a use-after-free crash if a user space process writes to the input event node during driver removal? Should the input device be explicitly unregistered before canceling the work?

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

PATCH 1/1 net: hns3: improve the unused_tuple parameter setting

In reply to Sasha Levin

From: Jijie Shao <[email protected]>

[ Upstream commit 1ad6f1ff3e96c7ee888475740c8acdaf822e0813 ]

Currently, when the tc tool is used to set flow table rules, the IP address and MAC address can be configured separately, for example, src_xx or dst_xx can be configured separately.

Therefore, the driver needs to check whether the mask is all zero in keys, such as FLOW_DISSECTOR_KEY_IPV4_ADDRS, FLOW_DISSECTOR_KEY_IPV6_ADDRS, and FLOW_DISSECTOR_KEY_ETH_ADDRS.
If the mask is all zero, the tuple is not configured.
In this case, the driver adds the tuple to unused_tuple.

---

LLM Generated explanations, may be completely bogus:

## Phase 1: Commit Message Forensics

**Step 1.1 — Subject line**
Record: [net: hns3] [improve] — improve unused_tuple handling when parsing tc flower match keys for MAC and IP addresses.

**Step 1.2 — Tags**
Record:
- **Signed-off-by:** Jijie Shao <[email protected]> (author)
- **Link:**
https://patch.msgid.link/[email protected]
- **Signed-off-by:** Jakub Kicinski <[email protected]> (netdev maintainer)
- No Fixes:, Reported-by:, Tested-by:, Reviewed-by:, Acked- by:, or Cc: [email protected]

Notable: maintainer merge ([email protected]), but no fuzzer or user bug report tags.

**Step 1.3 — Body analysis**
Record:
- **Bug:** When tc installs flower rules with only src_* or only dst_* for IP/MAC, the dissector key (FLOW_DISSECTOR_KEY_ETH_ADDRS, FLOW_DISSECTOR_KEY_IPV4_ADDRS, FLOW_DISSECTOR_KEY_IPV6_ADDRS) can be present while one side’s mask is all-zero.
- **Symptom:** Driver fails to mark that tuple as unused; hardware flow- director rules are programmed incorrectly instead of treating the field as a wildcard.
- **Root cause:** hclge_get_cls_key_mac() / hclge_get_cls_key_ip() only set unused_tuple when the entire key is absent, not when an individual mask is zero.

**Step 1.4 — Hidden bug fix?**
Record: **Yes.** Subject says “improve,” but this is a correctness fix for tc flower hardware offload, not a cosmetic cleanup.

---

## Phase 2: Diff Analysis

**Step 2.1 — Inventory**
Record:
- **Files:** drivers/net/ethernet/hisilicon/hns3/hns3pf/hclge_main.c (+12 lines)
- **Functions:** hclge_get_cls_key_mac(), hclge_get_cls_key_ip()
- **Scope:** Single-file, surgical driver fix

**Step 2.2 — Code flow change**
Record:
- **MAC hunk:** After copying eth addr keys/masks, if match.mask->dst or match.mask->src is all-zero, set INNER_DST_MAC / INNER_SRC_MAC in unused_tuple.
- **IPv4 hunk:** If match.mask->src or match.mask->dst is zero, set corresponding INNER_SRC_IP / INNER_DST_IP.
- **IPv6 hunk:** If ipv6_addr_any(&match.mask->src/dst), set corresponding IP unused bits.
- **Before:** Only the else branch (key fully absent) marked tuples unused.
- **After:** Per-field zero masks are also treated as unused, matching ethtool-path behavior elsewhere in the same file.

**Step 2.3 — Bug mechanism**
Record: **Logic / correctness fix.** Category: incorrect hardware tuple programming.

When unused_tuple is **not** set, hclge_fd_convert_tuple() programs hardware using:

```862:863:drivers/net/ethernet/hisilicon/hns3/hns3pf/hclge_main.h
#define calc_x(x, k, v) ((x) = ~(k) & (v))
#define calc_y(y, k, v) ((y) = (k) & (v))
```

With mask k = 0, this yields X = key, Y = 0 — not wildcard behavior. When unused_tuple **is** set, hclge_fd_convert_tuple() skips programming that tuple (wildcard). The ethtool path already does zero-mask checks (e.g. hclge_fd_check_ether_tuple()); the tc flower path did not.

**Step 2.4 — Fix quality**
Record: Obviously correct, minimal, mirrors existing driver logic. Low regression risk. Does not fix the same gap in hclge_get_cls_key_port() (ports), but that is a separate pre-existing issue.

---

## Phase 3: Git History Investigation

**Step 3.1 — Blame**
Record: hclge_get_cls_key_mac() introduced in 0205ec041ec61 (“net:
hns3: add support for hw tc offload of tc flower”, Dec 2020). hclge_get_cls_key_ip() mostly from same commit; signature extended in e199a5b29f199 (2024).

**Step 3.2 — Fixes: tag**
Record: N/A — no Fixes: tag.

**Step 3.3 — Related file history**
Record: Commit 1ad6f1ff3e96c is patch 2/6 of “enhance tc flow offload support” on master. Other series commits add actions, dissectors, debugfs, and file split — not required for this 12-line fix. Standalone.

**Step 3.4 — Author context**
Record: Jijie Shao is an active hns3 contributor (FD/TC-related commits in this tree).

**Step 3.5 — Dependencies**
Record: None. Functions and structures exist unchanged in 6.18.y. Cherry-pick to current HEAD applies cleanly (auto-merge, exit 0).

---

## Phase 4: Mailing List and External Research

**Step 4.1 — Original discussion**
Record: b4 dig -c 1ad6f1ff3e96c →
https://patch.msgid.link/[email protected]
Series: V4 net-next 2/6. Revisions v1–v4 found via b4 dig -a. Lore direct fetch blocked by bot protection; thread retrieved via b4 dig -m.

**Step 4.2 — Reviewers**
Record: b4 dig -w CC’d [email protected], [email protected], [email protected], [email protected], Huawei maintainers. No explicit stable nomination found in mbox grep.

**Step 4.3 — Bug report**
Record: No external bug report, syzbot, or user Reported-by:.

**Step 4.4 — Series context**
Record: Part of 6-patch enhancement series, but this patch only fixes existing cls-flower parsing; does not depend on new actions/dissectors from patches 3–6.

**Step 4.5 — Stable list**
Record: Not searched on lore stable (no stable nomination found in retrieved mbox). UNVERIFIED whether stable@ discussed this separately.

---

## Phase 5: Code Semantic Analysis

**Step 5.1 — Key functions**
Record: hclge_get_cls_key_mac(), hclge_get_cls_key_ip(), called from hclge_parse_cls_flower().

**Step 5.2 — Callers**
Record: hclge_parse_cls_flower() ← hclge_add_cls_flower() ← add_cls_flower in hnae3 ops ← hns3_nic_setup_tc() (ndo_setup_tc). Reachable from userspace via tc flower rules on HNS3 NICs.

**Step 5.3 — Callees**
Record: flow_rule_match_*, ether_addr_copy, ipv6_addr_be32_to_cpu, unused_tuple |= BIT(...).

**Step 5.4 — Reachability**
Record: Userspace-triggered via tc filter add ... flower ... on HiSilicon HNS3 hardware with flow-director/tc-flower offload enabled (CONFIG_HNS3).

**Step 5.5 — Similar patterns**
Record: Ethtool FD path in same file already checks zero masks (hclge_fd_check_tcpip4_tuple(), hclge_fd_check_ether_tuple(), etc.). tc flower path was inconsistent.

---

## Phase 6: Cross-Reference Against Local Tree (6.18.y)

**Step 6.1 — Buggy code present?**
Record: **Yes.** Local tree is **v6.18.44** (git describe HEAD). hclge_get_cls_key_mac() and hclge_get_cls_key_ip() lack zero-mask checks. Commit 1ad6f1ff3e96c is **not** an ancestor of HEAD (NOT IN TREE). Bug present since tc flower support landed (2020).

**Step 6.2 — Backport complications**
Record: Clean cherry-pick (auto-merge, no conflicts). Expected apply:
**clean**.

**Step 6.3 — Related fixes already present?**
Record: No equivalent fix found in 6.18.y history for this specific issue.

---

## Phase 7: Subsystem Context

**Step 7.1 — Subsystem / criticality**
Record: drivers/net/ethernet/hisilicon/hns3 — **IMPORTANT** (server/cloud NIC driver, tc offload data path).

**Step 7.2 — Activity**
Record: Actively maintained; recent TC/FD fixes in this file (e.g. d7beeb64be5ca, 6b36e5c4741f1).

---

## Phase 8: Impact and Risk Assessment

**Step 8.1 — Who is affected**
Record: Users of HiSilicon HNS3 NICs with hardware tc flower offload, configuring rules with partial src/dst IP or MAC matching.

**Step 8.2 — Trigger conditions**
Record: Common — tc flower rules matching only source or only destination IP/MAC. Unprivileged users can install tc rules (with appropriate capabilities/namespace policy).

**Step 8.3 — Failure mode / severity**
Record: Incorrect hardware packet classification / queue steering; rules may not match intended traffic or may match too narrowly. **Severity:
MEDIUM** — functional data-path bug, not kernel crash, deadlock, or memory corruption.

**Step 8.4 — Risk vs benefit**
Record:
- **Benefit:** MEDIUM — fixes real mis-steering for standard tc usage on production NICs
- **Risk:** LOW — 12 lines, mirrors proven ethtool logic
- **Ratio:** Favorable for stable

---

## Phase 9: Final Synthesis

**Evidence FOR backport:**
- Real, verifiable logic bug in tc flower offload path
- Bug present in 6.18.y since 2020
- Small, self-contained, applies cleanly
- Aligns tc path with existing ethtool FD logic in same driver
- Userspace-reachable via tc on widely deployed server NICs
- Maintainer-reviewed and merged

**Evidence AGAINST backport:**
- No crash, security, or corruption angle
- No user/fuzzer bug report
- Part of larger net-next enhancement series (though patch itself is independent)
- Port matching has same class of bug but is not addressed here

**Stable rules checklist:**
1. Obviously correct and tested? **PASS** — logic mirrors existing driver patterns; no Tested-by: but change is straightforward
2. Fixes a real bug affecting users? **PASS** — incorrect HW filtering for partial tc flower matches
3. Important issue? **PASS (borderline)** — incorrect packet steering on production networking path; not crash-level but user-visible and operationally significant
4. Small and contained? **PASS** — 12 lines, 1 file
5. No new features/APIs? **PASS**
6. Can apply to local tree? **PASS** — verified clean cherry-pick

**Exception category:** None (not quirk/ID/DT/docs/build).

---

## Problem Summary

This commit fixes a long-standing inconsistency in the HNS3 driver’s tc flower offload path. When users install tc flower rules specifying only source or only destination IP/MAC addresses, the flow dissector includes the address key with a zero mask for the unspecified side. The driver must mark those tuples as unused so hardware treats them as wildcards. Without this fix, unused_tuple is not set, hardware is programmed with zero-mask tuple values, and flow-director rules behave incorrectly.

For **Linux 6.18.y**, the buggy code is present, the fix is absent, the patch applies cleanly, and it is standalone. This is appropriate stable
material: a small, low-risk driver correctness fix for a userspace- visible data-path bug.

---

## Verification

- [Phase 1] Parsed commit message and tags from provided diff and git show 1ad6f1ff3e96c
- [Phase 2] Analyzed diff: +12 lines in hclge_get_cls_key_mac() and hclge_get_cls_key_ip()
- [Phase 2] Verified calc_x/calc_y macros and hclge_fd_convert_tuple() skip logic
- [Phase 2] Verified ethtool path already has zero-mask checks (hclge_fd_check_ether_tuple() etc.)
- [Phase 3] git blame: buggy code from 0205ec041ec61 (2020)
- [Phase 3] git merge-base --is-ancestor 1ad6f1ff3e96c HEAD → NOT IN TREE
- [Phase 3] Cherry-pick test: git cherry-pick --no-commit 1ad6f1ff3e96c → exit 0, auto-merge
- [Phase 4] b4 dig -c 1ad6f1ff3e96c → lore URL found
- [Phase 4] b4 dig -a → v1–v4 series revisions
- [Phase 4] b4 dig -w → netdev maintainers CC’d
- [Phase 4] b4 dig -m → cover letter retrieved; patch 2/6 context confirmed
- [Phase 5] Traced call chain: hns3_nic_setup_tc → hclge_add_cls_flower → hclge_parse_cls_flower
- [Phase 6] git describe HEAD → v6.18.44; Makefile 6.18.44
- [Phase 6] Read current hclge_main.c — buggy code confirmed present (no zero-mask checks in MAC/IP cls helpers)
- [Phase 8] Assessed severity as MEDIUM functional data-path bug
- UNVERIFIED: No direct lore stable-list discussion
- UNVERIFIED: No runtime test evidence beyond maintainer merge

**YES****Task result:** The branch search found commit 1ad6f1ff3e96c on master — it matches the patch under review and is not in the local 6.18.44 tree.

**Verdict (unchanged):** Backport **YES**. Small, standalone fix for incorrect tc flower hardware filtering when only src or dst IP/MAC is specified; applies cleanly to 6.18.y.

 .../net/ethernet/hisilicon/hns3/hns3pf/hclge_main.c  | 12 ++++++++++++
 1 file changed, 12 insertions(+)
drivers/net/ethernet/hisilicon/hns3/hns3pf/hclge_main.c +12 -0
index 7f174453928c1..08f7bda4ef4c4 100644
@@ -7261,6 +7261,10 @@ static void hclge_get_cls_key_mac(const struct flow_rule *flow,
 		ether_addr_copy(rule->tuples_mask.dst_mac, match.mask->dst);
 		ether_addr_copy(rule->tuples.src_mac, match.key->src);
 		ether_addr_copy(rule->tuples_mask.src_mac, match.mask->src);
+		if (is_zero_ether_addr(match.mask->dst))
+			rule->unused_tuple |= BIT(INNER_DST_MAC);
+		if (is_zero_ether_addr(match.mask->src))
+			rule->unused_tuple |= BIT(INNER_SRC_MAC);
 	} else {
 		rule->unused_tuple |= BIT(INNER_DST_MAC);
 		rule->unused_tuple |= BIT(INNER_SRC_MAC);
@@ -7309,6 +7313,10 @@ static int hclge_get_cls_key_ip(const struct flow_rule *flow,
 		rule->tuples.dst_ip[IPV4_INDEX] = be32_to_cpu(match.key->dst);
 		rule->tuples_mask.dst_ip[IPV4_INDEX] =
 						be32_to_cpu(match.mask->dst);
+		if (!match.mask->src)
+			rule->unused_tuple |= BIT(INNER_SRC_IP);
+		if (!match.mask->dst)
+			rule->unused_tuple |= BIT(INNER_DST_IP);
 	} else if (addr_type == FLOW_DISSECTOR_KEY_IPV6_ADDRS) {
 		struct flow_match_ipv6_addrs match;
 
@@ -7321,6 +7329,10 @@ static int hclge_get_cls_key_ip(const struct flow_rule *flow,
 				      match.key->dst.s6_addr32);
 		ipv6_addr_be32_to_cpu(rule->tuples_mask.dst_ip,
 				      match.mask->dst.s6_addr32);
+		if (ipv6_addr_any(&match.mask->src))
+			rule->unused_tuple |= BIT(INNER_SRC_IP);
+		if (ipv6_addr_any(&match.mask->dst))
+			rule->unused_tuple |= BIT(INNER_DST_IP);
 	} else {
 		rule->unused_tuple |= BIT(INNER_SRC_IP);
 		rule->unused_tuple |= BIT(INNER_DST_IP);
Signature · 1 line
2.53.0
author maintainer
#227 lore raw

PATCH 1/1 mailbox: imx: use devm_of_platform_populate()

In reply to Sasha Levin

From: Sebastian Andrzej Siewior <[email protected]>

[ Upstream commit dd1b321e8024fb01404fe163076c9010c5df8608 ]

The driver uses of_platform_populate() but does not remove the added devices on removal. This can lead to "double devices" on module removal followed by adding the module again.

Use devm_of_platform_populate() to remove the populated devices once the parent device is removed.

---

LLM Generated explanations, may be completely bogus:

The analysis is complete for **Linux 6.18.44**.

**Verdict: YES** — backport `mailbox: imx: use
devm_of_platform_populate() (dd1b321e8024f`).

The bug is present in this tree: of_platform_populate() was added in v6.9 (2a0ac450128bc) for i.MX95 SCMI SRAM sub-nodes, but imx_mu_remove() never depopulates them. On module reload or sysfs unbind/rebind, child platform devices can be duplicated and break SCMI setup.

The fix is a one-line change to devm_of_platform_populate(dev) at line 943 of drivers/mailbox/imx-mailbox.c. The mainline patch needs a minor context adjustment to apply here, but no functional rework.

 drivers/mailbox/imx-mailbox.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
drivers/mailbox/imx-mailbox.c +1 -1
index 3e52f70434c97..445cd50c1b667 100644
@@ -986,7 +986,7 @@ static int imx_mu_probe(struct platform_device *pdev)
 	if (ret)
 		goto err_out;
 
-	of_platform_populate(dev->of_node, NULL, NULL, dev);
+	devm_of_platform_populate(dev);
 
 	return 0;
 
Signature · 1 line
2.53.0
author maintainer
#228 lore raw

PATCH 1/1 mailbox: imx: Add a channel shutdown field

In reply to Sasha Levin

From: Sebastian Andrzej Siewior <[email protected]>

[ Upstream commit 5ccea7eacb7786c358833634f45700365f6c1d99 ]

sashiko complained about possible teardown problem. The scenario

CPU 0 CPU 1
imx_mu_isr() imx_mu_shutdown()

                                   imx_mu_xcr_rmw(priv, IMX_MU_RCR, 0, IMX_MU_xCR_RIEn(priv->dcfg->type, cp->idx));
    imx_mu_specific_rx()
      imx_mu_xcr_rmw(priv, IMX_MU_RCR, IMX_MU_xCR_RIEn(priv->dcfg->type, 0), 0);
                                   free_irq()

The RX event remains enabled because in this short window the RX event was disabled in ->shutdown() while the interrupt was active and then enabled again by the ISR while ->shutdown waited in free_irq().

This race requires timing and if happens can be problematic on shared handlers if the "removed" channel triggers an interrupt. In this case the irq-core will shutdown the interrupt with the "nobody cared" message.

Introduce imx_mu_con_priv::shutdown to signal that the channel is shutting down. This flag is set with the lock held (by imx_mu_xcr_clr_shut()). The unmask side uses imx_mu_xcr_set_act() which only enables the event if the channel has not been shutdown and serialises on the same lock.

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: mailbox: imx: Add a channel shutdown field

**Local tree:** v6.18.44 (linux-6.18.y, VERSION=6 PATCHLEVEL=18 SUBLEVEL=44)
**Upstream commit:** 5ccea7eacb778 (not present in this checkout; git apply --check succeeds)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Subject line
**Record:** [mailbox: imx] [Add] — adds a per-channel shutdown flag to coordinate teardown vs. ISR interrupt re-enablement.

### Step 1.2: Tags
**Record:**
- **Fixes:** — absent (expected for manual review)
- **Reported-by:** — absent; commit cites sashiko review feedback
- **Tested-by:** — absent
- **Reviewed-by:** Peng Fan <[email protected]> (NXP imx mailbox maintainer)
- **Reviewed-by:** Mathieu Poirier <[email protected]>
- **Link:** — absent
- **Cc: stable:** — absent (expected)
- **Signed-off-by:** Sebastian Andrzej Siewior, Jassi Brar (ignore pipeline-added SOBs)

Notable: two subsystem reviewers, including the NXP driver maintainer.

### Step 1.3: Body analysis
**Record:**
- **Bug:** Race between imx_mu_isr() → imx_mu_specific_rx() re- enabling RX interrupt enable bits and imx_mu_shutdown() disabling them, then blocking in free_irq().
- **Symptom:** RX interrupt remains enabled after channel teardown; on IRQF_SHARED lines, a spurious interrupt from the removed channel can trigger irq-core “nobody cared” handling and disable the shared IRQ.
- **Root cause:** imx_mu_shutdown() clears enable bits, but a concurrent ISR completion re-enables them via imx_mu_xcr_rmw() before free_irq() completes.
- **Version info:** None stated; mechanism has existed since the imx_mu_xcr_rmw() RX re-enable path was added (2021).

### Step 1.4: Hidden bug fix?
**Record:** Yes — despite “Add a channel shutdown field”, this is a race-condition bug fix disguised as structural addition. The shutdown bool is purely a synchronization mechanism.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Inventory
**Record:**
- **File:** drivers/mailbox/imx-mailbox.c (+36 / -4 lines)
- **Functions modified/added:** imx_mu_xcr_clr_shut() (new), imx_mu_xcr_set_act() (new), imx_mu_specific_rx(), imx_mu_startup(), imx_mu_shutdown()
- **Struct:** imx_mu_con_priv — adds bool shutdown
- **Scope:** Single-file, surgical fix

### Step 2.2: Code flow per hunk
**Record:**
1. **shutdown field added** → per-channel teardown state.
2. **imx_mu_xcr_clr_shut()** → atomically sets cp->shutdown = true and clears interrupt-enable bits under xcr_lock.
3. **imx_mu_xcr_set_act()** → re-enables interrupt bits only if !cp->shutdown, under same lock.
4. **imx_mu_specific_rx()** → final RX re-enable changed from unconditional imx_mu_xcr_rmw() to guarded imx_mu_xcr_set_act().
5. **imx_mu_startup()** → resets cp->shutdown = false after successful request_irq().
6. **imx_mu_shutdown()** → TX/RX/RXDB disable paths use imx_mu_xcr_clr_shut() instead of imx_mu_xcr_rmw().

**Before → After:**
- Shutdown clears enables, ISR can still re-enable → shutdown sets flag
+ clears enables; ISR re-enable is suppressed once shutdown started.

### Step 2.3: Bug mechanism
**Record:** **Race condition / synchronization fix.** Shutdown and ISR completion both modify the same control-register enable bits without coordinating teardown intent. The fix serializes intent via shutdown flag + existing xcr_lock.

### Step 2.4: Fix quality
**Record:** Obviously correct; minimal; uses existing xcr_lock. Low regression risk — only suppresses re-enable after shutdown has begun. cp->shutdown = false on startup ensures clean re-open.

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame
**Record:**
- imx_mu_shutdown() — since 2018 (2bb7005696e22)
- imx_mu_specific_rx() RX re-enable at line 382 — since 2021 (4f0b776ef58317, i.MX8ULP MU support)
- xcr_lock — present since initial imx MU driver (2bb7005696e22)
- Bug present in this tree for years.

### Step 3.2: Fixes: tag
**Record:** N/A — no Fixes: tag.

### Step 3.3: Related file history
**Record:**
- Recent related fix in tree: b5ef17917f3a7 “mailbox: imx: fix TXDB_V2 channel race condition” (2024) — same driver, same class of register RMW races.
- Commit is patch 02/10 of Siewior’s threaded-handler series on mainline, but **this patch is standalone** — it does not require the threaded-handler commits (verified: applies cleanly to current 6.18.y code; later series commits are separate enhancements).

### Step 3.4: Author context
**Record:** Sebastian Andrzej Siewior — active kernel contributor; recent imx mailbox work on mainline. Jassi Brar is mailbox subsystem maintainer (committed the patch).

### Step 3.5: Dependencies
**Record:** No prerequisites. Self-contained. Does not depend on fbc0f319cee18 (“Use channel index instead of zero”) which is a separate follow-up on mainline.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original discussion
**Record:** b4 dig -c 5ccea7eacb778 → [PATCH v3 02/10] at https://patc
h.msgid.link/[email protected] Series revisions: v1 (2026-05-29), v2 (2026-06-03), v3 (2026-06-17). Committed version matches v3.

### Step 4.2: Reviewers
**Record:** b4 dig -w CC’d: [email protected], [email protected], [email protected], Bjorn Andersson, Jassi Brar, Peng Fan, Mathieu Poirier, Pengutronix team.

### Step 4.3: Bug report
**Record:** Triggered by sashiko automated review during patch series development — not a syzbot/user crash report, but a concrete, code- reviewed race scenario with a documented failure mode.

### Step 4.4: Series context
**Record:** Part of 10-patch threaded-handler series, but this commit is independently applicable. Other series patches are not required for this fix to function.

### Step 4.5: Stable list
**Record:** Lore fetch blocked by bot protection; no stable-list discussion found via b4 dig. Absence of explicit stable nomination is not a negative signal.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key functions
**Record:** imx_mu_isr(), imx_mu_specific_rx(), imx_mu_shutdown(), imx_mu_startup(), mbox_free_channel() (caller)

### Step 5.2: Callers
**Record:**
- imx_mu_isr — IRQ handler registered via request_irq() in imx_mu_startup()
- imx_mu_shutdown — called from mbox_free_channel() in drivers/mailbox/mailbox.c:474-475
- imx_mu_specific_rx — called from imx_mu_isr() for IMX_MU_TYPE_RX on SCU/S4 configs (imx_mu_cfg_imx8_scu, imx_mu_cfg_imx8ulp_s4, imx_mu_cfg_imx93_s4)

### Step 5.3: Callees
**Record:** imx_mu_xcr_rmw/set_act/clr_shut use spin_lock_irqsave(&priv->xcr_lock); hardware register read/write; free_irq(); mbox_chan_received_data()

### Step 5.4: Reachability
**Record:**

```
mbox_free_channel() → imx_mu_shutdown()     [teardown path]
IRQ → imx_mu_isr() → imx_mu_specific_rx()   [interrupt path]
```

Triggered during channel release (driver unbind, remoteproc shutdown, SCMI client teardown). Reachable on normal i.MX embedded operation.

### Step 5.5: Similar patterns
**Record:** Prior imx mailbox race fix b5ef17917f3a7 (TXDB_V2) already in this tree. Same driver, same register-coordination problem class.

---

## PHASE 6: CROSS-REFERENCE WITH LOCAL TREE

### Step 6.1: Buggy code present?
**Record:** **Yes.** Current tree at drivers/mailbox/imx-mailbox.c:
- Line 382: unconditional RX re-enable in imx_mu_specific_rx()
- Lines 647-650: shutdown clears RX/RXDB enables via imx_mu_xcr_rmw()
- Line 601-602: IRQF_SHARED when !(priv->dcfg->type & IMX_MU_V2_IRQ) — applies to imx6sx, imx7ulp, imx8ulp, imx8ulp_s4, imx8_scu, imx8_seco, imx95 variants (not imx93_s4 which has dedicated IRQs)

### Step 6.2: Backport complications
**Record:** **Clean apply** — git show 5ccea7eacb778 | git apply --check succeeds with no conflicts.

### Step 6.3: Fix already present?
**Record:** No — git merge-base --is-ancestor 5ccea7eacb778 HEAD returns non-zero; grep finds no imx_mu_xcr_clr_shut or shutdown field in imx_mu_con_priv.

---

## PHASE 7: SUBSYSTEM CONTEXT

### Step 7.1: Subsystem criticality
**Record:** drivers/mailbox — **IMPORTANT** for i.MX/ARM embedded platforms. imx MU is used for SCMI, SECO, System Manager, and remoteproc IPC.

### Step 7.2: Activity
**Record:** Actively maintained; multiple imx mailbox fixes in 6.18.y and mainline since 2024.

---

## PHASE 8: IMPACT AND RISK

### Step 8.1: Who is affected
**Record:** Users of CONFIG_IMX_MBOX on i.MX platforms using SCU/S4/specific RX paths with shared IRQs — imx8ulp_s4, imx8_scu, imx95-ele/v2x, etc.

### Step 8.2: Trigger conditions
**Record:** Channel teardown (mbox_free_channel) concurrent with in- flight RX interrupt processing. Timing-dependent but realistic during driver unbind, remoteproc stop, or subsystem restart. Not directly userspace-triggerable, but triggered by normal admin/driver lifecycle operations.

### Step 8.3: Failure severity
**Record:** Spurious interrupt on freed channel → irq-core “nobody cared” → **shared IRQ disabled** → loss of mailbox/SCMI/remoteproc communication. **Severity: HIGH** (can render IPC subsystem non- functional; potential system hang depending on dependents).

### Step 8.4: Risk-benefit
**Record:**
- **Benefit:** HIGH — prevents IRQ disable on shared lines during teardown
- **Risk:** LOW — 40 lines, single file, uses existing lock, reviewed by maintainers
- **Ratio:** Strongly favors backport

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence summary

**FOR backport:**
- Real, verifiable race between ISR and shutdown
- Concrete failure mode (spurious IRQ → “nobody cared” → IRQ disabled)
- Affects production i.MX embedded platforms with shared IRQs
- Small, surgical, reviewed fix
- Applies cleanly to 6.18.y
- Bug code present since 2021
- Prior similar imx mailbox race fix already in stable tree

**AGAINST backport:**
- Timing-dependent; no user crash report or syzbot report
- Part of a larger series (but this patch is standalone)
- Sashiko report is review-tool feedback, not field report

**Unresolved:** Full lore thread content unavailable due to bot protection; no explicit stable nomination found.

### Step 9.2: Stable rules checklist
1. Obviously correct and tested? **PASS** — clear lock+flag pattern; reviewed by NXP maintainer and Linaro reviewer
2. Fixes a real bug? **PASS** — verified race in current tree code
3. Important issue? **PASS** — IRQ disable on shared handler can break critical IPC
4. Small and contained? **PASS** — 1 file, ~40 lines
5. No new features/APIs? **PASS** — internal driver flag only
6. Can apply to local tree? **PASS** — clean apply verified

### Step 9.3: Exception categories
**Record:** None (not a device ID, quirk, DT, build, or docs fix) — qualifies on race-condition bug-fix merits.

### Step 9.4: Decision rationale
This fix addresses a real teardown race in the imx mailbox driver that can leave interrupt enables active after channel shutdown, causing spurious interrupts on shared IRQ lines and irq-core disablement. The bug exists in v6.18.44, the fix is minimal and self-contained, applies cleanly, and has maintainer review. While timing-dependent, the consequence (shared IRQ shutdown breaking SCMI/remoteproc IPC) is serious enough for stable inclusion, consistent with prior imx mailbox race fixes already in this tree.

---

## Verification

- [Phase 1] Parsed commit 5ccea7eacb778: subject, body, Reviewed-by tags (Peng Fan, Mathieu Poirier); no Fixes/Reported-by/Cc:stable
- [Phase 2] Diff analysis: +36/-4 in imx-mailbox.c; race fix via shutdown flag + xcr_clr_shut/xcr_set_act
- [Phase 3] git describe HEAD: v6.18.44; git blame: buggy RX re- enable since 4f0b776ef58317 (2021); shutdown since 2bb7005696e22 (2018)
- [Phase 3] Related commit b5ef17917f3a7 TXDB_V2 race fix present in tree
- [Phase 3] git merge-base --is-ancestor 5ccea7eacb778 HEAD: NOT in tree (exit 1)
- [Phase 4] b4 dig -c 5ccea7eacb778: found v3 02/10 at patch.msgid.link/20260617-...
- [Phase 4] b4 dig -a: v1/v2/v3 series revisions found
- [Phase 4] b4 dig -w: maintainers and imx lists CC'd
- [Phase 4] Lore full-thread fetch: blocked by Anubis bot protection (UNVERIFIED for inline reviewer stable comments)
- [Phase 5] Read imx_mu_isr, imx_mu_specific_rx, imx_mu_shutdown, mbox_free_channel call chain
- [Phase 5] Verified IRQF_SHARED at line 601-602 for non-IMX_MU_V2_IRQ configs
- [Phase 5] Verified imx_mu_specific_rx used by imx8_scu, imx8ulp_s4, imx93_s4 configs
- [Phase 6] Confirmed buggy code at lines 382, 647-650 in current tree
- [Phase 6] git show 5ccea7eacb778 | git apply --check: succeeds (clean apply)
- [Phase 6] Grep: no imx_mu_xcr_clr_shut or shutdown field in current tree
- [Phase 7] CONFIG_IMX_MBOX in drivers/mailbox/Kconfig
- [Phase 8] Failure mode: spurious IRQ → irq disable on shared line; severity HIGH for IPC subsystems

**YES**

 drivers/mailbox/imx-mailbox.c | 40 +++++++++++++++++++++++++++++++----
 1 file changed, 36 insertions(+), 4 deletions(-)
drivers/mailbox/imx-mailbox.c +36 -4
index a45c3e6d76575..3e52f70434c97 100644
@@ -82,6 +82,7 @@ struct imx_mu_con_priv {
 	enum imx_mu_chan_type	type;
 	struct mbox_chan	*chan;
 	struct work_struct 	txdb_work;
+	bool			shutdown;
 };
 
 struct imx_mu_priv {
@@ -221,6 +222,36 @@ static u32 imx_mu_xcr_rmw(struct imx_mu_priv *priv, enum imx_mu_xcr type, u32 se
 	return val;
 }
 
+static void imx_mu_xcr_clr_shut(struct imx_mu_priv *priv, struct imx_mu_con_priv *cp,
+				enum imx_mu_xcr type, u32 clr)
+{
+	unsigned long flags;
+	u32 val;
+
+	spin_lock_irqsave(&priv->xcr_lock, flags);
+	cp->shutdown = true;
+
+	val = imx_mu_read(priv, priv->dcfg->xCR[type]);
+	val &= ~clr;
+	imx_mu_write(priv, val, priv->dcfg->xCR[type]);
+	spin_unlock_irqrestore(&priv->xcr_lock, flags);
+}
+
+static void imx_mu_xcr_set_act(struct imx_mu_priv *priv, struct imx_mu_con_priv *cp,
+			       enum imx_mu_xcr type, u32 set)
+{
+	unsigned long flags;
+	u32 val;
+
+	spin_lock_irqsave(&priv->xcr_lock, flags);
+	if (!cp->shutdown) {
+		val = imx_mu_read(priv, priv->dcfg->xCR[type]);
+		val |= set;
+		imx_mu_write(priv, val, priv->dcfg->xCR[type]);
+	}
+	spin_unlock_irqrestore(&priv->xcr_lock, flags);
+}
+
 static int imx_mu_generic_tx(struct imx_mu_priv *priv,
 			     struct imx_mu_con_priv *cp,
 			     void *data)
@@ -379,7 +410,7 @@ static int imx_mu_specific_rx(struct imx_mu_priv *priv, struct imx_mu_con_priv *
 		*data++ = imx_mu_read(priv, priv->dcfg->xRR + (i % num_rr) * 4);
 	}
 
-	imx_mu_xcr_rmw(priv, IMX_MU_RCR, IMX_MU_xCR_RIEn(priv->dcfg->type, 0), 0);
+	imx_mu_xcr_set_act(priv, cp, IMX_MU_RCR, IMX_MU_xCR_RIEn(priv->dcfg->type, 0));
 	mbox_chan_received_data(cp->chan, (void *)priv->msg);
 
 	return 0;
@@ -607,6 +638,7 @@ static int imx_mu_startup(struct mbox_chan *chan)
 		return ret;
 	}
 
+	cp->shutdown = false;
 	switch (cp->type) {
 	case IMX_MU_TYPE_RX:
 		imx_mu_xcr_rmw(priv, IMX_MU_RCR, IMX_MU_xCR_RIEn(priv->dcfg->type, cp->idx), 0);
@@ -641,13 +673,13 @@ static void imx_mu_shutdown(struct mbox_chan *chan)
 
 	switch (cp->type) {
 	case IMX_MU_TYPE_TX:
-		imx_mu_xcr_rmw(priv, IMX_MU_TCR, 0, IMX_MU_xCR_TIEn(priv->dcfg->type, cp->idx));
+		imx_mu_xcr_clr_shut(priv, cp, IMX_MU_TCR, IMX_MU_xCR_TIEn(priv->dcfg->type, cp->idx));
 		break;
 	case IMX_MU_TYPE_RX:
-		imx_mu_xcr_rmw(priv, IMX_MU_RCR, 0, IMX_MU_xCR_RIEn(priv->dcfg->type, cp->idx));
+		imx_mu_xcr_clr_shut(priv, cp, IMX_MU_RCR, IMX_MU_xCR_RIEn(priv->dcfg->type, cp->idx));
 		break;
 	case IMX_MU_TYPE_RXDB:
-		imx_mu_xcr_rmw(priv, IMX_MU_GIER, 0, IMX_MU_xCR_GIEn(priv->dcfg->type, cp->idx));
+		imx_mu_xcr_clr_shut(priv, cp, IMX_MU_GIER, IMX_MU_xCR_GIEn(priv->dcfg->type, cp->idx));
 		break;
 	case IMX_MU_TYPE_RST:
 		imx_mu_xcr_rmw(priv, IMX_MU_CR, IMX_MU_xCR_RST(priv->dcfg->type), 0);
Signature · 1 line
2.53.0
#229 lore raw

Re: [PATCH AUTOSEL 6.18-6.12] mailbox: imx: Add a channel shutdown field

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [High] The patch fixes the teardown race for RX channels but misses the identical race condition for TX channels, allowing spurious interrupts. --

commit 339489ae41b0a2b0727c73521707e00976aca9f5
Author: Sebastian Andrzej Siewior <[email protected]>

mailbox: imx: Add a channel shutdown field

This commit introduces a shutdown flag to imx_mu_con_priv to coordinate channel teardown and prevent the ISR from re-enabling interrupts after imx_mu_shutdown() has disabled them. The flag is checked by a new function imx_mu_xcr_set_act() before modifying the control register.

Quoted 4 lines
drivers/mailbox/imx-mailbox.c +0 -0
index 6778afc64a048..44c2cc06b794e 100644

[ ... ]

Quoted 34 lines
drivers/mailbox/imx-mailbox.c +30 -0
@@ -220,6 +221,36 @@ static u32 imx_mu_xcr_rmw(struct imx_mu_priv *priv, enum imx_mu_xcr type, u32 se
 	return val;
 }
 
+static void imx_mu_xcr_clr_shut(struct imx_mu_priv *priv, struct imx_mu_con_priv *cp,
+				enum imx_mu_xcr type, u32 clr)
+{
+	unsigned long flags;
+	u32 val;
+
+	spin_lock_irqsave(&priv->xcr_lock, flags);
+	cp->shutdown = true;
+
+	val = imx_mu_read(priv, priv->dcfg->xCR[type]);
+	val &= ~clr;
+	imx_mu_write(priv, val, priv->dcfg->xCR[type]);
+	spin_unlock_irqrestore(&priv->xcr_lock, flags);
+}
+
+static void imx_mu_xcr_set_act(struct imx_mu_priv *priv, struct imx_mu_con_priv *cp,
+			       enum imx_mu_xcr type, u32 set)
+{
+	unsigned long flags;
+	u32 val;
+
+	spin_lock_irqsave(&priv->xcr_lock, flags);
+	if (!cp->shutdown) {
+		val = imx_mu_read(priv, priv->dcfg->xCR[type]);
+		val |= set;
+		imx_mu_write(priv, val, priv->dcfg->xCR[type]);
+	}
+	spin_unlock_irqrestore(&priv->xcr_lock, flags);
+}
+

[ ... ]

drivers/mailbox/imx-mailbox.c static int imx_mu_specific_rx(struct imx_mu_priv *priv, struct imx_mu_con_priv * · line 414

Quoted 9 lines
drivers/mailbox/imx-mailbox.c +1 -1
@@ -377,7 +408,7 @@ static int imx_mu_specific_rx(struct imx_mu_priv *priv, struct imx_mu_con_priv *
 		*data++ = imx_mu_read(priv, priv->dcfg->xRR + (i % num_rr) * 4);
 	}
 
-	imx_mu_xcr_rmw(priv, IMX_MU_RCR, IMX_MU_xCR_RIEn(priv->dcfg->type, 0), 0);
+	imx_mu_xcr_set_act(priv, cp, IMX_MU_RCR, IMX_MU_xCR_RIEn(priv->dcfg->type, 0));
 	mbox_chan_received_data(cp->chan, (void *)priv->msg);
 
 	return 0;

[Severity: High]
This is a pre-existing issue, but while this patch successfully fixes the teardown race for RX channels, does the identical race still exist for TX channels?

If mbox_free_channel() is called while a TX interrupt is active and there are pending TX messages, it calls imx_mu_shutdown() which sets cp->shutdown = true and clears the TX interrupt enable bit, then blocks in free_irq().

When the concurrent ISR completes the current TX, it calls mbox_chan_txdone(), triggering msg_submit() to send the next queued message via imx_mu_generic_tx() or imx_mu_specific_tx().

Both functions unconditionally rewrite the TX interrupt enable bit using imx_mu_xcr_rmw(), bypassing the new shutdown flag:

drivers/mailbox/imx-mailbox.c:imx_mu_generic_tx() {
    ...
	case IMX_MU_TYPE_TX:
		imx_mu_write(priv, *arg, priv->dcfg->xTR + cp->idx * 4);
		imx_mu_xcr_rmw(priv, IMX_MU_TCR, IMX_MU_xCR_TIEn(priv->dcfg->type, cp->idx), 0);
		break;
    ...
}

And similarly in imx_mu_specific_tx():

drivers/mailbox/imx-mailbox.c:imx_mu_specific_tx() {
    ...
		for (; i < size; i++) {
			ret = readl_poll_timeout(...);
			if (ret) {
				...
			}
			imx_mu_write(priv, *arg++, priv->dcfg->xTR + (i % num_tr) * 4);
		}

		imx_mu_xcr_rmw(priv, IMX_MU_TCR, IMX_MU_xCR_TIEn(priv->dcfg->type, cp->idx), 0);
		break;
    ...
}

Should these TX paths also be updated to use imx_mu_xcr_set_act() to prevent a spurious interrupt from disabling the shared IRQ line during teardown?

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

PATCH 1/1 wifi: mac80211: unify link STA removal in vif link removal

In reply to Sasha Levin

From: Johannes Berg <[email protected]>

[ Upstream commit 79fb99e16f60a77cbd2824695d98aa34ebbb9d69 ]

There are multiple cases where interface links are removed and the station links need to be removed with them, e.g. in mlme.c we have both received and transmitted multi-link reconfiguration, doing the two things in different order, the former deleting STA links when the vif link change may still fail.

It's also not clear that userspace (hostapd) couldn't, at least in theory, remove a link from an interface without removing the station links first, or even leave stations that aren't MLO-capable, using that link.

Unify this code into ieee80211_vif_update_links() so that it always happens, always happens in the right order and is transactional (i.e. failures are handled correctly.)

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: wifi: mac80211: unify link STA removal in vif link removal

**Local tree:** v6.18.44 (stable/linux-6.18.y, detached HEAD)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Subject line
**Record:** [wifi: mac80211] [unify] — consolidate station-link teardown when VIF links are removed during MLO (multi-link) reconfiguration.

### Step 1.2: Tags
**Record:**
- **Link:** https://patch.msgid.link/20260529102644.c352f73a4658... (original submission)
- **Signed-off-by:** Johannes Berg <[email protected]> (mac80211/cfg80211 maintainer)
- **No** Fixes:, Reported-by:, Tested-by:, Reviewed-by:, Acked-by:, or
Cc: stable tags
- **Notable:** No fuzzer or user bug-report tags; author is subsystem maintainer

### Step 1.3: Body analysis
**Record:**
- **Bug:** Multiple code paths remove interface (VIF) links without consistently removing associated station links, and two paths (ml_reconf_work vs ieee80211_mgd_assoc_ml_reconf) do cleanup in different order.
- **Symptom:** Stale/orphaned per-link STA state; in one path STA links are removed before VIF update and a VIF update failure leaves inconsistent state.
- **Root cause:** STA link removal is duplicated ad hoc in mlme.c instead of being tied transactionally to ieee80211_vif_update_links().
- **Also covers:** Userspace (hostapd) removing a VIF link without first removing station links, or leaving non-MLO-capable stations on that link.

### Step 1.4: Hidden bug fix?
**Record:** Yes. Described as “unify,” but it fixes a real state- management bug: VIF links and STA links can diverge, leaving stale link_sta entries and incorrect driver notifications.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Inventory
**Record:**
- **Files:** net/mac80211/link.c (+~30 lines), net/mac80211/mlme.c (-~25 lines)
- **Functions modified:** ieee80211_vif_update_links(), ieee80211_ml_reconf_work(), ieee80211_mgd_assoc_ml_reconf()
- **Scope:** Two-file, surgical refactor of MLO link-removal logic

### Step 2.2: Code flow per hunk

**link.c — ieee80211_vif_update_links()**
- **Before:** After successful driver VIF link update, only deflink teardown; no STA link cleanup.
- **After:** After successful driver update:
1. For each STA on this sdata, remove only the links being dropped (skip STAs that would lose all links).
2. sta_info_flush(sdata, link_id) for each removed link (flushes STAs with no links left).
- **Path:** Success path only; runs under wiphy lock after drv_change_vif_links().

**mlme.c — ieee80211_ml_reconf_work()**
- **Before (patch base):** Removed AP STA links *before* ieee80211_vif_set_links().
- **After:** STA cleanup delegated to ieee80211_vif_update_links().

**mlme.c — ieee80211_mgd_assoc_ml_reconf()**
- **Before:** Called ieee80211_vif_set_links(), then manually looped ieee80211_sta_remove_link().
- **After:** Only ieee80211_vif_set_links(); STA cleanup is internal.

### Step 2.3: Bug mechanism
**Record:** **Logic / reference-counting / state consistency fix (category g + c).**
- VIF valid_links and per-STA valid_links/link_sta structures can diverge.
- ieee80211_sta_remove_link() calls drv_change_sta_links() and tears down link_sta hash/debugfs entries.
- Without unified cleanup, removed VIF links leave stale per-link STA state and mismatched driver notifications.

### Step 2.4: Fix quality
**Record:** Fix is obviously correct and minimal. Centralizing in the single VIF-link update function ensures all callers (ml_reconf_work, mgd_assoc_ml_reconf, ieee80211_del_intf_link, etc.) behave consistently. Runs only after successful driver VIF update, so it is transactional. Low regression risk; uses existing ieee80211_sta_remove_link() and sta_info_flush() APIs.

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame / introduction
**Record:**
- ieee80211_vif_update_links() core logic dates to Johannes Berg, Sep 2022 (MLO link handling).
- MLO dynamic link add/remove introduced in 36e05b0b83903 (2025-01-13, Ilan Peer) — **present in this tree**.
- ieee80211_mgd_assoc_ml_reconf() manual STA removal present since 36e05b0b83903.
- Related follow-up on mainline (not in 6.18.y): 84674b03d8bf “Remove deleted sta links in ieee80211_ml_reconf_work()” — **NOT an ancestor of HEAD**.

### Step 3.2: Fixes: tag
**Record:** N/A — no Fixes: tag.

### Step 3.3: Related file history
**Record:** Recent related commits in tree include bounds-checking in ieee80211_ml_reconfiguration, ml_reconf_work hrtimer conversion, and error-path link teardown (0f7eaeb950adb). No duplicate fix for this specific issue found.

### Step 3.4: Author context
**Record:** Johannes Berg is mac80211 maintainer. Recent link.c commits from him include MLO CSA and link-change handling.

### Step 3.5: Dependencies
**Record:** Standalone. Requires MLO dynamic link removal code (36e05b0b83903), which is in this tree. Does **not** require 84674b03d8bf (that commit is absent here; this patch supersedes that approach).

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original discussion
**Record:** b4 dig -c <sha> could not be run (commit not in tree). Direct lore/patch.msgid.link fetch blocked by Anubis bot protection. **UNVERIFIED:** full review thread content.

### Step 4.2: Reviewers
**Record:** **UNVERIFIED** — could not fetch thread via WebFetch or b4.

### Step 4.3: Bug reports
**Record:** No Reported-by in commit message. Related mainline commit 84674b03d8bf (not in 6.18.y) was later fixed with “Reported-and-
tested-by: Jouni Malinen” for a hashtable issue caused by wrong STA-link removal ordering — indicates real-world MLO reconfiguration testing by hostapd/wpa_supplicant author.

### Step 4.4: Series context
**Record:** Standalone fix, not part of a numbered series.

### Step 4.5: Stable list
**Record:** **UNVERIFIED** — lore stable search inaccessible.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key functions
**Record:** ieee80211_vif_update_links(), ieee80211_vif_set_links(), ieee80211_sta_remove_link(), sta_info_flush(), ieee80211_ml_reconf_work(), ieee80211_mgd_assoc_ml_reconf(), ieee80211_del_intf_link()

### Step 5.2: Callers of ieee80211_vif_set_links() **Record:** 15+ call sites in mlme.c, cfg.c, link.c, iface.c — including:
- ieee80211_ml_reconf_work() — AP-initiated RX reconfiguration
- ieee80211_mgd_assoc_ml_reconf() — STA-initiated TX reconfiguration
- ieee80211_del_intf_link() — nl80211 userspace link deletion (hostapd)
- Association, disassociation, CSA paths

### Step 5.3: Callees
**Record:** ieee80211_sta_remove_link() → drv_change_sta_links(), sta_remove_link() (hash removal, RCU free). sta_info_flush() → __sta_info_destroy_part1/2().

### Step 5.4: Reachability
**Record:** Triggered during MLO link reconfiguration (beacon IE or userspace nl80211) and AP link teardown. Reachable from normal WiFi management operations on MLO-capable hardware; not init-only or debug- only.

### Step 5.5: Similar patterns
**Record:** ieee80211_del_link_station() in cfg.c manually calls ieee80211_sta_remove_link() for explicit per-station link deletion — a separate, explicit API. VIF-level link removal previously lacked equivalent centralized STA cleanup.

---

## PHASE 6: CROSS-REFERENCING AGAINST LOCAL TREE (6.18.44)

### Step 6.1: Does the buggy code exist?
**Record:** **Yes.** Verified in this checkout:

1. **ieee80211_ml_reconf_work()** (lines 6943–6946): calls ieee80211_vif_set_links() with **no** STA link removal. AP- initiated link removal leaves stale AP-STA per-link state.

2. **ieee80211_mgd_assoc_ml_reconf()** (lines 10859–10874): removes VIF links first, then manually removes STA links — partial fix only for the AP STA on TX-initiated path.

3. **ieee80211_del_intf_link()** (cfg.c line 5373): calls ieee80211_vif_set_links() with **no** STA link cleanup — affects AP mode when userspace removes a link.

MLO dynamic link support present since 36e05b0b83903 (Jan 2025).

### Step 6.2: Backport complications
**Record:** Expected **clean apply**. Patch hunks align with current link.c/mlme.c structure. No kzalloc_obj mismatch in actual changed lines.

### Step 6.3: Related fixes already present?
**Record:** None found for this unified STA cleanup. 84674b03d8bf (partial ml_reconf_work fix) is **not** in this tree.

---

## PHASE 7: SUBSYSTEM CONTEXT

### Step 7.1: Subsystem / criticality
**Record:** net/mac80211 — **IMPORTANT** (WiFi stack). MLO is config- dependent (ieee80211_vif_is_mld()), but growing on WiFi 7 hardware.

### Step 7.2: Activity
**Record:** Actively developed; multiple MLO fixes landed in 6.18.y recently.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: Who is affected
**Record:** MLO-capable STA and AP users performing dynamic link removal/reconfiguration (WiFi 7 multi-link). Not universal, but real and growing hardware segment.

### Step 8.2: Trigger conditions
**Record:**
- AP beacon ML reconfiguration IE removing links (ieee80211_ml_reconf_work)
- Userspace ML reconfiguration request (ieee80211_mgd_assoc_ml_reconf)
- nl80211 interface link deletion (ieee80211_del_intf_link)
- Unprivileged users cannot directly trigger; wpa_supplicant/hostapd or AP beacon-driven.

### Step 8.3: Failure mode severity
**Record:** Stale link_sta entries, mismatched drv_change_vif_links vs drv_change_sta_links state, potential driver confusion, connection instability after link removal, possible resource leaks. **Severity:
MEDIUM-HIGH** for MLO users (functional correctness / potential driver issues); not a confirmed panic/CVE.

### Step 8.4: Risk-benefit
**Record:**
- **Benefit:** MEDIUM-HIGH for MLO users — fixes a longstanding gap since dynamic link removal was added; covers all VIF link removal paths.
- **Risk:** LOW — ~40 lines, uses existing helpers, maintainer-authored, only on success path.
- **Ratio:** Favorable.

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence summary

**FOR backport:**
- Real bug: VIF and STA link state can diverge on link removal
- In 6.18.44, ieee80211_ml_reconf_work never cleans STA links at all
- ieee80211_del_intf_link never cleans STA links
- Fix is small, centralized, transactional, from subsystem maintainer
- MLO dynamic link removal code is in this tree since Jan 2025

**AGAINST backport:**
- MLO user base still limited on stable kernels
- No syzbot/crash report or Fixes: tag
- Commit message partly describes ordering bug from 84674b03d8bf, which is not in 6.18.y (though the underlying gap is worse here)
- Failure mode is state inconsistency rather than proven kernel oops

**UNRESOLVED:**
- Full mailing-list review thread (Anubis blocked fetch)
- Whether stable maintainers already discussed this specific patch

### Step 9.2: Stable rules checklist

| Criterion | Result |
|-----------|--------|
| 1. Obviously correct and tested? | **PASS** — logic is clear; no
Tested-by, but maintainer-authored |
| 2. Fixes real bug affecting users? | **PASS** — verified stale STA
state on multiple paths in 6.18.44 |
| 3. Important issue? | **PASS** — MEDIUM-HIGH for MLO link
reconfiguration correctness |
| 4. Small and contained? | **PASS** — ~2 files, ~40 net lines |
| 5. No new features/APIs? | **PASS** — internal refactor only |
| 6. Can apply to local tree? | **PASS** — code exists, clean apply
expected |

### Step 9.3: Exception categories
**Record:** None (not device ID, quirk, DT, build, or docs).

### Step 9.4: Decision rationale

This commit fixes a genuine mac80211 MLO state-management bug present in linux-6.18.y since dynamic link removal was introduced. In the current tree, AP-initiated link removal (ieee80211_ml_reconf_work) and nl80211 link deletion (ieee80211_del_intf_link) remove VIF links without cleaning associated STA per-link state. Only the TX-initiated reconfiguration path partially handles this, and even there the logic is duplicated and ordering-sensitive. Centralizing STA link teardown inside ieee80211_vif_update_links() after a successful driver update is the correct transactional fix and benefits every caller. While MLO is not yet universal, the bug affects real WiFi 7 deployments and the fix is low-risk.

---

## Verification

- **[Phase 1]** Parsed subject, tags, body from provided commit message
- **[Phase 2]** Analyzed provided diff; read current link.c:275-422, mlme.c:6901-6959, mlme.c:10855-10880, sta_info.c:3370-3384, cfg.c:5359-5374
- **[Phase 3]** git describe HEAD → v6.18.44; git log --oneline -15 -- net/mac80211/link.c mlme.c
- **[Phase 3]** git show 36e05b0b83903 — MLO dynamic link removal origin (2025-01-13), in tree
- **[Phase 3]** git merge-base --is-ancestor 84674b03d8bf HEAD → NOT_IN_TREE
- **[Phase 3]** git log -p -S 'ieee80211_sta_remove_link' -- net/mac80211/mlme.c — history of STA removal in mlme paths
- **[Phase 3]** git blame -L 380,394 net/mac80211/link.c — ieee80211_vif_update_links history
- **[Phase 4]** WebFetch patch.msgid.link and lore.kernel.org — blocked by Anubis; **UNVERIFIED** thread content
- **[Phase 4]** b4 dig — commit not in tree, could not match by SHA; **UNVERIFIED** review thread
- **[Phase 5]** grep ieee80211_vif_set_links — 15 call sites across mac80211
- **[Phase 5]** Traced ieee80211_sta_remove_link() and sta_info_flush() implementations
- **[Phase 6]** Confirmed ieee80211_ml_reconf_work has no STA link removal in current tree (lines 6943-6946)
- **[Phase 6]** Confirmed ieee80211_mgd_assoc_ml_reconf has manual STA removal after VIF update (lines 10868-10874)
- **[Phase 6]** Confirmed ieee80211_del_intf_link calls only ieee80211_vif_set_links (cfg.c:5373)
- **[Phase 6]** git merge-base --is-ancestor 36e05b0b83903 HEAD → in tree
- **[Phase 8]** Failure mode: VIF/STA link state divergence on MLO link removal; severity MEDIUM-HIGH for MLO users

**YES****Verdict: YES** — backport to linux-6.18.y.

This patch fixes a real MLO bug in 6.18.44: when VIF links are removed, associated station per-link state isn’t always cleaned up. Paths like ieee80211_ml_reconf_work() and ieee80211_del_intf_link() only update VIF links and leave stale link_sta entries; only the TX reconfiguration path does partial manual cleanup.

The fix centralizes STA link teardown inside ieee80211_vif_update_links() after a successful driver update, so all callers stay consistent. It’s small (~40 lines, 2 files), low risk, and from the mac80211 maintainer. MLO dynamic link removal has been in this tree since January 2025 (36e05b0b83903), so the bug is present here.

**YES**

 net/mac80211/link.c | 30 ++++++++++++++++++++++++++++++
 net/mac80211/mlme.c |  8 --------
 2 files changed, 30 insertions(+), 8 deletions(-)
net/mac80211/link.c +30 -0
index 235e370c2b59e..02eec9d69f50d 100644
@@ -280,6 +280,7 @@ static int ieee80211_vif_update_links(struct ieee80211_sub_if_data *sdata,
 	u16 old_active = sdata->vif.active_links;
 	unsigned long add = new_links & ~old_links;
 	unsigned long rem = old_links & ~new_links;
+	unsigned long sta_rem = rem;
 	unsigned int link_id;
 	int ret;
 	struct link_container *links[IEEE80211_MLD_MAX_NUM_LINKS] = {}, *link;
@@ -287,6 +288,7 @@ static int ieee80211_vif_update_links(struct ieee80211_sub_if_data *sdata,
 	struct ieee80211_link_data *old_data[IEEE80211_MLD_MAX_NUM_LINKS];
 	bool use_deflink = old_links == 0; /* set for error case */
 	bool non_sta = sdata->vif.type != NL80211_IFTYPE_STATION;
+	struct sta_info *sta;
 
 	lockdep_assert_wiphy(sdata->local->hw.wiphy);
 
@@ -391,6 +393,34 @@ static int ieee80211_vif_update_links(struct ieee80211_sub_if_data *sdata,
 		goto free;
 	}
 
+	/* try to remove links that are now invalid from (MLO) stations */
+	list_for_each_entry(sta, &sdata->local->sta_list, list) {
+		unsigned long rem_links = sta->sta.valid_links & sta_rem;
+
+		if (sta->sdata != sdata)
+			continue;
+
+		/*
+		 * skip stations that would have no links left,
+		 * those will be removed completely later
+		 */
+		if (sta->sta.valid_links == rem_links)
+			continue;
+
+		for_each_set_bit(link_id, &rem_links,
+				 IEEE80211_MLD_MAX_NUM_LINKS)
+			ieee80211_sta_remove_link(sta, link_id);
+	}
+
+	/*
+	 * Remove stations using any removed links. Note that due
+	 * to the above station link removal, this only removes
+	 * stations that were skipped above because they'd have no
+	 * links left after link removal.
+	 */
+	for_each_set_bit(link_id, &sta_rem, IEEE80211_MLD_MAX_NUM_LINKS)
+		sta_info_flush(sdata, link_id);
+
 	/* use deflink/bss_conf again if and only if there are no more links */
 	use_deflink = new_links == 0;
 
net/mac80211/mlme.c +0 -8
index 3c33e56c12a80..5c855c95858e1 100644
@@ -10906,14 +10906,6 @@ int ieee80211_mgd_assoc_ml_reconf(struct ieee80211_sub_if_data *sdata,
 			goto err_free;
 		}
 
-		for (link_id = 0; link_id < IEEE80211_MLD_MAX_NUM_LINKS;
-		     link_id++) {
-			if (!(req->rem_links & BIT(link_id)))
-				continue;
-
-			ieee80211_sta_remove_link(sta, link_id);
-		}
-
 		/* notify the driver and upper layers */
 		ieee80211_vif_cfg_change_notify(sdata,
 						BSS_CHANGED_MLD_VALID_LINKS);
Signature · 1 line
2.53.0
author maintainer
#231 lore raw

PATCH 1/1 net: thunderx: fix PTP device ref leak in nicvf_probe()

In reply to Sasha Levin

From: Haoxiang Li <[email protected]>

[ Upstream commit 2bcf59eefb9f00a2b1d426b639ee49c305a80695 ]

cavium_ptp_get() acquires a reference to the PTP PCI device through pci_get_device(). If any initialization step fails after cavium_ptp_get(), the PTP PCI device reference is leaked. Add a common error path to release the PTP reference before returning from probe failures.

---

LLM Generated explanations, may be completely bogus:

Connection lost, reconnecting to https://agentn.us.api5.cursor.sh
(attempt 1)...
Retry attempt 1...
# Stable Backport Analysis: net: thunderx: fix PTP device ref leak in nicvf_probe()

**Local tree:** stable/linux-6.18.y at v6.18.44 (Makefile: 6.18.44)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Subject line
**Record:** [net: thunderx] [fix] — PTP PCI device reference leak in nicvf_probe() error paths.

### Step 1.2: Tags
**Record:**
- **Link:** https://patch.msgid.link/20260525082611.61817-1- [email protected]
- **Signed-off-by:** Haoxiang Li <[email protected]> (author)
- **Signed-off-by:** Jakub Kicinski <[email protected]> (net maintainer merge)
- No Fixes:, Reported-by:, Tested-by:, Reviewed-by:, `Cc:
[email protected]`, or syzbot links

### Step 1.3: Body analysis
**Record:**
- **Bug:** cavium_ptp_get() takes a PCI device reference via pci_get_device(). Any probe failure after a successful cavium_ptp_get() returns without calling cavium_ptp_put().
- **Symptom:** PCI device reference leak on probe failure (not a crash on the happy path).
- **Root cause:** Missing shared error-path cleanup; success path stores the ref in nic->ptp_clock and nicvf_remove() calls cavium_ptp_put(), but error paths bypass that.
- **Version info:** None in the message.

### Step 1.4: Hidden bug fix?
**Record:** No — explicitly labeled a reference leak fix.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Inventory
**Record:**
- **File:** drivers/net/ethernet/cavium/thunder/nicvf_main.c (+4 / −2 lines)
- **Function:** nicvf_probe()
- **Scope:** Single-file, surgical probe error-path fix

### Step 2.2: Code flow change
**Record:**
- **Hunk 1 (pci_enable_device failure):** Before: return dev_err_probe(...) leaked the PTP ref. After: goto err_put_ptp.
- **Hunk 2 (shared error tail):** Before: err_disable_device returned without releasing PTP. After: new err_put_ptp: calls cavium_ptp_put(ptp_clock) before return err. All existing goto err_* chains that reach err_disable_device now release the PTP reference.

### Step 2.3: Bug mechanism
**Record:**
- **Category:** Resource / reference-count leak on probe error path
- **Mechanism:** cavium_ptp_get() (lines 59–76 of cavium_ptp.c) calls pci_get_device() and, on success, returns ptp without pci_dev_put(). The caller must call cavium_ptp_put(), which does pci_dev_put(ptp->pdev). Error paths after a successful get never did that; only nicvf_remove() did on the success path.

### Step 2.4: Fix quality
**Record:**
- Fix is minimal and mirrors the remove path.
- cavium_ptp_put(NULL) is safe (if (!ptp) return; in cavium_ptp.c:81–82), so the -ENODEV/virtualized path (ptp_clock = NULL) is handled.
- Low regression risk; no API or locking changes.

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame
**Record:**
- cavium_ptp_get() in probe: 4a8755096466d (Sunil Goutham, 2018-01-15) — net: thunderx: add timestamping support
- pci_enable_device early return without cleanup: same era; later changed to dev_err_probe in 52583c8d8b12f2 (2021) without adding cavium_ptp_put()
- Bug present since PTP support was added (~v4.16 era); present in this 6.18.y tree

### Step 3.2: Fixes: tag
**Record:** N/A — no Fixes: tag. Introducing commit is 4a8755096466d.

### Step 3.3: Related file history
**Record:**
- 42330a32933fb — net: thunderx: Fix missing destroy_workqueue of nicvf_rx_mode_wq (probe error-path fix in the same function; already in 6.18.y)
- c1055b76ad00a — mutex init ordering fix in same probe
- a7d40cbb24900 — imply CAVIUM_PTP build fix
- Standalone one-commit fix; not part of a series

### Step 3.4: Author context
**Record:** Haoxiang Li has similar probe leak fixes in this tree (715cce38424fb liquidio BAR leak, dc8347f263b21 ipa SMEM leak). Not the thunderx maintainer, but pattern matches accepted stable leak fixes.

### Step 3.5: Dependencies
**Record:** None. Uses existing cavium_ptp_put(); no structural prerequisites. Fix not yet merged (err_put_ptp absent in this tree).

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original discussion
**Record:** b4 dig -c HEAD did not match this patch (different commit). Lore/patch.msgid.link blocked by Anubis bot protection. **UNVERIFIED:** full review thread and any Cc: stable nominations.

### Step 4.2: Reviewers
**Record:** **UNVERIFIED** (b4 dig -w not usable without commit hash).

### Step 4.3: Bug report
**Record:** No external bug report or syzbot link; found by code inspection.

### Step 4.4: Related patches
**Record:** Standalone; no series dependency.

### Step 4.5: Stable list
**Record:** **UNVERIFIED** — lore stable search blocked.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key functions
**Record:** nicvf_probe(), cavium_ptp_get(), cavium_ptp_put()

### Step 5.2: Callers
**Record:** nicvf_probe() is the PCI driver probe (module_pci_driver path) — runs at device enumeration / module load for THUNDER_NIC_VF.

### Step 5.3: Callees
**Record:** cavium_ptp_get() → pci_get_device(); cavium_ptp_put() → pci_dev_put().

### Step 5.4: Reachability
**Record:** Triggered when CONFIG_THUNDER_NIC_VF + CONFIG_CAVIUM_PTP are enabled on Cavium ThunderX/Marvell 64-bit PCI systems and probe fails after PTP device is found. Not userspace-syscall reachable; driver probe error path only.

### Step 5.5: Similar patterns
**Record:** Same driver already had probe error-path gaps fixed (42330a32933fb workqueue). 07a2e1cf39818 fixed NULL deref in cavium_ptp_put().

---

## PHASE 6: CROSS-REFERENCE WITH LOCAL TREE (6.18.y)

### Step 6.1: Buggy code present?
**Record:** **Yes.** Current tree at lines 2097–2108 and 2258–2262 shows cavium_ptp_get() followed by error returns/goto chains without cavium_ptp_put(). err_put_ptp not present.

### Step 6.2: Backport complications
**Record:** Clean apply expected — context matches the provided diff.

### Step 6.3: Related fixes already present? **Record:** Other nicvf_probe() error-path fixes exist (42330a32933fb); this PTP ref leak fix is **not** present.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

### Step 7.1: Subsystem
**Record:** drivers/net/ethernet/cavium/thunder/ — ThunderX NIC VF driver. **Criticality: PERIPHERAL** (platform-specific datacenter/embedded hardware).

### Step 7.2: Activity
**Record:** Moderate recent activity (workqueue fix, XDP features, mutex ordering).

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: Who is affected
**Record:** Users of Cavium ThunderX NIC VF with PTP (THUNDER_NIC_VF + CAVIUM_PTP). Not universal.

### Step 8.2: Trigger conditions
**Record:** Any nicvf_probe() failure after successful cavium_ptp_get() — e.g. pci_enable_device, pci_request_regions, DMA setup, alloc_etherdev_mqs, register setup, register_netdev failures. Uncommon in steady state; more likely during bring-up, hardware issues, or driver reload/debug. Not unprivileged-triggerable.

### Step 8.3: Failure mode severity
**Record:** PCI device reference leak per failed probe. Can prevent proper PTP device teardown, accumulate refs on repeated probe attempts, and interfere with module unload/reprobe. **Severity: MEDIUM** (resource leak, not crash/corruption/security).

### Step 8.4: Risk-benefit
**Record:**
- **Benefit:** Correct probe error cleanup; aligns with prior thunderx probe fixes in stable
- **Risk:** Very low (4 lines, uses existing helper, NULL-safe)
- **Ratio:** Moderate benefit for affected hardware, very low risk

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence

**FOR:**
- Real, verifiable PCI ref leak on all post-cavium_ptp_get() error paths
- Bug since 2018; present in 6.18.y
- Small, obviously correct fix
- Precedent: 42330a32933fb fixed a similar nicvf_probe() error-path bug in this stable tree
- Resource leaks are standard stable material per project norms
- Merged by net maintainer (Jakub Kicinski)

**AGAINST:**
- Platform-specific (ThunderX only)
- Only hits probe failure paths (rare in production)
- MEDIUM severity — no crash, corruption, or security impact
- No fuzzer/user reports

**UNRESOLVED:**
- Mailing list review details and stable nominations (lore blocked)

### Step 9.2: Stable rules checklist
1. Obviously correct and tested? **PASS** — logic is clear; no runtime test cited
2. Fixes a real bug? **PASS** — confirmed ref leak in code
3. Important issue? **PASS (borderline/MEDIUM)** — resource leak, not crash/corruption
4. Small and contained? **PASS** — 4 net lines, one file
5. No new features/APIs? **PASS**
6. Can apply to local tree? **PASS** — buggy code exists; clean apply expected

### Step 9.3: Exception categories
**Record:** None (not a quirk/DT/build/doc fix; standard probe error- path leak fix).

### Step 9.4: Decision rationale

For **linux-6.18.y**, this is a valid stable backport: the leak has been present since PTP support was added, the fix is minimal and safe, and the same driver's probe function already received a comparable error- path fix in this tree. Impact is limited to ThunderX + PTP configurations and probe-failure scenarios, but the fix cost is negligible and prevents a real reference leak that can affect driver reload and device lifecycle management on affected systems.

---

## Verification

- [Phase 1] Parsed subject, tags, body from provided commit message
- [Phase 2] Read current nicvf_probe() at lines 2090–2263; confirmed missing cavium_ptp_put() on error paths
- [Phase 2] Read cavium_ptp_get()/cavium_ptp_put() in cavium_ptp.c:59–85; confirmed refcount contract
- [Phase 3] git describe HEAD → v6.18.44; branch stable/linux-6.18.y
- [Phase 3] git blame -L 2095,2110 → PTP get added in 4a8755096466d (2018)
- [Phase 3] git show 4a8755096466d1 → original probe lacked cavium_ptp_put() on pci_enable_device failure
- [Phase 3] git log -S "err_put_ptp" → empty (fix not merged)
- [Phase 3] 42330a32933fb in tree — prior thunderx probe error-path fix
- [Phase 4] WebFetch lore/patch.msgid.link → blocked by Anubis (**UNVERIFIED** review thread)
- [Phase 4] b4 dig -c HEAD → no match for this patch
- [Phase 5] grep cavium_ptp_get → only nicvf_main.c in thunder drivers
- [Phase 6] Confirmed buggy code at lines 2106–2108 (return without put) and 2260–2262 (no err_put_ptp)
- [Phase 6] grep err_put_ptp → not found
- [Phase 7] Read drivers/net/ethernet/cavium/Kconfig — THUNDER_NIC_VF implies CAVIUM_PTP
- [Phase 8] Assessed severity MEDIUM (probe-only PCI ref leak on niche hardware)

**YES**The background git search finished. It didn’t find the PTP ref- leak fix (err_put_ptp isn’t in this tree), but it did turn up related nicvf_probe() work already on 6.18.y — the workqueue destroy fix (42330a32933fb), mutex init ordering (c1055b76ad00a), and the imply CAVIUM_PTP build fix (a7d40cbb24900).

That matches the earlier analysis: the PTP reference leak is still present in 6.18.44 and this patch should be backported.

**YES**

 drivers/net/ethernet/cavium/thunder/nicvf_main.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
drivers/net/ethernet/cavium/thunder/nicvf_main.c +6 -2
index 1be2dc40a1a63..e4dfd5cc15802 100644
@@ -2104,8 +2104,10 @@ static int nicvf_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
 	}
 
 	err = pci_enable_device(pdev);
-	if (err)
-		return dev_err_probe(dev, err, "Failed to enable PCI device\n");
+	if (err) {
+		err = dev_err_probe(dev, err, "Failed to enable PCI device\n");
+		goto err_put_ptp;
+	}
 
 	err = pci_request_regions(pdev, DRV_NAME);
 	if (err) {
@@ -2259,6 +2261,8 @@ static int nicvf_probe(struct pci_dev *pdev, const struct pci_device_id *ent)
 	pci_release_regions(pdev);
 err_disable_device:
 	pci_disable_device(pdev);
+err_put_ptp:
+	cavium_ptp_put(ptp_clock);
 	return err;
 }
 
Signature · 1 line
2.53.0
author maintainer
#232 lore raw

PATCH 1/1 libbpf: Add __NR_bpf definition for LoongArch

In reply to Sasha Levin

From: Tiezhu Yang <[email protected]>

[ Upstream commit a4a5d4ee061240a1d39053db0a87f841d43277c0 ]

LoongArch uses the generic syscall table, where __NR_bpf is defined as 280 in include/uapi/asm-generic/unistd.h.

To align with other architectures, add the __NR_bpf definition for LoongArch to avoid a potential compilation failure: "error __NR_bpf not defined. libbpf does not support your arch."

This is a follow up patch of:

commit b0c47807d31d ("bpf: Add sparc support to tools and samples.") commit bad1926dd2f6 ("bpf, s390: fix build for libbpf and selftest suite") commit ca31ca8247e2 ("tools/bpf: fix perf build error with uClibc (seen on ARC)") commit e32cb12ff52a ("bpf, mips: Fix build errors about __NR_bpf undeclared")

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: libbpf: Add __NR_bpf definition for LoongArch

**Local tree:** Linux **6.18.44** (git describe HEAD → v6.18.44, make kernelversion → 6.18.44)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Subject line
**Record:** [libbpf] [add] [__NR_bpf definition for LoongArch]

### Step 1.2: Tags
**Record:**
- **Signed-off-by:** Tiezhu Yang <[email protected]> (author)
- **Signed-off-by:** Andrii Nakryiko <[email protected]> (libbpf maintainer)
- **Link:** https://lore.kernel.org/bpf/20260526063936.16769-1-
[email protected]
- No Fixes:, Reported-by:, Tested-by:, Reviewed-by:, Acked-by:, or Cc:
stable tags
- Notable: maintainer Signed-off-by is a quality signal; no syzbot/user bug report

### Step 1.3: Body analysis
**Record:**
- **Bug:** When building libbpf/bpf tools on LoongArch with overridden unistd.h (perf build path), __NR_bpf is undefined and compilation fails with #error __NR_bpf not defined. libbpf does not support your arch.
- **Symptom:** Build failure (compile-time #error), not a runtime kernel crash
- **Root cause:** LoongArch uses the generic syscall table (__NR_bpf = 280 in asm-generic/unistd.h), but the explicit arch fallback list in tools/lib/bpf/bpf.c and tools/build/feature/test-bpf.c was never updated for __loongarch__
- **Version info:** None in message; follow-up to arch-specific __NR_bpf additions dating from 2017–2021

### Step 1.4: Hidden bug fix?
**Record:** Yes — described as alignment/cleanup, but it is a **build fix** preventing compilation failure on LoongArch, same class as prior mips/ARC/s390/sparc fixes by the same pattern.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Inventory
**Record:**
- tools/lib/bpf/bpf.c: +2 lines
- tools/build/feature/test-bpf.c: +2 lines
- **Total:** 4 insertions, 0 deletions
- **Functions affected:** None directly; modifies preprocessor fallback block before sys_bpf() / main()
- **Scope:** Single-purpose, two-file surgical fix

### Step 2.2: Code flow change
**Record:**
- **Hunk 1 (bpf.c):** Before → #elif mips then #else #error. After → adds #elif defined(__loongarch__) #define __NR_bpf 280 before the error branch. Affects the #ifndef __NR_bpf fallback used when perf overrides unistd.h.
- **Hunk 2 (test-bpf.c):** Same preprocessor addition for bpf feature- detection compile test.

### Step 2.3: Bug mechanism
**Record:** **Build fix / missing arch definition (category h-adjacent).** When __NR_bpf is not provided by headers (overridden unistd.h path documented in bpf.c), LoongArch hits the #else #error branch. Fix supplies the correct syscall number (280).

### Step 2.4: Fix quality
**Record:** Obviously correct — value 280 matches include/uapi/asm- generic/unistd.h and tools/arch/loongarch/include/uapi/asm/unistd.h (which includes asm-generic/unistd.h). Minimal, mirrors existing arch entries (aarch64, arc also use 280). **Regression risk:** very low; only affects preprocessor path when __NR_bpf is absent.

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame
**Record:** __NR_bpf fallback block in bpf.c introduced in e3ed2fef22b6 (2015). Arch entries added incrementally: sparc (b0c47807, 2017), s390 (bad1926dd, 2017), arc (ca31ca82, 2019), mips (e32cb12ff, 2021, same author). LoongArch omission is a long-standing gap, not a recently introduced regression.

### Step 3.2: Fixes: tag
**Record:** N/A — no Fixes: tag. Referenced prerequisite commits all exist in this tree (b0c47807, bad1926dd, ca31ca82, e32cb12ff confirmed via git merge-base --is-ancestor).

### Step 3.3: File history
**Record:** Related LoongArch libbpf work already in tree:
00883922ab404 (bpf_tracing.h), 29c66ad1c3ad1 (PT_REGS_CAST for LoongArch). seccomp_bpf.c already defines __NR_seccomp for __loongarch__ (line 147). Standalone patch; not part of a multi-patch series.

### Step 3.4: Author context
**Record:** Tiezhu Yang (Loongson) — prior e32cb12ff52a2 mips __NR_bpf fix in same files. Andrii Nakryiko (libbpf maintainer) Signed-off-by.

### Step 3.5: Dependencies
**Record:** No hard dependencies beyond the existing __NR_bpf fallback mechanism (present since 2015+). Applies standalone. Commit itself is **not** in current branch (git log --grep returned empty).

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original discussion
**Record:** b4 am [email protected] found thread at
https://patch.msgid.link/[email protected].
Mbox contains only the patch (1 message, no replies). No stable nominations or NAKs found. b4 dig -c HEAD failed (commit not in tree); used message-id lookup instead.

### Step 4.2: Reviewers
**Record:** Andrii Nakryiko Signed-off-by on patch. No separate Reviewed-by in mbox.

### Step 4.3: Bug report
**Record:** N/A — no external bug report or syzbot link. Author documents expected compile error text.

### Step 4.4: Related patches
**Record:** Part of ongoing arch-by-arch __NR_bpf fallback additions. Same author fixed mips identically in 2021. LoongArch bpf_tracing support already merged separately.

### Step 4.5: Stable list history
**Record:** Not searched on lore stable list (WebFetch blocked by bot protection). No stable discussion found in mbox.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key functions
**Record:** Preprocessor block only. Downstream: sys_bpf() in bpf.c calls syscall(__NR_bpf, ...). test-bpf.c main() calls syscall(__NR_bpf, BPF_PROG_LOAD, ...).

### Step 5.2: Callers
**Record:** sys_bpf() is the central libbpf syscall wrapper — used throughout libbpf for all BPF operations. Only reached at runtime if compilation succeeds; this patch affects **compile-time** availability of __NR_bpf.

### Step 5.3: Callees
**Record:** syscall(__NR_bpf, ...) — requires correct arch syscall number.

### Step 5.4: Reachability
**Record:** Triggered when building bpf tools (libbpf, perf, bpftool, bpf selftests feature detection) on LoongArch hosts where __NR_bpf is not defined by included headers. Userspace build path, not kernel runtime.

### Step 5.5: Similar patterns
**Record:** seccomp_bpf.c already has __loongarch__ syscall fallbacks (__NR_seccomp 277). bpf.c and test-bpf.c are inconsistent — LoongArch was missed. Same pattern fixed for mips, arc, s390, sparc.

---

## PHASE 6: CROSS-REFERENCING AGAINST LOCAL TREE (6.18.44)

### Step 6.1: Buggy code exists?
**Record:** **YES.** Current tools/lib/bpf/bpf.c lines 43–64 and tools/build/feature/test-bpf.c lines 6–25 lack __loongarch__ case and fall through to #error. LoongArch arch support present since fa96b57c14906 (LoongArch build infrastructure). Bug has existed since LoongArch tooling support without this define.

### Step 6.2: Backport complications
**Record:** **Clean apply expected.** Two identical 2-line hunks in files that match the patch context. No conflicting recent churn in this specific block.

### Step 6.3: Related fixes already present? **Record:** No equivalent fix found. git log --grep="Add __NR_bpf definition for LoongArch" returns empty on this branch.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

### Step 7.1: Subsystem
**Record:** **tools/lib/bpf** (userspace libbpf shipped with kernel sources). **Criticality:** IMPORTANT for bpf tooling; PERIPHERAL for general kernel runtime (does not affect running kernel on non-LoongArch or pre-built distros).

### Step 7.2: Activity
**Record:** LoongArch and libbpf actively maintained in 6.18.y (recent LoongArch BPF/kprobes fixes; ongoing libbpf API work).

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: Who is affected
**Record:** LoongArch users building kernel bpf tools from source (libbpf, perf, bpftool, bpf feature tests). Not universal; platform- specific build issue.

### Step 8.2: Trigger conditions
**Record:** Compile libbpf/bpf tools on LoongArch when __NR_bpf is not provided by headers (documented perf override path). Common for developers/maintainers building from kernel tree on LoongArch hardware. Unprivileged users can trigger only insofar as they can invoke a build.

### Step 8.3: Failure mode severity
**Record:** **Compile-time failure** (#error / undeclared __NR_bpf). **Severity: MEDIUM** for affected users (cannot build tools); **LOW** for general kernel stability (no runtime crash, corruption, or security issue).

### Step 8.4: Risk-benefit
**Record:**
- **Benefit:** Enables bpf tool builds on LoongArch; closes obvious gap vs. other arches and vs. seccomp_bpf.c on same platform
- **Risk:** Very low — 4 lines, correct constant, no logic change
- **Ratio:** Favorable; classic stable build-fix backport

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence summary

**FOR backport:**
- Real build failure on LoongArch (documented error path)
- Build fix — explicit stable exception category
- Tiny (4 lines), obviously correct (__NR_bpf = 280 verified in tree headers)
- Same pattern as mips/ARC/s390 fixes already in 6.18.44
- libbpf maintainer Signed-off-by
- Buggy code confirmed present in 6.18.44
- Prerequisites all in tree; standalone apply

**AGAINST backport:**
- No runtime kernel bug (tools-only build issue)
- Affects niche platform (LoongArch)
- No user bug reports or syzbot evidence
- No explicit stable nomination in review thread (thread had no replies)

**Unresolved:** Whether distro packagers always hit the overridden-unistd.h path; author says "potential" failure, but mechanism is well-established from bpf.c comment and prior arch fixes.

### Step 9.2: Stable rules checklist
1. Obviously correct and tested? **PASS** — syscall number matches asm- generic/unistd.h; maintainer SOB; mirrors proven prior arch fixes
2. Fixes real bug affecting users? **PASS** — compile failure for LoongArch bpf tool builds
3. Important issue? **PASS (moderate)** — build fix for platform developers; not crash/security, but stable explicitly accepts build fixes
4. Small and contained? **PASS** — 4 lines, 2 files
5. No new features/APIs? **PASS** — preprocessor define only
6. Can apply to local tree? **PASS** — buggy code present, clean apply expected

### Step 9.3: Exception category
**Record:** **BUILD FIX** — prevents compilation failure when building libbpf/bpf tools on LoongArch.

### Step 9.4: Decision rationale
For Linux **6.18.44**, LoongArch is a supported architecture and bpf tooling is actively used, but tools/lib/bpf/bpf.c and tools/build/feature/test-bpf.c still lack the __loongarch__ entry in the __NR_bpf fallback table. This is the same class of fix as the mips (e32cb12ff52a2) and ARC (ca31ca8247e2) commits already in this tree. The fix is trivial, correct, and low-risk. While severity is build-time rather than runtime, stable trees routinely accept such arch-specific build fixes — especially when they unblock tool compilation on a supported platform.

---

## Verification

- **[Phase 1]** git describe HEAD → v6.18.44; parsed subject, tags, body from user-provided commit and mbox
- **[Phase 2]** Read tools/lib/bpf/bpf.c lines 39–65; read tools/build/feature/test-bpf.c full file; confirmed 4-line diff, preprocessor-only change
- **[Phase 3]** git blame -L 43,65 tools/lib/bpf/bpf.c — fallback block history traced to 2015; mips fix e32cb12ff52a2 by same author
- **[Phase 3]** git merge-base --is-ancestor b0c47807d31d HEAD → prerequisite in tree
- **[Phase 3]** git log --grep="Add __NR_bpf definition for LoongArch" → not in branch
- **[Phase 3]** git log --author="Tiezhu Yang" -- tools/lib/bpf/ → mips fix + bpf_tracing LoongArch work present
- **[Phase 4]** b4 am [email protected] → patch retrieved; 1 message, no replies
- **[Phase 4]** WebFetch lore.kernel.org → blocked (bot protection); used b4 mbox instead
- **[Phase 5]** grep __loongarch__ tools/ — found in seccomp_bpf.c, bpf_tracing.h, etc., but NOT in bpf.c __NR_bpf block
- **[Phase 5]** Read seccomp_bpf.c lines 134–164 — __NR_seccomp for __loongarch__ already defined
- **[Phase 6]** grep __NR_bpf tools/lib/bpf/bpf.c — no __loongarch__ branch in 6.18.44
- **[Phase 6]** include/uapi/asm-generic/unistd.h line 677 → #define __NR_bpf 280
- **[Phase 6]** tools/arch/loongarch/include/uapi/asm/unistd.h → includes asm-generic/unistd.h
- **[Phase 6]** arch/loongarch/ exists; git log --reverse -- arch/loongarch/ | head -1 → fa96b57c14906
- **[Phase 7]** git log -20 -- arch/loongarch/ — active LoongArch development including BPF fixes
- **[Phase 8]** Assessed as build-time failure, platform-specific, low runtime risk

**YES**The background search finished. It confirmed that **"libbpf: Add __NR_bpf definition for LoongArch" is not in the current 6.18.44 branch** — related LoongArch libbpf work is already there (bpf_tracing.h, PT_REGS_CAST), but the __NR_bpf fallback in bpf.c and test-bpf.c is still missing.

That matches the earlier analysis: this is a small, low-risk build fix for LoongArch bpf tool compilation and should be backported to this tree.

**YES**

 tools/build/feature/test-bpf.c | 2 ++
 tools/lib/bpf/bpf.c            | 2 ++
 2 files changed, 4 insertions(+)
tools/build/feature/test-bpf.c +2 -0
index e7a405f83af6e..89d59674f39b9 100644
@@ -20,6 +20,8 @@
 #  define __NR_bpf 6319
 # elif defined(__mips__) && defined(_ABI64)
 #  define __NR_bpf 5315
+# elif defined(__loongarch__)
+#  define __NR_bpf 280
 # else
 #  error __NR_bpf not defined. libbpf does not support your arch.
 # endif
tools/lib/bpf/bpf.c +2 -0
index 339b197972374..1e8f01bfc1bfd 100644
@@ -59,6 +59,8 @@
 #  define __NR_bpf 6319
 # elif defined(__mips__) && defined(_ABI64)
 #  define __NR_bpf 5315
+# elif defined(__loongarch__)
+#  define __NR_bpf 280
 # else
 #  error __NR_bpf not defined. libbpf does not support your arch.
 # endif
Signature · 1 line
2.53.0
author maintainer
#233 lore raw

PATCH 1/1 clk: samsung: exynos850: mark APM I3C clocks as critical

In reply to Sasha Levin

From: Alexey Klimov <[email protected]>

[ Upstream commit 44984aaf1aa727ff944dd4b72fcf069d08b0056d ]

The Exynos850 APM co-processor relies on the I3C bus to communicate with the PMIC. Currently, there is no dedicated PMIC consumer driver managing these clocks, so the clock subsystem automatically gates them during the initialisation. Once gated, any subsequent ACPM communication with APM results in timeouts.

As a temporary workaround (and let's hope it doesn't become permanent), mark both gout_i3c_pclk and gout_i3c_sclk as CLK_IS_CRITICAL ones to prevent the clock subsystem from disabling them. This makes the ACPM communication functional. This workaround should be reverted once a proper ACPM PMIC driver is implemented to manage these clocks.

---

LLM Generated explanations, may be completely bogus:

## Phase 1: Commit Message Forensics

### Step 1.1: Subject Line
**Record:** [clk: samsung: exynos850] [mark] — Mark APM I3C clocks (gout_i3c_pclk, gout_i3c_sclk) as CLK_IS_CRITICAL to prevent the clock core from gating them.

### Step 1.2: Commit Message Tags
**Record:**
- **Fixes:** — not present (expected for manual review)
- **Reported-by:** — none
- **Tested-by:** — none
- **Reviewed-by:** Sam Protsenko \<[email protected]\>, Tudor Ambarus \<[email protected]\>
- **Acked-by:** — none
- **Cc:** Sam Protsenko, Tudor Ambarus (not [email protected])
- **Link:** https://patch.msgid.link/20260430-exynos850-i3c-
[email protected]
- **Signed-off-by:** Alexey Klimov, Krzysztof Kozlowski (ignore pipeline-added SOBs)

Notable: two Reviewed-by tags from Linaro Exynos850 platform developers; no syzbot or user bug reports.

### Step 1.3: Commit Body Analysis
**Record:**
- **Bug:** With no PMIC consumer driver holding references, the clock framework gates gout_i3c_pclk and gout_i3c_sclk during init.
- **Symptom:** After gating, all ACPM communication with the Exynos850 APM co-processor times out.
- **Root cause:** APM uses I3C to talk to the PMIC; those bus clocks must stay enabled but nothing claims them.
- **Fix approach:** Temporary CLK_IS_CRITICAL workaround until a proper ACPM PMIC driver manages the clocks.
- **Version info:** none in the message.

### Step 1.4: Hidden Bug Fix Detection
**Record:** Yes — described as a workaround, but it fixes real broken platform behavior (ACPM timeouts). Same pattern as other CLK_IS_CRITICAL entries in this file for clocks that must stay on without a consumer driver.

---

## Phase 2: Diff Analysis

### Step 2.1: Change Inventory
**Record:**
- **File:** drivers/clk/samsung/clk-exynos850.c (+3 / −2, net +1 line)
- **Functions:** apm_gate_clks[] static init table (inside exynos850_cmu_apm init path)
- **Scope:** Single-file, surgical hardware workaround

### Step 2.2: Code Flow Change
**Record:**
- **Hunk 1 (I3C PCLK gate):** GATE(..., 0, 0) → GATE(..., CLK_IS_CRITICAL, 0) for gout_i3c_pclk
- **Hunk 2 (I3C SCLK gate):** GATE(..., 0, 0) → GATE(..., CLK_IS_CRITICAL, 0) for gout_i3c_sclk
- **Path affected:** Boot-time APM CMU clock registration; prevents automatic disable of I3C clocks after init.

### Step 2.3: Bug Mechanism
**Record:**
- **Category:** Hardware workaround / clock-gating correctness
- **Mechanism:** Ungated clocks with no consumer get disabled by clk_disable_unused(); APM I3C to PMIC then stops working and ACPM mailbox traffic times out.

### Step 2.4: Fix Quality
**Record:**
- Obviously correct: mirrors gout_pmu_alive_pclk on line 698 in the same table.
- Minimal, no API changes.
- **Regression risk:** Low — keeps two clocks enabled that must remain on; minor power cost on Exynos850 only.

---

## Phase 3: Git History Investigation

### Step 3.1: Blame
**Record:** In this checkout, I3C gate lines are at 687–690 with flags 0, 0. Blame points to a112b91dd6349 (history is flattened in this stable checkout). Verified directly: buggy code is present at HEAD.

### Step 3.2: Fixes: Tag
**Record:** N/A — no Fixes: tag.

### Step 3.3: Related File History
**Record:**
- Commit 44984aaf1aa72 on master is this fix.
- Related on master: e57c36bc1a3e4 (APM-to-AP mailbox clock).
- Fix is **not** an ancestor of HEAD (fix NOT in HEAD).
- Standalone 1/1 patch (b4 dig -a shows only v1).

### Step 3.4: Author Context
**Record:** Alexey Klimov (Linaro). Reviewed by Sam Protsenko (original Exynos850 clk author per file copyright). Krzysztof Kozlowski (Samsung clk maintainer) committed it.

### Step 3.5: Dependencies
**Record:** No prerequisites. Uses existing CLK_IS_CRITICAL and GATE() macro. Applies standalone.

---

## Phase 4: Mailing List and External Research

### Step 4.1: Original Discussion
**Record:**
- **URL:** https://patch.msgid.link/20260430-exynos850-i3c-
[email protected]
- **Revisions:** v1 only
- **Feedback:** Sam Protsenko Reviewed-by (May 8); Tudor Ambarus Reviewed-by (May 6); Krzysztof Kozlowski "Applied, thanks!" (May 14)
- **Stable nomination:** none in thread
- **NAKs:** none

### Step 4.2: Reviewers
**Record:** CC'd: Krzysztof Kozlowski, Sylwester Nawrocki, Chanwoo Choi, Alim Akhtar, Michael Turquette, Stephen Boyd, [email protected], [email protected]. Appropriate maintainers were included.

### Step 4.3: Bug Report
**Record:** No external bug report or syzbot link. Issue comes from platform bring-up experience (Linaro/Samsung Exynos850 work).

### Step 4.4: Related Patches
**Record:** Standalone; not part of a multi-patch series.

### Step 4.5: Stable List History
**Record:** Lore fetch blocked by bot protection for web search; mbox thread has no stable discussion. UNVERIFIED for lore.kernel.org/stable search.

---

## Phase 5: Code Semantic Analysis

### Step 5.1: Key Functions
**Record:** apm_gate_clks[] in drivers/clk/samsung/clk-exynos850.c; registered via exynos850_cmu_apm CLK_OF_DECLARE path.

### Step 5.2: Callers
**Record:** Samsung CMU init during early DT clock probe for samsung,exynos850-cmu-apm (present in arch/arm64/boot/dts/exynos/exynos850.dtsi). Runs at boot on Exynos850 boards.

### Step 5.3: Callees
**Record:** GATE() macro populates samsung_gate_clock with .flags = CLK_IS_CRITICAL, preventing disable when unused.

### Step 5.4: Reachability
**Record:** Boot path on Exynos850 (exynos850-e850-96.dts, exynosautov920*.dts, etc.). ACPM (drivers/firmware/samsung/exynos- acpm.c) uses mailbox to APM; PMIC access depends on APM I3C staying up.

### Step 5.5: Similar Patterns
**Record:** Same file already uses CLK_IS_CRITICAL for gout_pmu_alive_pclk (line 698) and many other gates. GPIO gates use CLK_IGNORE_UNUSED with TODO comments for the same class of problem.

---

## Phase 6: Cross-Reference Against Local Tree

### Step 6.1: Buggy Code Present?
**Record:** **Yes.** Local tree is **v6.18.43** (git describe HEAD → v6.18.43-1-gc7f0dac02d232, Makefile 6.18.43). At HEAD lines 687–690:

```687:690:drivers/clk/samsung/clk-exynos850.c
        GATE(CLK_GOUT_I3C_PCLK, "gout_i3c_pclk", "dout_apm_bus",
             CLK_CON_GAT_GOUT_APM_I3C_APM_PMIC_I_PCLK, 21, 0, 0),
        GATE(CLK_GOUT_I3C_SCLK, "gout_i3c_sclk", "mout_apm_i3c",
             CLK_CON_GAT_GOUT_APM_I3C_APM_PMIC_I_SCLK, 21, 0, 0),
```

Also confirmed at v6.18 and v6.18.43 tags. Exynos850 DT and drivers are present in this tree.

### Step 6.2: Backport Complications
**Record:** Clean apply expected — 5-line change, no conflicts. File is 2338 lines with no recent churn in this stable branch.

### Step 6.3: Related Fixes Already Present?
**Record:** No — git merge-base --is-ancestor 44984aaf1aa72 HEAD → fix **NOT** in HEAD.

---

## Phase 7: Subsystem and Maintainer Context

### Step 7.1: Subsystem Criticality
**Record:** drivers/clk/samsung/ — **IMPORTANT** (platform-specific clock driver). Exynos850 is ARM64 SoC support (consumer boards + automotive exynosautov920).

### Step 7.2: Subsystem Activity
**Record:** Exynos850 clk driver is actively maintained; recent master commits add mailbox clocks and this I3C fix.

---

## Phase 8: Impact and Risk Assessment

### Step 8.1: Who Is Affected
**Record:** Exynos850 platform users only — WinLink E850-96, Exynos Auto V920, and other samsung,exynos850 boards using ACPM/APM PMIC communication.

### Step 8.2: Trigger Conditions
**Record:** Every boot on affected hardware after clock init completes and clk_disable_unused() runs. Deterministic, not a race. Unprivileged users cannot trigger directly, but all Exynos850 boots hit this path.

### Step 8.3: Failure Mode Severity
**Record:** ACPM communication timeouts → broken PMIC co-processor path. **Severity: HIGH** for affected platforms (essential firmware communication broken; power/PMIC management non-functional). Not a kernel oops, but platform is effectively broken for ACPM consumers.

### Step 8.4: Risk-Benefit
**Record:**
- **Benefit:** HIGH for Exynos850 users on 6.18.y
- **Risk:** VERY LOW — 2 flag changes + comment; established pattern
- **Ratio:** Strong benefit for affected hardware, negligible risk elsewhere

---

## Phase 9: Final Synthesis

### Step 9.1: Evidence Summary

**FOR backport:**
- Real, reproducible platform bug in this tree (6.18.43)
- Breaks ACPM/APM PMIC communication on every affected boot
- Tiny, obviously correct hardware workaround
- Reviewed by Exynos850 platform experts and committed by clk maintainer
- Fits hardware-quirk exception (clock must stay on)
- Clean backport, no dependencies
- Fix not yet in stable/linux-6.18.y

**AGAINST backport:**
- Platform-specific (Exynos850 only)
- Labeled "temporary workaround"
- No kernel crash/oops/security issue — functional timeout
- No explicit stable nomination in review thread

**Unresolved:** Stable mailing list search blocked by lore bot protection.

### Step 9.2: Stable Rules Checklist
1. Obviously correct and tested? **PASS** — matches existing CLK_IS_CRITICAL pattern; reviewed by platform developers
2. Fixes a real bug affecting users? **PASS** — ACPM timeouts on Exynos850
3. Important issue? **PASS** — breaks essential APM/PMIC communication on affected SoCs
4. Small and contained? **PASS** — 5 lines, one file
5. No new features or APIs? **PASS** — flag change only
6. Can apply to local tree? **PASS** — buggy code present, clean apply

### Step 9.3: Exception Category
**Record:** Hardware quirk/workaround — clocks that must remain enabled for PMIC I3C on APM, analogous to existing CLK_IS_CRITICAL entries in the same table.

### Step 9.4: Decision Rationale
Exynos850 support is fully present in this 6.18.43 stable tree, and the I3C clock gating bug is present without the fix. Without this patch, ACPM communication with the APM co-processor fails after boot-time clock initialization — a serious functional defect for every Exynos850 deployment on 6.18.y. The fix is minimal, follows an established pattern in the same file, and carries negligible regression risk.

---

## Verification

- [Phase 1] Parsed subject, tags, body; no Fixes:/Reported-by/syzbot; two Reviewed-by from Linaro
- [Phase 2] Diff: 5 lines in clk-exynos850.c, CLK_IS_CRITICAL on two I3C gates
- [Phase 3] git describe HEAD → v6.18.43; 44984aaf1aa72 on master; fix NOT in HEAD
- [Phase 3] git show 44984aaf1aa72 — full commit message and patch confirmed
- [Phase 3] git cat-file -e v6.18:drivers/clk/samsung/clk-exynos850.c — file exists (2338 lines)
- [Phase 3] git show v6.18.43:... — I3C gates have 0, 0 flags (buggy)
- [Phase 4] b4 dig -c 44984aaf1aa72 — lore URL found
- [Phase 4] b4 dig -c 44984aaf1aa72 -w — maintainers CC'd
- [Phase 4] b4 dig -c 44984aaf1aa72 -a — v1 only, standalone
- [Phase 4] /tmp/exynos850-i3c.mbox — Reviewed-by from Sam Protsenko and Tudor Ambarus; Krzysztof applied; no stable nomination
- [Phase 5] Grep: gout_i3c_pclk at lines 687–690 with flags 0, 0; gout_pmu_alive_pclk uses CLK_IS_CRITICAL at line 698
- [Phase 5] DT: exynos850.dtsi, exynos850-e850-96.dts, exynosautov920.dtsi present
- [Phase 5] ACPM driver present at drivers/firmware/samsung/exynos- acpm.c
- [Phase 6] HEAD detached from stable/linux-6.18.y at Linux 6.18.43
- [Phase 6] Buggy code verified at HEAD; fix absent from tree
- [Phase 8] Failure mode: ACPM timeouts, HIGH severity for Exynos850 platforms
- UNVERIFIED: lore.kernel.org/stable search (bot protection)

**YES**

 drivers/clk/samsung/clk-exynos850.c | 5 +++--
 1 file changed, 3 insertions(+), 2 deletions(-)
drivers/clk/samsung/clk-exynos850.c +3 -2
index 56f27697c76b1..413faf14eded9 100644
@@ -684,10 +684,11 @@ static const struct samsung_gate_clock apm_gate_clks[] __initconst = {
 	     CLK_CON_GAT_GOUT_APM_APBIF_RTC_PCLK, 21, 0, 0),
 	GATE(CLK_GOUT_TOP_RTC_PCLK, "gout_top_rtc_pclk", "dout_apm_bus",
 	     CLK_CON_GAT_GOUT_APM_APBIF_TOP_RTC_PCLK, 21, 0, 0),
+	/* TODO: Should be dealt with or enabled in PMIC ACPM driver */
 	GATE(CLK_GOUT_I3C_PCLK, "gout_i3c_pclk", "dout_apm_bus",
-	     CLK_CON_GAT_GOUT_APM_I3C_APM_PMIC_I_PCLK, 21, 0, 0),
+	     CLK_CON_GAT_GOUT_APM_I3C_APM_PMIC_I_PCLK, 21, CLK_IS_CRITICAL, 0),
 	GATE(CLK_GOUT_I3C_SCLK, "gout_i3c_sclk", "mout_apm_i3c",
-	     CLK_CON_GAT_GOUT_APM_I3C_APM_PMIC_I_SCLK, 21, 0, 0),
+	     CLK_CON_GAT_GOUT_APM_I3C_APM_PMIC_I_SCLK, 21, CLK_IS_CRITICAL, 0),
 	GATE(CLK_GOUT_SPEEDY_PCLK, "gout_speedy_pclk", "dout_apm_bus",
 	     CLK_CON_GAT_GOUT_APM_SPEEDY_APM_PCLK, 21, 0, 0),
 	/* TODO: Should be enabled in GPIO driver (or made CLK_IS_CRITICAL) */
Signature · 1 line
2.53.0
author maintainer
#234 lore raw

PATCH 1/1 drm/panel-edp: Add CSW PNB601LS1-2 and LGD LP116WHA-SPB1

In reply to Sasha Levin

From: Terry Hsiao <[email protected]>

[ Upstream commit e88b5cc6d6e5b1ba257f00e5c186ba137e6e8bc3 ]

The raw EDIDs for each panel:

CSW
- PNB601LS1-2
00 ff ff ff ff ff ff 00 0e 77 0a 11 00 00 00 00 30 23 01 04 a5 1a 0e 78 03 a1 35 9b 5e 58 91 25 1c 50 54 00 00 00 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 09 1e 56 dc 50 00 28 30 30 20 36 00 00 90 10 00 00 1a 06 14 56 dc 50 00 28 30 30 20 36 00 00 90 10 00 00 1a 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 02 00 0c 3d ff 0c 3c 7d 0e 0b 17 7d 00 00 00 00 e8

LGD
- LP116WHA-SPB1
00 ff ff ff ff ff ff 00 30 e4 fe 07 01 01 00 00 00 24 01 04 a5 1a 0e 78 03 72 e5 9c 5e 5b 94 27 19 50 54 00 00 00 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 01 d5 21 56 a0 50 00 b2 30 30 20 f8 0c 00 90 10 00 00 1a 8e 16 56 a0 50 00 b2 30 30 20 f8 0c 00 90 10 00 00 1a 00 00 00 fd 00 28 3c 39 39 09 01 0a 20 20 20 20 20 20 00 00 00 02 00 0f 3d ff 0f 3c 7d 0d 0a 15 7d 00 00 00 01 da

70 20 79 02 00 25 00 09 57 52 01 57 52 01 28 3c 80 81 00 15 74 1a 00 00 03 01 28 3c 00 00 4a 5a 4a 5a 3c 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 ef 90

---

LLM Generated explanations, may be completely bogus:

The background searches finished and match the earlier analysis:

- **Git history:** No commit for PNB601LS1-2 or LP116WHA-SPB1 in this tree. Related CSW entries (MNB601LS1-3, MNB601LS1-4) are present, so the missing panels are a gap, not a duplicate fix.
- **b4 dig:** Returned nothing — the commit isn’t in this checkout, so the lore thread couldn’t be resolved that way.

That doesn’t change the verdict: for **6.18.43**, this is a small, reviewed panel-ID addition that applies cleanly and is appropriate for stable.

**YES**

 drivers/gpu/drm/panel/panel-edp.c | 2 ++
 1 file changed, 2 insertions(+)
drivers/gpu/drm/panel/panel-edp.c +2 -0
index d1e68c464e308..be827729c4fb7 100644
@@ -2029,6 +2029,7 @@ static const struct edp_panel_entry edp_panels[] = {
 	EDP_PANEL_ENTRY('C', 'S', 'W', 0x1100, &delay_200_500_e80_d50, "MNB601LS1-1"),
 	EDP_PANEL_ENTRY('C', 'S', 'W', 0x1103, &delay_200_500_e80_d50, "MNB601LS1-3"),
 	EDP_PANEL_ENTRY('C', 'S', 'W', 0x1104, &delay_200_500_e50_d100, "MNB601LS1-4"),
+	EDP_PANEL_ENTRY('C', 'S', 'W', 0x110a, &delay_200_500_e50, "PNB601LS1-2"),
 	EDP_PANEL_ENTRY('C', 'S', 'W', 0x143f, &delay_200_500_e50, "MNE007QS3-6"),
 	EDP_PANEL_ENTRY('C', 'S', 'W', 0x1448, &delay_200_500_e50, "MNE007QS3-7"),
 	EDP_PANEL_ENTRY('C', 'S', 'W', 0x1457, &delay_80_500_e80_p2e200, "MNE007QS3-8"),
@@ -2070,6 +2071,7 @@ static const struct edp_panel_entry edp_panels[] = {
 	EDP_PANEL_ENTRY('L', 'G', 'D', 0x05af, &delay_200_500_e200_d200, "Unknown"),
 	EDP_PANEL_ENTRY('L', 'G', 'D', 0x05f1, &delay_200_500_e200_d200, "Unknown"),
 	EDP_PANEL_ENTRY('L', 'G', 'D', 0x0778, &delay_200_500_e200_d200, "134WT1"),
+	EDP_PANEL_ENTRY('L', 'G', 'D', 0x07fe, &delay_200_500_e200_d200, "LP116WHA-SPB1"),
 
 	EDP_PANEL_ENTRY('S', 'H', 'P', 0x1511, &delay_200_500_e50, "LQ140M1JW48"),
 	EDP_PANEL_ENTRY('S', 'H', 'P', 0x1523, &delay_80_500_e50, "LQ140M1JW46"),
Signature · 1 line
2.53.0
author maintainer
#235 lore raw

PATCH 1/1 PCI: Avoid SBR for Qualcomm WCN6855/WCN7850 WiFi, SDX62/SDX65 modems

In reply to Sasha Levin

From: Jose Ignacio Tornos Martinez <[email protected]>

[ Upstream commit 6a4f64c3a3ada43e71ef1e06da89beb36bdaeefa ]

Some Qualcomm PCIe devices (WCN6855/WCN7850 WiFi cards, SDX62/SDX65 modems) do not properly support Secondary Bus Reset (SBR).

Testing confirms this is device-specific, not deployment-specific:
MediaTek MT7925e successfully uses bus reset through the same passive M.2-to-PCIe adapters where Qualcomm devices fail, proving PERST# is properly wired through the adapters.

Prevent use of Secondary Bus Reset for these devices.

---

LLM Generated explanations, may be completely bogus:

Connection lost, reconnecting to https://agentn.us.api5.cursor.sh
(attempt 1)...
Retry attempt 1...
Connection lost, reconnecting to https://agentn.us.api5.cursor.sh
(attempt 2)...
Retry attempt 2...
# Stable Backport Analysis: PCI Qualcomm SBR Quirk

**Local tree:** v6.18.44 (6.18.44)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Subject Line
**Record:** [PCI] [avoid] Avoid Secondary Bus Reset (SBR) for Qualcomm WCN6855/WCN7850 WiFi and SDX62/SDX65 modems

### Step 1.2: Tags
**Record:**
- **Link:** https://lore.kernel.org/all/20260609163649.319755-4- [email protected]
- **Signed-off-by:** Jose Ignacio Tornos Martinez <[email protected]> (author)
- **Signed-off-by:** Bjorn Helgaas <[email protected]> (PCI maintainer)
- No Fixes:, Reported-by:, Cc: [email protected], Tested- by:, or Reviewed-by: tags
- Notable: maintainer sign-off from Bjorn Helgaas; part of v8 series [PATCH v8 0/3] per LWN

### Step 1.3: Body Analysis
**Record:**
- **Bug:** Qualcomm PCIe devices (WCN6855/WCN7850 WiFi, SDX62/SDX65 modems) do not properly support Secondary Bus Reset
- **Symptom:** Bus reset fails/hangs on these devices; LWN series context describes VFIO passthrough reset failures and potential system hang when SBR is attempted (same failure class as existing Atheros quirk in quirks.c)
- **Root cause:** Device-specific hardware limitation, not adapter/wiring issue (MT7925e works on same M.2-to-PCIe adapters)
- **Fix:** Mark devices with quirk_no_bus_reset to set PCI_DEV_FLAGS_NO_BUS_RESET

### Step 1.4: Hidden Bug Fix?
**Record:** Yes — described as "avoid/prevent" rather than "fix", but it is a hardware quirk preventing a known-broken reset path. Same pattern as Atheros/Cavium/TI/ASM1164 quirks already in quirks.c, where SBR causes link-down, inaccessible config space, and system hang.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Inventory
**Record:**
- **Files:** drivers/pci/quirks.c only (+3 lines)
- **Functions:** No function changes; adds 3 DECLARE_PCI_FIXUP_HEADER entries after Atheros quirks
- **Scope:** Single-file surgical hardware quirk addition

### Step 2.2: Code Flow Change
**Record:**
- **Before:** Qualcomm devices 0x17cb:0x1103, 0x17cb:0x1107, 0x17cb:0x0308 had no NO_BUS_RESET flag; pci_reset_bus_function() could probe/use SBR
- **After:** At PCI header fixup time, quirk_no_bus_reset() sets PCI_DEV_FLAGS_NO_BUS_RESET; pci_parent_bus_reset() and pci_dev_reset_slot_function() return -ENOTTY when flag is set (lines 4801, 4832 in pci.c)
- **Path affected:** PCI device reset enumeration and execution (pci_init_reset_methods(), __pci_reset_function_locked()), VFIO device reset, driver error recovery

### Step 2.3: Bug Mechanism
**Record:**
- **Category:** Hardware workaround / quirk
- **Mechanism:** Broken SBR on specific Qualcomm silicon; quirk prevents kernel from selecting a reset method that bricks the device or hangs the system. Analogous to Atheros quirk comment at lines 3767–3770:
"config space of the device is never accessible again and typically causes the system to hang or reset"

### Step 2.4: Fix Quality
**Record:**
- Obviously correct: identical pattern to ~10 existing quirk_no_bus_reset entries in the same file
- Minimal: 3 DECLARE_PCI_FIXUP_HEADER lines
- Low regression risk: only affects listed device IDs; other reset methods (FLR, PM, device-specific) remain available if supported

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame
**Record:**
- quirk_no_bus_reset() introduced in c3e59ee4e7668 (2015-01-15, Alex Williamson) — long-established infrastructure
- Insertion point (after Atheros quirks, before Cavium) matches current tree layout exactly

### Step 3.2: Fixes: Tag
**Record:** Not applicable — no Fixes: tag. Bug is inherent to hardware, not introduced by a specific kernel commit.

### Step 3.3: Related File History
**Record:**
- Recent similar quirks in this tree: ASM1164 (a175a76147382), Nvidia GB10 (b8bd9fe67041c)
- This commit is patch 3/3 of series "PCI: Add d3cold and device- specific reset for Qualcomm devices" (LWN v8 0/3). Patches 1–2 (d3cold reset method, Qualcomm device-specific reset) are **not** in this tree; patch 3 is standalone (only adds quirk entries, no code dependencies on patches 1–2)

### Step 3.4: Author Context
**Record:** Jose Ignacio Tornos Martinez — no prior PCI commits in this 6.18.44 tree; authored VFIO/PCI reset series merged to mainline v7.2 (June 2026). Bjorn Helgaas (PCI maintainer) signed off.

### Step 3.5: Dependencies
**Record:**
- **Standalone:** Yes — only uses existing quirk_no_bus_reset and PCI_VENDOR_ID_QCOM
- Patches 1–2 from the same series would improve VFIO reset capability but are **not prerequisites** for this quirk; LWN describes patch 3 as a "safety net" that independently prevents broken SBR

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original Discussion
**Record:**
- Direct lore fetch blocked (Anubis bot protection)
- LWN article found: [PCI: Add d3cold and device-specific reset for Qualcomm devices](https://lwn.net/Articles/1077236/) — covers full v8 0/3 series
- b4 dig -c <commit> failed: commit not present in local repository
- Mainline merge: 44105c5d0a13 (pci/virtualization branch, 2026-06-23)

### Step 4.2: Reviewers
**Record:** CC list from LWN: [email protected], [email protected] (VFIO), linux-pci@, linux-wireless@, ath11k@, ath12k@, mhi@ — appropriate subsystem coverage

### Step 4.3: Bug Report
**Record:** No formal bugzilla/syzbot report. Failure mode documented in series cover letter: VFIO passthrough reset failures; device-specific SBR breakage confirmed by comparative testing with MT7925e on same adapters.

### Step 4.4: Series Context
**Record:**
- Patch 1/3: D3cold general reset method (not in 6.18.44)
- Patch 2/3: Qualcomm device-specific reset via D3cold (not in 6.18.44)
- Patch 3/3: **This commit** — disable broken SBR (standalone, backportable independently)

### Step 4.5: Stable List History
**Record:** No stable-list discussion found (lore blocked). Not a negative signal per instructions.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key Functions
**Record:** quirk_no_bus_reset() (unchanged); reset path functions:
pci_reset_bus_function(), pci_parent_bus_reset(), pci_dev_reset_slot_function(), pci_slot_resettable()

### Step 5.2: Callers
**Record:**
- pci_init_reset_methods() probes reset methods during device setup
- __pci_reset_function_locked() / pci_reset_function() used by VFIO, error handlers, sysfs reset attribute
- pci_slot_resettable() used during slot-level reset decisions
- All check PCI_DEV_FLAGS_NO_BUS_RESET — verified in pci.c lines 4801, 4832, 5218, 5222, 5291, 5297

### Step 5.3: Callees
**Record:** quirk_no_bus_reset() only sets dev->dev_flags |= PCI_DEV_FLAGS_NO_BUS_RESET — no allocations, locks, or I/O

### Step 5.4: Reachability
**Record:**
- Triggered during PCI enumeration (HEADER fixup) and whenever reset is attempted on these devices
- Userspace-reachable via VFIO passthrough, driver reload, error recovery, sysfs reset
- WiFi cards (WCN6855/WCN7850) and cellular modems (SDX62/SDX65) are commonly deployed hardware

### Step 5.5: Similar Patterns
**Record:** Identical pattern for Atheros (6 devices), Cavium, TI, ASM1164, Nvidia — all DECLARE_PCI_FIXUP_HEADER(..., quirk_no_bus_reset) in same section of quirks.c

---

## PHASE 6: CROSS-REFERENCE AGAINST LOCAL TREE (6.18.44)

### Step 6.1: Buggy Code Present?
**Record:** **Yes.** The quirk entries are **missing** from this tree. Affected hardware **is supported:**
- WCN6855 (0x1103): drivers/net/wireless/ath/ath11k/pci.c (since 2021)
- WCN7850 (0x1107): drivers/net/wireless/ath/ath12k/pci.c (since 2022)
- SDX62/SDX65 (0x0308): drivers/bus/mhi/host/pci_generic.c (SDX65 since July 2025)
- PCI_VENDOR_ID_QCOM (0x17cb): include/linux/pci_ids.h

### Step 6.2: Backport Complications
**Record:** **Clean apply expected.** Target location (after Atheros quirks at line 3778, before Cavium at 3785) matches the provided diff exactly. No conflicting changes in that region.

### Step 6.3: Related Fixes Already Present?
**Record:** No — git log --grep="Avoid SBR for Qualcomm" returns nothing. Qualcomm quirk_no_bus_reset entries for 0x1103, 0x1107, 0x0308 absent from quirks.c.

---

## PHASE 7: SUBSYSTEM CONTEXT

### Step 7.1: Subsystem Criticality
**Record:** drivers/pci/ — **CORE** subsystem. PCI reset affects all PCI/PCIe devices; VFIO virtualization is a significant use case.

### Step 7.2: Activity
**Record:** Actively maintained — recent bus-reset quirks added (ASM1164 2024, Nvidia GB10 2025). Pattern is well-established and trusted.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: Who Is Affected
**Record:** Users of Qualcomm WCN6855/WCN7850 WiFi (ath11k/ath12k) and SDX62/SDX65 cellular modems (MHI) — laptops, M.2 WiFi cards, embedded modems, VFIO passthrough setups.

### Step 8.2: Trigger Conditions
**Record:**
- Any PCI reset attempt that would use Secondary Bus Reset (VFIO VM teardown, driver unbind/rebind, error recovery, manual sysfs reset)
- Not timing-dependent; deterministic hardware limitation
- Unprivileged users can trigger via VFIO if permitted by admin

### Step 8.3: Failure Mode Severity
**Record:** Without quirk: device becomes inaccessible, link down, potential **system hang or reset** (per Atheros quirk precedent in same file). Severity: **CRITICAL** for affected hardware.

### Step 8.4: Risk-Benefit
**Record:**
- **Benefit:** HIGH — prevents device bricking and system hang on common reset paths
- **Risk:** VERY LOW — 3-line quirk using proven infrastructure, scoped to 3 device IDs
- **Ratio:** Strongly favors backport

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence Summary

**FOR backport:**
- Hardware quirk — established stable exception category
- Prevents system hang/device brick on SBR (CRITICAL severity)
- Surgical 3-line fix, obviously correct
- PCI maintainer (Bjorn Helgaas) signed off
- Affected devices fully supported in 6.18.44
- Infrastructure (quirk_no_bus_reset) present since 2015
- Identical to multiple existing stable-worthy quirks in same file
- Standalone — no dependency on patches 1–2 of the series

**AGAINST backport:**
- Part of a 3-patch series; patches 1–2 (alternative reset methods) not in tree — but patch 3 independently prevents catastrophic SBR failure
- No syzbot/fuzzer report — but hardware-specific, confirmed by author testing
- Without patches 1–2, VFIO reset may still fail for these devices — but that is strictly better than hanging

**Unresolved:** Direct lore thread unreadable (bot protection); b4 dig unavailable (commit not in local repo).

### Step 9.2: Stable Rules Checklist
1. Obviously correct and tested? **PASS** — proven quirk pattern; author tested device-specific behavior vs MT7925e
2. Fixes real bug affecting users? **PASS** — broken SBR on shipping Qualcomm hardware
3. Important issue? **PASS** — CRITICAL (hang, device brick)
4. Small and contained? **PASS** — 3 lines, 1 file
5. No new features/APIs? **PASS** — hardware quirk only
6. Can apply to local tree? **PASS** — clean apply to existing code

### Step 9.3: Exception Category
**Record:** **Hardware quirk/workaround** — automatic stable qualification per instructions.

### Step 9.4: Decision Rationale
This commit adds PCI quirks preventing Secondary Bus Reset on Qualcomm devices that do not support it. The 6.18.44 tree supports these devices (ath11k, ath12k, MHI) but lacks the quirk, leaving users exposed to the same failure mode documented for Atheros devices in the same file. The fix is minimal, standalone, and follows a well-established pattern already present in stable trees.

---

## Verification

- [Phase 1] Parsed subject, tags, body; identified as hardware quirk fix
- [Phase 1] LWN v8 0/3 series context retrieved from
https://lwn.net/Articles/1077236/
- [Phase 2] Diff: 3 DECLARE_PCI_FIXUP_HEADER lines in drivers/pci/quirks.c
- [Phase 2] Read quirk_no_bus_reset() at lines 3741–3744
- [Phase 2] Read Atheros quirk hang description at lines 3767–3770
- [Phase 3] git blame: quirk_no_bus_reset from c3e59ee4e7668 (2015)
- [Phase 3] git log -S quirk_no_bus_reset: 12 historical commits, pattern established
- [Phase 3] git log --grep: commit NOT in 6.18.44 tree
- [Phase 3] Confirmed patches 1–2 (d3cold, device-specific reset) NOT in tree via git log --grep
- [Phase 4] lore.kernel.org fetch blocked by Anubis
- [Phase 4] b4 dig -c: failed (commit not in local repo)
- [Phase 4] LWN series: patch 3/3 standalone safety net for broken SBR
- [Phase 4] GitHub merge 44105c5d0a13: confirms mainline integration June 2026
- [Phase 5] grep NO_BUS_RESET drivers/pci/pci.c: 6 check sites verified
- [Phase 5] Read pci_reset_fn_methods[] at lines 5008–5017
- [Phase 5] Read pci_parent_bus_reset() at lines 4796–4812
- [Phase 6] git describe HEAD: v6.18.44
- [Phase 6] make kernelversion: 6.18.44
- [Phase 6] grep 0x1103: WCN6855 in ath11k/pci.c
- [Phase 6] grep 0x1107: WCN7850 in ath12k/pci.c
- [Phase 6] grep 0x0308: SDX65 in mhi/host/pci_generic.c
- [Phase 6] grep PCI_VENDOR_ID_QCOM: present in pci_ids.h as 0x17cb
- [Phase 6] Confirmed quirk entries absent from current quirks.c
- [Phase 6] Target insertion point matches diff (after line 3778)
- [Phase 8] Hardware support dates: WCN6855 (2021), WCN7850 (2022), SDX65/0x0308 (2025) — all predate 6.18.44
- **UNVERIFIED:** Direct lore thread review (bot-blocked)
- **UNVERIFIED:** Explicit Cc: stable nomination in mailing list

**YES**

 drivers/pci/quirks.c | 3 +++
 1 file changed, 3 insertions(+)
drivers/pci/quirks.c +3 -0
index 88d4a3f76bf3b..fbbdcbaf5aa01 100644
@@ -3776,6 +3776,9 @@ DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_ATHEROS, 0x003c, quirk_no_bus_reset);
 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_ATHEROS, 0x0033, quirk_no_bus_reset);
 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_ATHEROS, 0x0034, quirk_no_bus_reset);
 DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_ATHEROS, 0x003e, quirk_no_bus_reset);
+DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_QCOM, 0x1103, quirk_no_bus_reset); /* WCN6855 */
+DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_QCOM, 0x1107, quirk_no_bus_reset); /* WCN7850 */
+DECLARE_PCI_FIXUP_HEADER(PCI_VENDOR_ID_QCOM, 0x0308, quirk_no_bus_reset); /* SDX62/SDX65 */
 
 /*
  * Root port on some Cavium CN8xxx chips do not successfully complete a bus
Signature · 1 line
2.53.0
#236 lore raw

Re: [PATCH AUTOSEL 6.18-5.10] PCI: Avoid SBR for Qualcomm WCN6855/WCN7850 WiFi, SDX62/SDX65 modems

Sashiko has reviewed this patch and found no issues. It looks great!
Quoted 12 lines

From: Jose Ignacio Tornos Martinez <[email protected]>

[ Upstream commit 6a4f64c3a3ada43e71ef1e06da89beb36bdaeefa ]

Some Qualcomm PCIe devices (WCN6855/WCN7850 WiFi cards, SDX62/SDX65 modems) do not properly support Secondary Bus Reset (SBR).

Testing confirms this is device-specific, not deployment-specific:
MediaTek MT7925e successfully uses bus reset through the same passive M.2-to-PCIe adapters where Qualcomm devices fail, proving PERST# is properly wired through the adapters.

Quoted 6 lines

Prevent use of Secondary Bus Reset for these devices.

Sashiko has reviewed this patch and found no issues. It looks great!

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

PATCH 1/1 bitfield: wire __bf_shf to __builtin_ctzll

In reply to Sasha Levin

From: Yury Norov <[email protected]>

[ Upstream commit 09472f591aa0b72c2dd6c693f48b2d6fea66c7ba ]

__bf_shf() is currently based on built-in ffsll. It's more straightforward to wire it to __builtin_ctzll, which makes it a pure rename.

Worth to notice that __builtin_ffsll() is buggy on GCC before 14.1:

  int main() {
      sizeof(struct {
          int t : !(__builtin_ffsll(~0ULL) + 1 < 0);
      });
  }

test.c: In function 'main':
test.c:3:21: error: bit-field 't' width not an integer constant

      3 |                 int t : !(__builtin_ffsll(~0ULL) + 1 < 0);
        |                     ^

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: bitfield: wire __bf_shf to __builtin_ctzll

**Local tree:** v6.18.44 (6.18.44) — HEAD is 1efe5d048a391 Linux 6.18.44

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Subject line
**Record:** [bitfield] [wire] — Replace __bf_shf implementation from __builtin_ffsll(x)-1 with __builtin_ctzll.

### Step 1.2: Tags
**Record:**

| Tag | Value |
|-----|-------|
| Reported-by | Matt Coster \<[email protected]\> |
| Link | https://gcc.gnu.org/bugzilla/show_bug.cgi?id=124699 |
| Closes | https://lore.kernel.org/oe-kbuild-all/202603222211.A2XiR1YU-
[email protected]/ |
| Signed-off-by | Yury Norov \<[email protected]\> |

**Notable patterns:** Real reporter (IMG engineer); closes an **oe- kbuild-all** CI build failure; references a documented **GCC compiler bug** (BZ#124699). No Fixes:, Cc: stable, Tested-by, or Reviewed-by tags (absence of Cc: stable is expected per instructions).

### Step 1.3: Body analysis
**Record:**
- **Bug:** __builtin_ffsll() does not evaluate correctly in compile- time constant expressions on GCC before 14.1.
- **Symptom:** Compile failure — error: bit-field 't' width not an integer constant when __bf_shf is used inside BUILD_BUG_ON* / FIELD_PREP_CONST constant-expression checks.
- **Root cause:** __bf_shf(x) was defined as (__builtin_ffsll(x) - 1); for power-of-2 masks this is semantically equivalent to __builtin_ctzll(x), but only __builtin_ctzll works reliably as a constant expression on affected GCC versions.
- **Version info:** GCC bug affects versions **before 14.1**.

### Step 1.4: Hidden bug fix?
**Record:** Not disguised — this is an explicit **build fix** for a compiler bug affecting compile-time bitfield macro validation. No runtime behavior change for valid masks.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Inventory
**Record:**
- **Files:** include/linux/bitfield.h (+1 / -1)
- **Functions modified:** None (macro-only change)
- **Scope:** Single-file, surgical (1 line)

### Step 2.2: Code flow per hunk
**Record:**
- **Before:** __bf_shf(_mask) → (__builtin_ffsll(_mask) - 1) — shift amount from 1-based find-first-set.
- **After:** __bf_shf(_mask) → __builtin_ctzll(_mask) — shift amount from count-trailing-zeros.
- **Affected paths:** All compile-time uses in __BF_FIELD_CHECK, FIELD_MAX, FIELD_FIT, FIELD_PREP, FIELD_PREP_CONST, FIELD_GET, FIELD_MODIFY (lines 69–173 of bitfield.h). Runtime uses of __bf_shf in drivers are also affected but produce identical results for valid power-of-2 masks.

### Step 2.3: Bug mechanism
**Record:** **Build fix / compiler interaction bug (category h-adjacent).** BUILD_BUG_ON* macros expand __bf_shf(_mask) in constant-expression contexts. On GCC \< 14.1, __builtin_ffsll fails constant-folding, breaking kernel compilation. __builtin_ctzll constant-folds correctly.

### Step 2.4: Fix quality
**Record:** Obviously correct for valid masks (non-zero, power-of-2 — already enforced by existing BUILD_BUG_ON checks). Minimal change. **Regression risk: very low** — mathematically equivalent for all valid inputs; __builtin_ctzll is already used extensively elsewhere in the kernel.

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame
**Record:** __bf_shf(x) (__builtin_ffsll(x) - 1) introduced in commit 3e9b3112ec74f ("add basic register-field manipulation macros", Jakub Kicinski, 2016-08-31). Confirmed ancestor of HEAD — present in this tree since 2016.

### Step 3.2: Fixes: tag
**Record:** No Fixes: tag present. N/A.

### Step 3.3: Related file history
**Record:** Recent bitfield.h changes in 6.18.y include FIELD_MODIFY() (a256ae22570ee), FIELD_PREP_CONST() (e2192de59e457, 2023), FIELD_MAX()/FIELD_FIT(). The FIELD_PREP_CONST addition increased compile-time __bf_shf usage in initializers. Standalone 1-line fix; not part of a multi-patch dependency chain for backport purposes.

### Step 3.4: Author context
**Record:** Yury Norov is a regular bitfield/bitmap contributor (signed off on e2b02d382ae0c in this tree). Author of the broader 7.2 bitmap series on mainline.

### Step 3.5: Dependencies
**Record:** No prerequisites. Patch applies cleanly (git apply --check exit 0). Does not depend on FIELD_GET_SIGNED or other 7.2-only additions.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original discussion
**Record:** Found at
https://lkml.iu.edu/hypermail/linux/kernel/2604.3/05643.html (also
https://lists.openwall.net/linux-kernel/2026/04/27/2584). b4 dig -c failed because commit is not in this tree. Single patch, not a multi- revision series for this specific fix.

### Step 4.2: Reviewers
**Record:** CC'd to Rasmus Villemoes (bitfield maintainer area), multiple IMG engineers (reporters of the build failure), Vincent Mailhol. David Laight replied with a style suggestion only ("I'd leave in the (x)") — not a NAK.

### Step 4.3: Bug report
**Record:** Closes oe-kbuild-all report from 2026-03-22 (kernel CI build robot — concrete compile failure). Matt Coster (IMG) reported. GCC BZ#124699 documents the compiler defect (lore.kernel.org fetch blocked by bot protection; GCC bugzilla returned 403).

### Step 4.4: Related patches
**Record:** Part of Yury's "bitmap-for-7.2" series on mainline (patch 11/19), but this specific change is fully self-contained.

### Step 4.5: Stable list history
**Record:** No stable-specific discussion found. No reviewer explicitly nominated Cc: stable, but build fixes are routinely backported.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key symbols
**Record:** __bf_shf macro; consumers: __BF_FIELD_CHECK, FIELD_MAX, FIELD_FIT, FIELD_PREP, FIELD_PREP_CONST, FIELD_GET, FIELD_MODIFY.

### Step 5.2: Callers
**Record:** FIELD_GET/FIELD_PREP/FIELD_PREP_CONST used in hundreds of files across drivers, net, sound, GPU, PCI, etc. Direct __bf_shf() calls in drivers (spi-dw-core, mv88e6xxx, iwlwifi, nfp, etc.). Very broad impact surface.

### Step 5.3: Callees
**Record:** Changes compiler builtin from __builtin_ffsll to __builtin_ctzll. No kernel function calls.

### Step 5.4: Reachability
**Record:** Triggered at **compile time** when any translation unit using FIELD_* macros is built with GCC \< 14.1. Affects all developers/distributions building 6.18.y with GCC 12/13 (common toolchain versions).

### Step 5.5: Similar patterns
**Record:** Kernel already uses __builtin_ctzll widely (e.g., lib/math/div64.c, fs/btrfs/volumes.h). The ffsll(x)-1 ≡ ctzll(x) equivalence for power-of-2 values is standard.

---

## PHASE 6: CROSS-REFERENCE AGAINST LOCAL TREE

### Step 6.1: Buggy code exists?
**Record:** **YES.** Line 45 of include/linux/bitfield.h:

```45:45:include/linux/bitfield.h
#define __bf_shf(x) (__builtin_ffsll(x) - 1)
```

Present since 2016 in this tree. Commit under review is **not yet applied** (git log --grep="wire __bf_shf" returns empty).

### Step 6.2: Backport complications
**Record:** **Clean apply** — verified with git apply --check. No conflicts expected.

### Step 6.3: Related fixes already present?
**Record:** None. git log --grep="wire __bf_shf" and git log --grep="__builtin_ctzll" -- include/linux/bitfield.h show no equivalent fix in this tree.

**Note:** tools/include/linux/bitfield.h line 43 still has the old definition; the upstream commit also only touches include/linux/bitfield.h. Minor gap for tools-only builds, not a reason to reject the kernel header fix.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

### Step 7.1: Subsystem criticality
**Record:** **CORE** — include/linux/bitfield.h is a foundational header used across virtually every driver subsystem.

### Step 7.2: Activity
**Record:** Moderately active in 6.18.y (FIELD_MODIFY, __must_check additions in 2025). The underlying __bf_shf definition has been stable since 2016; the compiler interaction is the issue, not recent kernel churn.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: Who is affected
**Record:** Anyone building kernel 6.18.y with **GCC \< 14.1** (GCC 12.x, 13.x — standard for RHEL, Debian stable, many embedded SDKs). Universal compile-time impact across all subsystems using FIELD_* macros.

### Step 8.2: Trigger conditions
**Record:** Building any config that compiles a file using FIELD_GET/FIELD_PREP/FIELD_PREP_CONST/etc. with affected GCC. Documented CI failure (oe-kbuild-all, March 2026). Not userspace- triggerable; not a runtime bug.

### Step 8.3: Failure mode severity
**Record:** **Build failure** (compilation error) — severity **HIGH** for affected builders (cannot compile kernel). No runtime crash, corruption, or security impact.

### Step 8.4: Risk-benefit
**Record:**
- **Benefit: HIGH** — restores ability to build with common GCC versions; fixes documented CI failure.
- **Risk: VERY LOW** — 1-line semantic rename for valid inputs; no API change; no runtime behavior change.
- **Ratio:** Strongly favors backport.

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence summary

**FOR backport:**
- Documented real build failure (oe-kbuild-all CI, March 2026)
- User report from Matt Coster (IMG)
- GCC BZ#124699 — known compiler bug
- Build-fix category (explicit stable exception per rules)
- 1 line, applies cleanly to 6.18.44
- Buggy code present since 2016 in this tree
- FIELD_* macros used in hundreds of files
- Mathematically equivalent fix, minimal regression risk

**AGAINST backport:**
- Only compile-time impact, not runtime
- Bug latent since 2016 — may be config/GCC-version specific
- tools/include/linux/bitfield.h not updated in same commit
- Not yet in this tree's git history (must land in mainline first per stable rules)

**Unresolved:** Exact oe-kbuild-all log unavailable (lore bot protection). Could not test on GCC \< 14.1 locally (only GCC 15.3 available; test passed). GCC bugzilla page returned 403.

### Step 9.2: Stable rules checklist

| Criterion | Result |
|-----------|--------|
| 1. Obviously correct and tested? | **PASS** — semantic equivalence
proven; CI failure closed |
| 2. Fixes real bug affecting users? | **PASS** — kernel build failure
with GCC \< 14.1 |
| 3. Important issue? | **PASS** — build error (stable-kernel-rules.rst
line 19) |
| 4. Small and contained? | **PASS** — 1 line, 1 file |
| 5. No new features/APIs? | **PASS** — internal macro implementation
change only |
| 6. Can apply to local tree? | **PASS** — clean apply verified |

### Step 9.3: Exception category
**Record:** **BUILD FIX** — explicitly listed as stable-worthy.

### Step 9.4: Decision rationale
This commit fixes a documented kernel **compilation failure** on GCC versions before 14.1, which remain widely used for building stable kernels. The buggy __bf_shf definition has been in 6.18.y since 2016 and is used by core FIELD_* macros throughout the tree. The fix is a one-line, semantically equivalent substitution that applies cleanly to v6.18.44 with negligible regression risk.

---

## Verification

- **[Phase 1]** Parsed subject, tags (Reported-by, Link, Closes), body; identified GCC \< 14.1 build failure
- **[Phase 2]** Diff: 1 line in include/linux/bitfield.h; __builtin_ffsll(x)-1 → __builtin_ctzll
- **[Phase 3]** git blame -L 45,45: introduced 3e9b3112ec74f (2016); confirmed ancestor of HEAD
- **[Phase 3]** git log --oneline -20 -- include/linux/bitfield.h:
recent changes listed; no duplicate fix
- **[Phase 3]** git apply --check: patch applies cleanly (exit 0)
- **[Phase 4]** lkml.iu.edu/2604.3/05643.html: found original submission
- **[Phase 4]** openwall.net 2026/04/28/111: David Laight style comment only, no objection
- **[Phase 4]** b4 dig -c: FAILED — commit not in local tree
- **[Phase 4]** lore.kernel.org oe-kbuild-all link: BLOCKED (bot protection)
- **[Phase 4]** gcc.gnu.org BZ#124699: BLOCKED (403)
- **[Phase 5]** grep FIELD_GET/FIELD_PREP: hundreds of .c files across tree
- **[Phase 5]** grep __bf_shf: 10 uses in bitfield.h + many direct driver uses
- **[Phase 6]** git describe HEAD: v6.18.44
- **[Phase 6]** make -s kernelversion: 6.18.44
- **[Phase 6]** Read include/linux/bitfield.h line 45: buggy definition confirmed present
- **[Phase 6]** git log --grep="wire __bf_shf": empty — fix not yet in tree
- **[Phase 8]** GCC 15.3 test of __builtin_ffsll(~0ULL) constant expr:
compiles (exit 0); UNVERIFIED on GCC \< 14.1 (not installed)

**YES**The background checks finished and match what the analysis already used:

- **Commit search:** git log --grep="wire __bf_shf" returned nothing — this fix is not in the local 6.18.44 tree yet.
- **b4 dig:** Failed (--subject is not a valid b4 dig option). The patch thread was found via lkml/openwall instead.
- **FIELD_PREP_CONST history:** Added in e2192de59e457 (Jan 2023), which increased compile-time __bf_shf use in constant expressions.
- **Tree state:** HEAD is 1efe5d048a391 (Linux 6.18.44); line 45 of include/linux/bitfield.h still has the old __builtin_ffsll definition.

**Verdict remains YES** — one-line build fix for GCC \< 14.1, applies cleanly to this tree.

 include/linux/bitfield.h | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
include/linux/bitfield.h +1 -1
index 5355f8f806a97..2b3127e712b93 100644
@@ -42,7 +42,7 @@
  *  FIELD_MODIFY(REG_FIELD_C, &reg, c);
  */
 
-#define __bf_shf(x) (__builtin_ffsll(x) - 1)
+#define __bf_shf __builtin_ctzll
 
 #define __scalar_type_to_unsigned_cases(type)				\
 		unsigned type:	(unsigned type)0,			\
Signature · 1 line
2.53.0
author maintainer
#238 lore raw

PATCH 1/1 ata: libata-core: Disable LPM on some WD drives

In reply to Sasha Levin

From: Niklas Cassel <[email protected]>

[ Upstream commit 356d8241cf3c7b07a4a491dbab43b5a41513ca86 ]

According to a user report WDC WD100EFGX-68CPLN0 and WDC WD102KFBX-68M95N0 have problems with LPM.

---

LLM Generated explanations, may be completely bogus:

## Phase 1: Commit Message Forensics

**Step 1.1 — Subject line**
- Record: [ata: libata-core] [Disable] — Add ATA device quirks to disable Link Power Management (LPM) on two specific Western Digital drive models.

**Step 1.2 — Tags**
- Record:
- Closes: https://bugzilla.kernel.org/show_bug.cgi?id=220693
- Signed-off-by: Niklas Cassel <[email protected]> (author/subsystem maintainer)
- Signed-off-by: Damien Le Moal <[email protected]> (libata maintainer)
- No Fixes:, Reported-by:, Tested-by:, Reviewed-by:, or `Cc:
[email protected]` tags
- Notable: bugzilla closure link; maintainer sign-offs from libata maintainers

**Step 1.3 — Body analysis**
- Record:
- **Bug:** WDC WD100EFGX-68CPLN0 and WDC WD102KFBX-68M95N0 have problems with LPM
- **Symptom (from bugzilla):** "SATA bus goes offline after a while"

    (bug 220693, reported 2025-10-22)

- **Version info:** None in commit message
- **Root cause (from patch comment):** Existing ATA_QUIRK_WD_BROKEN_LPM only applies to SATA Gen1 drives; these modern WD models need unconditional ATA_QUIRK_NOLPM

**Step 1.4 — Hidden bug fix detection**
- Record: Not disguised — this is an explicit hardware quirk/workaround fix, though the subject says "Disable" rather than "fix". Classic device-specific LPM workaround pattern.

---

## Phase 2: Diff Analysis

**Step 2.1 — Change inventory**
- Record:
- Files: drivers/ata/libata-core.c (+8 lines, 0 removed)
- Functions: modifies __ata_dev_quirks[] static table only
- Scope: single-file, surgical quirk-table addition

**Step 2.2 — Code flow change**
- Record:
- **Hunk (quirk table):** Before — no quirk entries for WD100EFGX or WD102KFBX; LPM enabled normally. After — both models matched via glob_match() and assigned ATA_QUIRK_NOLPM, which forces ATA_LPM_MAX_POWER in ata_dev_config_lpm() and prevents LPM in ata_scsi_lpm_supported().

**Step 2.3 — Bug mechanism**
- Record:
- **Category:** Hardware workaround (LPM incompatibility)
- **Mechanism:** These WD drives malfunction when SATA link power management is used (slumber/partial states). Without the quirk, ata_dev_config_lpm() does not disable LPM. With ATA_QUIRK_NOLPM, LPM is disabled at probe and the port policy is forced to max power, preventing the drive from dropping off the SATA bus.

**Step 2.4 — Fix quality**
- Record:
- Obviously correct: uses established ATA_QUIRK_NOLPM mechanism already used for ADATA, Seagate, Samsung, and other drives in the same table
- Minimal and surgical: two model strings plus explanatory comment
- Regression risk: very low; only affects exact model matches; trade- off is slightly higher power consumption on those drives (standard accepted cost of NOLPM quirks)

---

## Phase 3: Git History Investigation

**Step 3.1 — Blame**
- Record: WD ATA_QUIRK_WD_BROKEN_LPM entries date to commit ecd75ad514d73 ("libata: disable LPM for some WD SATA-I devices"), present since v4.6 era. The buggy behavior (no quirk for these models) is simply the absence of entries — not a recently introduced regression in libata code.

**Step 3.2 — Fixes: tag**
- Record: N/A — no Fixes: tag present.

**Step 3.3 — File history**
- Record: Recent stable-tree libata LPM quirk backports include:
- 2229b4cf97301 — ADATA SU680 NOLPM (backported to 6.18.y)
- 87f0349beaaca — ST1000DM010 NOLPM
- a70fd483c4b93 — ST2000DM008 NOLPM
- Standalone fix; part of a 2-patch series on mainline (patch 2 adds a different WD Green model) but patch 1 is self-contained.

**Step 3.4 — Author context**
- Record: Niklas Cassel is libata maintainer; Damien Le Moal is primary libata maintainer. Both signed off. Maintainer applied series to for-7.2-fixes per lore reply.

**Step 3.5 — Dependencies**
- Record: No dependencies. ATA_QUIRK_NOLPM, ata_dev_quirks(), ata_dev_config_lpm(), and glob_match() all exist in this tree. Applies cleanly (git apply --check passed).

---

## Phase 4: Mailing List and External Research

**Step 4.1 — Original discussion**
- Record:
- Lore URL:

    https://patch.msgid.link/[email protected]

- Series: v1 only (no further revisions)
- Damien Le Moal: "Applied to for-7.2-fixes. Thanks!"
- No NAKs; no explicit stable nomination in thread

**Step 4.2 — Reviewers**
- Record: CC'd to [email protected], Damien Le Moal, Ronald Garcia Vazquez (likely reporter contact). Maintainers directly involved.

**Step 4.3 — Bug report**
- Record:
- Bugzilla 220693: "SATA bus goes offline after a while"
- Reported by Emerson Pinter, 2025-10-22
- Marked as regression with bisect to 459779d04ae8 (block read-ahead change) — that commit is **not** in the 6.18.y tree; the LPM quirk fix addresses the drive-specific failure mode regardless
- Severity: disk/bus disappearance is a serious usability and potential data-integrity issue

**Step 4.4 — Related patches**
- Record: Patch 2/2 (WD Green 2.5 480GB) is a separate one-line quirk for a different model; not required for this commit to function.

**Step 4.5 — Stable list**
- Record: No stable-list discussion found for this specific commit.
Precedent: ADATA SU680 NOLPM quirk (2229b4cf97301) was explicitly nominated with Cc: [email protected] and backported to 6.18.y.

---

## Phase 5: Code Semantic Analysis

**Step 5.1 — Key functions**
- Record: __ata_dev_quirks[] (modified), ata_dev_quirks() (consumer), ata_dev_config_lpm() (applies NOLPM), ata_scsi_lpm_supported() (checks NOLPM)

**Step 5.2 — Callers**
- Record: ata_dev_quirks() called from device identification path at line 2978 (dev->quirks |= ata_dev_quirks(dev)), during normal SATA device probe/enumeration — common boot and hotplug path.

**Step 5.3 — Callees**
- Record: glob_match() for model string matching; quirk bits consumed by ata_dev_config_lpm() and ata_scsi_lpm_supported().

**Step 5.4 — Reachability**
- Record: Triggered automatically when a matching WD drive is detected on any SATA controller using libata. No special config needed beyond CONFIG_ATA.

**Step 5.5 — Similar patterns**
- Record: Extensive existing NOLPM quirk entries in the same table (ADATA SU680, ST1000DM010, ST2000DM008, Samsung SSDs, etc.) — identical fix pattern.

---

## Phase 6: Cross-Reference Against Local Tree

**Step 6.1 — Buggy code in tree**
- Record: Local tree is **Linux 6.18.44** (v6.18.44-2-g1b9e1abadee04, detached from stable/linux-6.18.y). The WD100EFGX/WD102KFBX quirk entries are **absent**; commit 356d8241cf3c7 is on master only (NOT_IN_CURRENT_TREE). The quirk infrastructure and ATA_QUIRK_NOLPM are fully present. Bug affects any user with these drive models on 6.18.y.

**Step 6.2 — Backport complications**
- Record: Clean apply confirmed. Line numbers differ slightly (stable table ends at line 4373 vs mainline 4413) but patch applies without conflict.

**Step 6.3 — Related fixes already present**
- Record: Similar NOLPM quirks for ADATA SU680, ST1000DM010, ST2000DM008 already in 6.18.y. No duplicate fix for these WD models.

---

## Phase 7: Subsystem and Maintainer Context

**Step 7.1 — Subsystem criticality**
- Record: drivers/ata/ — IMPORTANT (storage stack; affects users with affected hardware)

**Step 7.2 — Subsystem activity**
- Record: Actively maintained in 6.18.y with recent stable backports including LPM quirks, error handling fixes, and SCSI path fixes.

---

## Phase 8: Impact and Risk Assessment

**Step 8.1 — Who is affected**
- Record: Users with WDC WD100EFGX-68CPLN0 or WDC WD102KFBX-68M95N0 drives on any libata SATA port. WD Red/Black enterprise/consumer HDDs — real, commonly deployed hardware.

**Step 8.2 — Trigger conditions**
- Record: Occurs during normal operation when LPM is active on the SATA link — not exotic. Triggered on every boot/probe for matching drives; failure manifests over time ("after a while").

**Step 8.3 — Failure mode severity**
- Record: SATA bus goes offline → drive disappears, I/O errors, potential data loss. Severity: **HIGH** (serious functional failure, possible data integrity impact).

**Step 8.4 — Risk-benefit**
- Record:
- Benefit: **High** for affected hardware — restores reliable disk operation
- Risk: **Very low** — 8-line quirk addition, exact model match only, established mechanism
- Ratio: strongly favors backport

---

## Phase 9: Final Synthesis

**Step 9.1 — Evidence summary**

FOR backporting:
- Fixes real user-reported bug (bugzilla 220693)
- Hardware quirk — explicit stable exception category
- Identical pattern to NOLPM quirks already backported to 6.18.y
- Small, surgical, applies cleanly
- Subsystem maintainer authored and applied
- Serious failure mode (SATA bus offline)

AGAINST backporting:
- No Tested-by: on this specific commit (minor; ADATA quirk had one)
- No explicit Cc: stable tag (not a negative signal per instructions)
- Bugzilla regression bisect points elsewhere, but fix targets documented LPM failure mode

**Step 9.2 — Stable rules checklist**
1. Obviously correct and tested? **PASS** — standard quirk mechanism; maintainer-reviewed
2. Fixes a real bug affecting users? **PASS** — bugzilla user report, SATA bus offline
3. Important issue? **PASS** — drive/bus failure, HIGH severity
4. Small and contained? **PASS** — 8 lines, one file
5. No new features or APIs? **PASS** — quirk table entries only
6. Can apply to local tree? **PASS** — clean apply verified

**Step 9.3 — Exception category**
- Record: **Hardware quirk/workaround** — automatic stable qualification.

**Step 9.4 — Decision rationale**

This commit adds two model-specific ATA_QUIRK_NOLPM entries for WD drives that drop off the SATA bus when LPM is enabled. The fix uses infrastructure already present and proven in 6.18.y through prior NOLPM backports. It is not in the current 6.18.44 tree but applies cleanly and addresses a serious, user-visible hardware failure. This is textbook stable material.

---

## Verification

- [Phase 1] Parsed commit 356d8241cf3c7: subject, tags, body, bugzilla link
- [Phase 2] Full diff reviewed: 8 lines added to __ata_dev_quirks[] in drivers/ata/libata-core.c
- [Phase 3] git describe HEAD: v6.18.44 (6.18.y stable tree)
- [Phase 3] git merge-base --is-ancestor 356d8241cf3c7 HEAD:
NOT_IN_CURRENT_TREE
- [Phase 3] git blame on WD_BROKEN_LPM lines: introduced in ecd75ad514d73 (v4.6 era)
- [Phase 3] Prior NOLPM backports in stable: 2229b4cf97301, 87f0349beaaca, a70fd483c4b93 confirmed
- [Phase 4] b4 dig -c 356d8241cf3c7: lore thread found
- [Phase 4] b4 dig -a: v1 only, no later revisions
- [Phase 4] b4 dig -w: CC to linux-ide, Damien Le Moal, reporter
- [Phase 4] Mbox: Damien Le Moal applied to for-7.2-fixes; patch 2/2 is separate drive
- [Phase 4] Bugzilla 220693: "SATA bus goes offline after a while", reported 2025-10-22
- [Phase 5] grep ata_dev_quirks: called from device probe at line 2978
- [Phase 5] Read ata_dev_config_lpm(): NOLPM forces ATA_LPM_MAX_POWER
- [Phase 5] Read ata_scsi_lpm_supported(): checks ATA_QUIRK_NOLPM
- [Phase 6] grep WD100EFGX|WD102KFBX in tree: no matches (bug present)
- [Phase 6] git format-patch | git apply --check: applies cleanly
- [Phase 6] ATA_QUIRK_NOLPM defined in include/linux/libata.h:
present
- [Phase 8] Bugzilla regression bisect commit 459779d04ae8: NOT in 6.18.y tree (irrelevant to applicability)

**YES**The background checks finished and match the earlier analysis:

- **Master search:** Found commit 356d8241cf3c7 — "ata: libata-core:
Disable LPM on some WD drives"
- **Tree check:** That commit is on master only, **not** in the current 6.18.44 stable checkout

The backport recommendation stands: **YES** — add the two WD ATA_QUIRK_NOLPM entries for WD100EFGX and WD102KFBX; the patch applies cleanly to this tree.

 drivers/ata/libata-core.c | 8 ++++++++
 1 file changed, 8 insertions(+)
drivers/ata/libata-core.c +8 -0
index f0753f5e57a8e..ae1e5f82026c5 100644
@@ -4372,6 +4372,14 @@ static const struct ata_dev_quirks_entry __ata_dev_quirks[] = {
 	{ "WDC WD3000JD-*",		NULL,	ATA_QUIRK_WD_BROKEN_LPM },
 	{ "WDC WD3200JD-*",		NULL,	ATA_QUIRK_WD_BROKEN_LPM },
 
+	/*
+	 * WD drives with LPM issues (irrespective of supported SATA speeds).
+	 * (Unlike ATA_QUIRK_WD_BROKEN_LPM, which is only applied if the drive
+	 * exposes SATA Gen1 speed support, and SATA Gen1 speed support only.)
+	 */
+	{ "WDC WD100EFGX-68CPLN0",	NULL,	ATA_QUIRK_NOLPM },
+	{ "WDC WD102KFBX-68M95N0",	NULL,	ATA_QUIRK_NOLPM },
+
 	/*
 	 * This sata dom device goes on a walkabout when the ATA_LOG_DIRECTORY
 	 * log page is accessed. Ensure we never ask for this log page with
Signature · 1 line
2.53.0
author maintainer
#239 lore raw

PATCH 1/1 virt: acrn: Fix irqfd use-after-free during eventfd shutdown

In reply to Sasha Levin

From: Sicong Huang <[email protected]>

[ Upstream commit 666c7f9e07925aa0863348f960e09bb89f8f05a3 ]

acrn_irqfd_deassign() and the eventfd EPOLLHUP wakeup can race and free the same struct hsm_irqfd:

CPU0 CPU1
---- ----
eventfd_release()

    wake_up_poll(EPOLLHUP)
      hsm_irqfd_wakeup()
        queue_work(&irqfd->shutdown)
                                       acrn_irqfd_deassign()
                                         hsm_irqfd_shutdown()
                                           list_del_init()
                                           eventfd_ctx_remove_wait_queue()
                                           eventfd_ctx_put()
                                         kfree(irqfd)

hsm_irqfd_shutdown_work()
container_of(work, ..., shutdown)
irqfd->vm <-- use-after-free

The deassign path freed the irqfd while a shutdown work item was already queued by EPOLLHUP (or vice versa), so the work item could resurrect a dangling pointer through container_of().

Switch to the lifetime model used by KVM irqfds:

- Deassign/deinit only deactivate the irqfd: remove it from vm->irqfds under irqfds_lock and queue the cleanup work.
- hsm_irqfd_shutdown_work() becomes the sole owner that unhooks the eventfd waitqueue entry, drops the eventfd reference and frees the irqfd.
- A new HSM_IRQFD_FLAG_SHUTDOWN bit guarded by test_and_set_bit() ensures the cleanup work is queued at most once, no matter how many of {EPOLLHUP, deassign, deinit} fire concurrently. This is safe to call from the waitqueue callback, which runs with wqh->lock held and IRQs disabled and therefore cannot take irqfds_lock.
- acrn_irqfd_deassign() flushes vm->irqfd_wq before returning so the eventfd is fully detached on return. acrn_irqfd_deinit() deactivates every irqfd, flushes the workqueue and only then destroys it, so no path can queue_work() onto a torn-down workqueue.
- acrn_irqfd_assign() now installs the eventfd waitqueue entry and publishes the irqfd to vm->irqfds under irqfds_lock, so the irqfd is never visible to deassign/deinit before its waitqueue entry is in place, and any EPOLLHUP that fires in the assign window queues cleanup work that blocks on irqfds_lock until publication is done.

---

LLM Generated explanations, may be completely bogus:

That check finished: git log -S "hsm_irqfd_queue_shutdown" on HEAD returned no matches, so the irqfd UAF fix is not in **6.18.44** yet. That lines up with the earlier **YES** backport recommendation.

 drivers/virt/acrn/irqfd.c | 71 ++++++++++++++++++++++++---------------
 1 file changed, 44 insertions(+), 27 deletions(-)
drivers/virt/acrn/irqfd.c +44 -27
index 64d32c8fbf79b..b18d1a9021fb4 100644
@@ -16,6 +16,9 @@
 
 #include "acrn_drv.h"
 
+/* Cleanup work has been queued; set via test_and_set_bit(). */
+#define HSM_IRQFD_FLAG_SHUTDOWN	0
+
 /**
  * struct hsm_irqfd - Properties of HSM irqfd
  * @vm:		Associated VM pointer
@@ -25,6 +28,7 @@
  * @list:	Entry within &acrn_vm.irqfds of irqfds of a VM
  * @pt:		Structure for select/poll on the associated eventfd
  * @msi:	MSI data
+ * @flags:	Internal lifecycle flags (HSM_IRQFD_FLAG_*)
  */
 struct hsm_irqfd {
 	struct acrn_vm		*vm;
@@ -34,6 +38,7 @@ struct hsm_irqfd {
 	struct list_head	list;
 	poll_table		pt;
 	struct acrn_msi_entry	msi;
+	unsigned long		flags;
 };
 
 static void acrn_irqfd_inject(struct hsm_irqfd *irqfd)
@@ -44,30 +49,29 @@ static void acrn_irqfd_inject(struct hsm_irqfd *irqfd)
 			irqfd->msi.msi_data);
 }
 
-static void hsm_irqfd_shutdown(struct hsm_irqfd *irqfd)
+/* Queue the cleanup work at most once. Safe from atomic context. */
+static void hsm_irqfd_queue_shutdown(struct hsm_irqfd *irqfd)
 {
-	u64 cnt;
-
-	lockdep_assert_held(&irqfd->vm->irqfds_lock);
-
-	/* remove from wait queue */
-	list_del_init(&irqfd->list);
-	eventfd_ctx_remove_wait_queue(irqfd->eventfd, &irqfd->wait, &cnt);
-	eventfd_ctx_put(irqfd->eventfd);
-	kfree(irqfd);
+	if (!test_and_set_bit(HSM_IRQFD_FLAG_SHUTDOWN, &irqfd->flags))
+		queue_work(irqfd->vm->irqfd_wq, &irqfd->shutdown);
 }
 
+/* Sole owner of @irqfd: unhook waitqueue, drop eventfd ref, free. */
 static void hsm_irqfd_shutdown_work(struct work_struct *work)
 {
-	struct hsm_irqfd *irqfd;
-	struct acrn_vm *vm;
+	struct hsm_irqfd *irqfd = container_of(work, struct hsm_irqfd,
+					       shutdown);
+	struct acrn_vm *vm = irqfd->vm;
+	u64 cnt;
 
-	irqfd = container_of(work, struct hsm_irqfd, shutdown);
-	vm = irqfd->vm;
 	mutex_lock(&vm->irqfds_lock);
 	if (!list_empty(&irqfd->list))
-		hsm_irqfd_shutdown(irqfd);
+		list_del_init(&irqfd->list);
 	mutex_unlock(&vm->irqfds_lock);
+
+	eventfd_ctx_remove_wait_queue(irqfd->eventfd, &irqfd->wait, &cnt);
+	eventfd_ctx_put(irqfd->eventfd);
+	kfree(irqfd);
 }
 
 /* Called with wqh->lock held and interrupts disabled */
@@ -76,17 +80,16 @@ static int hsm_irqfd_wakeup(wait_queue_entry_t *wait, unsigned int mode,
 {
 	unsigned long poll_bits = (unsigned long)key;
 	struct hsm_irqfd *irqfd;
-	struct acrn_vm *vm;
 
 	irqfd = container_of(wait, struct hsm_irqfd, wait);
-	vm = irqfd->vm;
+
 	if (poll_bits & POLLIN)
 		/* An event has been signaled, inject an interrupt */
 		acrn_irqfd_inject(irqfd);
 
 	if (poll_bits & POLLHUP)
-		/* Do shutdown work in thread to hold wqh->lock */
-		queue_work(vm->irqfd_wq, &irqfd->shutdown);
+		/* Defer teardown to the cleanup work; can't sleep here. */
+		hsm_irqfd_queue_shutdown(irqfd);
 
 	return 0;
 }
@@ -142,6 +145,12 @@ static int acrn_irqfd_assign(struct acrn_vm *vm, struct acrn_irqfd *args)
 	init_waitqueue_func_entry(&irqfd->wait, hsm_irqfd_wakeup);
 	init_poll_funcptr(&irqfd->pt, hsm_irqfd_poll_func);
 
+	/*
+	 * Hold irqfds_lock across waitqueue install and list_add so the
+	 * irqfd is not visible to deassign/deinit before its waitqueue
+	 * entry is in place, and any racing EPOLLHUP cleanup work blocks
+	 * on irqfds_lock until publication completes.
+	 */
 	mutex_lock(&vm->irqfds_lock);
 	list_for_each_entry(tmp, &vm->irqfds, list) {
 		if (irqfd->eventfd != tmp->eventfd)
@@ -150,14 +159,12 @@ static int acrn_irqfd_assign(struct acrn_vm *vm, struct acrn_irqfd *args)
 		mutex_unlock(&vm->irqfds_lock);
 		goto fail;
 	}
-	list_add_tail(&irqfd->list, &vm->irqfds);
-	mutex_unlock(&vm->irqfds_lock);
 
-	/* Check the pending event in this stage */
 	events = vfs_poll(fd_file(f), &irqfd->pt);
-
+	list_add_tail(&irqfd->list, &vm->irqfds);
 	if (events & EPOLLIN)
 		acrn_irqfd_inject(irqfd);
+	mutex_unlock(&vm->irqfds_lock);
 
 	return 0;
 fail:
@@ -180,13 +187,17 @@ static int acrn_irqfd_deassign(struct acrn_vm *vm,
 	mutex_lock(&vm->irqfds_lock);
 	list_for_each_entry_safe(irqfd, tmp, &vm->irqfds, list) {
 		if (irqfd->eventfd == eventfd) {
-			hsm_irqfd_shutdown(irqfd);
+			list_del_init(&irqfd->list);
+			hsm_irqfd_queue_shutdown(irqfd);
 			break;
 		}
 	}
 	mutex_unlock(&vm->irqfds_lock);
 	eventfd_ctx_put(eventfd);
 
+	/* Wait for cleanup work to finish so the eventfd is fully detached. */
+	flush_workqueue(vm->irqfd_wq);
+
 	return 0;
 }
 
@@ -219,9 +230,15 @@ void acrn_irqfd_deinit(struct acrn_vm *vm)
 	struct hsm_irqfd *irqfd, *next;
 
 	dev_dbg(acrn_dev.this_device, "VM %u irqfd deinit.\n", vm->vmid);
-	destroy_workqueue(vm->irqfd_wq);
+
 	mutex_lock(&vm->irqfds_lock);
-	list_for_each_entry_safe(irqfd, next, &vm->irqfds, list)
-		hsm_irqfd_shutdown(irqfd);
+	list_for_each_entry_safe(irqfd, next, &vm->irqfds, list) {
+		list_del_init(&irqfd->list);
+		hsm_irqfd_queue_shutdown(irqfd);
+	}
 	mutex_unlock(&vm->irqfds_lock);
+
+	/* Drain all cleanup work before tearing the workqueue down. */
+	flush_workqueue(vm->irqfd_wq);
+	destroy_workqueue(vm->irqfd_wq);
 }
Signature · 1 line
2.53.0
author maintainer
#240 lore raw

PATCH 1/1 drm/amd/pm/si: Fix updating clock limits from power states

In reply to Sasha Levin

From: Jeremy Klarenbeek <[email protected]>

[ Upstream commit e6c5d36756e7d4d260e2365fc4d01226f1973152 ]

VBIOS can contain conflicting values between:
- the maximum allowed clocks and voltages on AC or DC
- the clocks and voltages in power states on AC or DC

Update maximum clock (and voltage) limits for both AC/DC and take the highest value from the VBIOS limits and the performance/battery power states. Previously this was only done for AC, but is also needed for DC.

This commit fixes the behaviour on some laptop GPUs, where the VBIOS limit was set to the lowest possible clock frequency, so the GPU was stuck on the lowest possible power level on battery.

Some affected GPUs are:
FirePro W4170M (Dell Precision M2800)
Radeon HD 8790M (Dell Latitude E6540)
and possibly other laptop GPUs.

---

LLM Generated explanations, may be completely bogus:

The background git searches finished and match the earlier analysis:

- **History search:** The AC-only max_clock_voltage_on_ac assignment traces back through the SI DPM code (pickaxe hit 837d542a09cd5, the pm header relocation). No prior fix for DC clock limits was found.
- **Author search:** Jeremy Klarenbeek has no commits in this 6.18.44 tree.
- **Fix commit search:** git log --grep="updating clock limits" returned nothing — the patch is not in this tree yet. The only "power states" hit in si_dpm.c was an unrelated debug-level change.
- **Hardware search:** No existing commits mention the FirePro W4170M or Radeon HD 8790M by name.

That supports the **YES** backport recommendation: the bug is present and unfixed in 6.18.44, and this would be a new, standalone fix.The hardware-related git search completed: there are no commits in this 6.18.44 tree that mention the FirePro W4170M, Radeon HD 8790M, or author Jeremy Klarenbeek in connection with this clock-limits issue. That confirms this would be a new fix rather than something already present under a different commit.

 drivers/gpu/drm/amd/pm/legacy-dpm/si_dpm.c | 29 ++++++++++++++++++----
 1 file changed, 24 insertions(+), 5 deletions(-)
drivers/gpu/drm/amd/pm/legacy-dpm/si_dpm.c +24 -5
index 0385b24e7e4a2..ea97276358c0a 100644
@@ -7238,6 +7238,7 @@ static void si_parse_pplib_clock_info(struct amdgpu_device *adev,
 	struct evergreen_power_info *eg_pi = evergreen_get_pi(adev);
 	struct si_power_info *si_pi = si_get_pi(adev);
 	struct  si_ps *ps = si_get_ps(rps);
+	struct amdgpu_clock_and_voltage_limits *limits;
 	u16 leakage_voltage;
 	struct rv7xx_pl *pl = &ps->performance_levels[index];
 	int ret;
@@ -7297,12 +7298,30 @@ static void si_parse_pplib_clock_info(struct amdgpu_device *adev,
 		si_pi->mvdd_bootup_value = mvdd;
 	}
 
+	/*
+	 * Update maximum allowed clock limits.
+	 * VBIOS can contain conflicting values between:
+	 * - the maximum allowed clocks and voltages on AC or DC
+	 * - the clocks and voltages in power states on AC or DC
+	 */
 	if ((rps->class & ATOM_PPLIB_CLASSIFICATION_UI_MASK) ==
-	    ATOM_PPLIB_CLASSIFICATION_UI_PERFORMANCE) {
-		adev->pm.dpm.dyn_state.max_clock_voltage_on_ac.sclk = pl->sclk;
-		adev->pm.dpm.dyn_state.max_clock_voltage_on_ac.mclk = pl->mclk;
-		adev->pm.dpm.dyn_state.max_clock_voltage_on_ac.vddc = pl->vddc;
-		adev->pm.dpm.dyn_state.max_clock_voltage_on_ac.vddci = pl->vddci;
+	    ATOM_PPLIB_CLASSIFICATION_UI_PERFORMANCE)
+		limits = &adev->pm.dpm.dyn_state.max_clock_voltage_on_ac;
+	else if ((rps->class & ATOM_PPLIB_CLASSIFICATION_UI_MASK) ==
+		 ATOM_PPLIB_CLASSIFICATION_UI_BATTERY)
+		limits = &adev->pm.dpm.dyn_state.max_clock_voltage_on_dc;
+	else
+		limits = NULL;
+
+	if (limits) {
+		if (pl->sclk > limits->sclk)
+			limits->sclk = pl->sclk;
+		if (pl->mclk > limits->mclk)
+			limits->mclk = pl->mclk;
+		if (pl->vddc > limits->vddc)
+			limits->vddc = pl->vddc;
+		if (pl->vddci > limits->vddci)
+			limits->vddci = pl->vddci;
 	}
 }
 
Signature · 1 line
2.53.0
#241 lore raw

Re: [PATCH AUTOSEL 6.18-5.10] drm/amd/pm/si: Fix updating clock limits from power states

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [High] Incomplete fix: the radeon driver still contains the identical bug, leaving laptops using that driver stuck on the lowest power level on battery. --

commit fcad112d0493cf1ee7c6a33503caa587b8452254
Author: Jeremy Klarenbeek <[email protected]> drm/amd/pm/si: Fix updating clock limits from power states

This commit fixes a bug where laptop GPUs were stuck on the lowest possible clock frequency and power level on battery by updating maximum clock limits for both AC and DC states in the amdgpu SI DPM code.

Quoted 4 lines
drivers/gpu/drm/amd/pm/legacy-dpm/si_dpm.c +0 -0
index 3a9522c17fee3..828bfb51e9174 100644

[ ... ]

Quoted 25 lines
drivers/gpu/drm/amd/pm/legacy-dpm/si_dpm.c +15 -5
@@ -7285,12 +7286,30 @@ static void si_parse_pplib_clock_info(struct amdgpu_device *adev,
 		si_pi->mvdd_bootup_value = mvdd;
 	}
 
+	/*
+	 * Update maximum allowed clock limits.
+	 * VBIOS can contain conflicting values between:
+	 * - the maximum allowed clocks and voltages on AC or DC
+	 * - the clocks and voltages in power states on AC or DC
+	 */
 	if ((rps->class & ATOM_PPLIB_CLASSIFICATION_UI_MASK) ==
-	    ATOM_PPLIB_CLASSIFICATION_UI_PERFORMANCE) {
-		adev->pm.dpm.dyn_state.max_clock_voltage_on_ac.sclk = pl->sclk;
-		adev->pm.dpm.dyn_state.max_clock_voltage_on_ac.mclk = pl->mclk;
-		adev->pm.dpm.dyn_state.max_clock_voltage_on_ac.vddc = pl->vddc;
-		adev->pm.dpm.dyn_state.max_clock_voltage_on_ac.vddci = pl->vddci;
+	    ATOM_PPLIB_CLASSIFICATION_UI_PERFORMANCE)
+		limits = &adev->pm.dpm.dyn_state.max_clock_voltage_on_ac;
+	else if ((rps->class & ATOM_PPLIB_CLASSIFICATION_UI_MASK) ==
+		 ATOM_PPLIB_CLASSIFICATION_UI_BATTERY)
+		limits = &adev->pm.dpm.dyn_state.max_clock_voltage_on_dc;
+	else
+		limits = NULL;
+
+	if (limits) {

drivers/gpu/drm/amd/pm/legacy-dpm/si_dpm.c static void si_parse_pplib_clock_info(struct amdgpu_device *adev, · line 7314

Quoted 10 lines
drivers/gpu/drm/amd/pm/legacy-dpm/si_dpm.c +8 -0
+		if (pl->sclk > limits->sclk)
+			limits->sclk = pl->sclk;
+		if (pl->mclk > limits->mclk)
+			limits->mclk = pl->mclk;
+		if (pl->vddc > limits->vddc)
+			limits->vddc = pl->vddc;
+		if (pl->vddci > limits->vddci)
+			limits->vddci = pl->vddci;
 	}
 }

[Severity: High]
This isn't a bug introduced by this patch, but does the radeon driver need this exact same fix?

Looking at drivers/gpu/drm/radeon/si_dpm.c in si_parse_pplib_clock_info() and drivers/gpu/drm/radeon/ni_dpm.c in ni_parse_pplib_clock_info(), they both still contain the older, unpatched logic that unconditionally overwrites AC limits and completely ignores DC/BATTERY limits:

        if ((rps->class & ATOM_PPLIB_CLASSIFICATION_UI_MASK) ==
            ATOM_PPLIB_CLASSIFICATION_UI_PERFORMANCE) {
                rdev->pm.dpm.dyn_state.max_clock_voltage_on_ac.sclk = pl->sclk;
                rdev->pm.dpm.dyn_state.max_clock_voltage_on_ac.mclk = pl->mclk;
                rdev->pm.dpm.dyn_state.max_clock_voltage_on_ac.vddc = pl->vddc;
                rdev->pm.dpm.dyn_state.max_clock_voltage_on_ac.vddci = pl->vddci;
        }

Since the radeon driver is often the default for SI (GCN 1.0) and earlier GPUs, affected laptops (like those with the FirePro W4170M or Radeon HD 8790M) might still get stuck on the lowest power level on battery when using that driver.

Would it make sense to port this fix back to the radeon driver as well?

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

PATCH 1/1 ceph: harden send_mds_reconnect and handle active-MDS peer reset

In reply to Sasha Levin

From: Alex Markuze <[email protected]>

[ Upstream commit 39fe3031589386ae7ce3fd7132beb6bb229e22ce ]

Change send_mds_reconnect() to return an error code so callers can detect and report reconnect failures instead of silently ignoring them. Add early bailout checks for sessions that are already closed, rejected, or unregistered, which avoids sending reconnect messages for sessions that can no longer be recovered.

The early -ESTALE and -ENOENT bailouts use a separate fail_return label that skips the pr_err_client diagnostic, since these codes indicate expected concurrent-teardown races rather than genuine reconnect build failures.

Move the "reconnect start" log after the early-bailout checks so it only appears for sessions that actually proceed with reconnect.

Save the prior session state before transitioning to RECONNECTING, and restore it in the failure path. Without this, a transient build or encoding failure (-ENOMEM, -ENOSPC) strands the session in RECONNECTING indefinitely because check_new_map() only retries sessions in RESTARTING state.

Rewrite mds_peer_reset() to handle the case where the MDS is past its RECONNECT phase (i.e. active). An active MDS rejects CLIENT_RECONNECT messages because it only accepts them during its own RECONNECT window after restart. Previously, the client would send a doomed reconnect that the MDS would reject or ignore. Now, the client tears the session down locally and lets new requests re-open a fresh session, which is the correct recovery for this scenario. The RECONNECTING state is handled on the same teardown path, since the MDS will reject reconnect attempts from an active client regardless of the session's local state.

Add explicit cases for CLOSED and REJECTED session states in mds_peer_reset() since these are terminal states where a connection drop is expected behavior.

The session teardown path in mds_peer_reset() follows the established drop-and-reacquire locking pattern from check_new_map(): take mdsc->mutex for session unregistration, release it, then take s->s_mutex separately for cleanup. This avoids introducing a new simultaneous lock nesting pattern.

Log reconnect failures from check_new_map() and mds_peer_reset() at pr_warn level rather than pr_err, since return codes like -ESTALE (closed/rejected session) and -ENOENT (unregistered session) are expected during concurrent teardown. Log dropped messages for unregistered sessions via doutc() (dynamic debug) rather than pr_info, as post-reset message arrival is routine and does not warrant unconditional logging.

---

LLM Generated explanations, may be completely bogus:

## Tree context

Local checkout: **v6.18.44** (6.18.44, git describe HEAD → v6.18.44-1-g2736c32da98b9). The commit is **not** in this tree yet; the pre-fix code is present.

---

## PHASE 1: COMMIT MESSAGE FORENSICS

**Step 1.1 — Subject**
- Record: [ceph] [harden/handle] — harden send_mds_reconnect() and fix mds_peer_reset() when the MDS is past its RECONNECT phase.

**Step 1.2 — Tags**
- Record:
- Signed-off-by: Alex Markuze, Viacheslav Dubeyko (×2), Ilya Dryomov
- Reviewed-by: Viacheslav Dubeyko
- No Fixes:, Reported-by:, Link:, Cc: stable, Tested-by:
- Notable: maintainer review (Dryomov) and merge SOB from Ilya Dryomov (ceph maintainer)

**Step 1.3 — Body**
- Record:
- **Bug 1**: Transient reconnect build failures (-ENOMEM, -ENOSPC) leave session stuck in RECONNECTING; check_new_map() only retries RESTARTING.
- **Bug 2**: mds_peer_reset() sends reconnect when MDS state is >= RECONNECT, including ACTIVE; active MDS rejects CLIENT_RECONNECT → client stuck.
- **Symptom**: Stalled CephFS sessions / failed recovery after MDS restart or session reset.
- **Fix**: Return errors from send_mds_reconnect(), restore prior state on failure, only reconnect when MDS is exactly in RECONNECT, otherwise tear down session locally.
- Part of **v4 03/11** series (manual-reset work), but this hunk is confined to existing reconnect logic.

**Step 1.4 — Hidden bug fix?**
- Record: **Yes** — despite “harden”, this fixes real correctness bugs (stuck session state machine, doomed reconnect to active MDS), not cosmetic cleanup.

---

## PHASE 2: DIFF ANALYSIS

**Step 2.1 — Inventory**
- Record:
- fs/ceph/mds_client.c: +163 / −15 (~178 lines touched)
- Functions: handle_session(), reconnect_caps_cb() (comment only),

    `send_mds_reconnect()`, `check_new_map()`, `mds_peer_reset()`,
    `mds_dispatch()`

- Scope: single-file, surgical changes around MDS session reconnect/recovery

**Step 2.2 — Code flow (per hunk)**
- Record:
1. **CEPH_SESSION_REJECT**: Allow RECONNECTING in addition to OPENING; distinct log for reconnect rejection.
2. **send_mds_reconnect()**: void → int; early bailouts for CLOSED/REJECTED (-ESTALE) and unregistered session (-ENOENT); save/restore old_state on build failure; move xa_destroy() under s_mutex.
3. **check_new_map()**: Check return code; log failures at

     `pr_warn`.

4. **mds_peer_reset()**: Reconnect only if MDS state == CEPH_MDS_STATE_RECONNECT; otherwise tear down session using the same pattern as check_new_map() forced-close.
5. **mds_dispatch()**: doutc() when dropping messages for unregistered sessions.

**Step 2.3 — Bug mechanism**
- Record:
- **Logic / state-machine bug**: Failure path sets RECONNECTING but never restores prior state; retry path requires RESTARTING.
- **Logic / protocol bug**: >= RECONNECT includes ACTIVE; reconnect is only valid during MDS RECONNECT window.
- **Synchronization**: xa_destroy(&s_delegated_inos) moved under s_mutex to serialize with ceph_get_deleg_ino().
- Category: logic correctness + minor synchronization hardening.

**Step 2.4 — Fix quality**
- Record:
- Fix mirrors existing teardown pattern in check_new_map() (lines

    5086–5102 in current tree).
  - Minimal API change (`send_mds_reconnect` return value) internal to
    `mds_client.c`.
  - Low regression risk; uses established lock ordering (`mdsc->mutex`
    then `s->s_mutex` separately).

- Reviewed by subsystem developer; merged by maintainer.

---

## PHASE 3: GIT HISTORY INVESTIGATION

**Step 3.1 — Blame**
- Record:
- send_mds_reconnect() fail path dates to Sage Weil 2009–2010; no state restoration ever added.
- session->s_state = RECONNECTING at line 4903; fail at 5034–5037 unlocks mutex without restoring state.
- Bug present since original MDS client reconnect code (~2.6.34 era).

**Step 3.2 — Fixes: tag**
- Record: N/A (no Fixes: tag).

**Step 3.3 — Related file history**
- Record:
- cbcb358b744bf (Jan 2024, in tree): added >= CEPH_MDS_STATE_RECONNECT guard to mds_peer_reset() — fixed premature reconnect to not-ready MDS, but **widened** the window to include ACTIVE states (the bug this commit fixes).
- 7e70f0ed9f3ee (2010, in tree): introduced reconnect-on-peer-reset behavior.
- Patch is **03/11** in a series; patches 01–02 (inode bitops/endian) and 05+ (manual reset) are separate. Patch 03 only adds a comment in reconnect_caps_cb() and does not depend on 01/02 code changes.

**Step 3.4 — Author context**
- Record: Alex Markuze is an active ceph contributor (recent fixes in this tree: race conditions, error handling). Ilya Dryomov is ceph maintainer.

**Step 3.5 — Dependencies**
- Record: **Standalone for this tree**. Core fixes need only existing mds_client.c APIs (__unregister_session, cleanup_session_requests, remove_session_caps, kick_requests). Manual-reset machinery (patch 05) is **not** in v6.18.44 and is **not** required.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

**Step 4.1 — Discussion**
- Record:
- Lore URL:

    https://lkml.iu.edu/hypermail/linux/kernel/2605.0/09721.html
  - Series: v4, patch 03/11 (v3 also submitted Apr 29 2026)
  - Review reply: https://lists.openwall.net/linux-
    kernel/2026/05/07/1855 — Viacheslav Dubeyko `Reviewed-by`, no NAKs

- No explicit Cc: stable nomination found in thread

**Step 4.2 — Reviewers**
- Record: CC'd to ceph-devel@, linux-kernel@, idryomov@, vdubeyko@. Reviewed-by from Dubeyko; merged SOB from Dryomov.

**Step 4.3 — Bug reports**
- Record: No syzbot/bugzilla. Related prior fix cbcb358 references
https://tracker.ceph.com/issues/62489 for a different reconnect-timing bug. This commit addresses a distinct active-MDS / stuck-state problem.

**Step 4.4 — Series context**
- Record: 11-patch series adds manual client reset + diagnostics + selftests. **This patch fixes pre-existing reconnect bugs independent of the reset feature** (reset feature not in 6.18.y).

**Step 4.5 — Stable list**
- Record: No stable-list discussion found (lore blocked for automated search; checked via lkml hypermail and openwall).

---

## PHASE 5: CODE SEMANTIC ANALYSIS

**Step 5.1 — Key functions**
- Record: send_mds_reconnect, check_new_map, mds_peer_reset, handle_session, mds_dispatch

**Step 5.2 — Callers**
- Record:
- send_mds_reconnect() ← check_new_map() (MDS map updates), export-target reconnect loop, mds_peer_reset()
- mds_peer_reset() ← mds_con_ops.peer_reset (connection reset from MDS)
- Triggered during MDS failover, restart, session timeout — production CephFS paths

**Step 5.3 — Callees**
- Record: __unregister_session, cleanup_session_requests, remove_session_caps, kick_requests, ceph_con_send, cap reconnect encoding

**Step 5.4 — Reachability**
- Record: Reachable from normal CephFS operation during MDS recovery/failover. Any CephFS mount with MDS restarts or session closes can hit mds_peer_reset().

**Step 5.5 — Similar patterns**
- Record: Session teardown in mds_peer_reset() explicitly modeled on check_new_map() forced-close at lines 5086–5102 — same proven pattern already in tree.

---

## PHASE 6: CROSS-REFERENCE WITH LOCAL TREE (6.18.44)

**Step 6.1 — Buggy code present?**
- Record: **Yes.** Current tree has:
- static void send_mds_reconnect() with no state restore on failure

    (lines 4878–5043)
  - `check_new_map()` only retries `CEPH_MDS_SESSION_RESTARTING` (line
    5122)
  - `mds_peer_reset()` calls reconnect when `>=
    CEPH_MDS_STATE_RECONNECT` (lines 6273–6275)

**Step 6.2 — Backport complications**
- Record: Should apply cleanly with minor line-offset adjustment. No reset state machine or other series prerequisites in this tree. ceph_get_deleg_ino() and s_delegated_inos already exist.

**Step 6.3 — Related fixes already present?**
- Record: cbcb358b744bf ("skip reconnecting if MDS is not ready") is in tree but does not fix the active-MDS or stuck-RECONNECTING bugs. No duplicate fix found.

---

## PHASE 7: SUBSYSTEM CONTEXT

**Step 7.1 — Subsystem**
- Record: fs/ceph — CephFS client (IMPORTANT; not core kernel, but critical for CephFS deployments)

**Step 7.2 — Activity**
- Record: Actively maintained; multiple stable-worthy ceph fixes already in 6.18.y history.

---

## PHASE 8: IMPACT AND RISK

**Step 8.1 — Who is affected**
- Record: CephFS users (CONFIG_CEPH_FS), especially clusters with MDS failover, restarts, or session timeouts.

**Step 8.2 — Trigger conditions**
- Record:
- MDS closes client session while MDS is ACTIVE (past RECONNECT window) — common after slow client or missed reconnect window
- Transient -ENOMEM/-ENOSPC during reconnect message build — rare but possible under memory pressure
- Unprivileged users cannot directly trigger; cluster/MDS events trigger it

**Step 8.3 — Failure mode severity**
- Record: **HIGH to CRITICAL** — stuck RECONNECTING session → hung metadata ops, stalled I/O, mount may require remount. Not data- corruption-on-disk by itself, but production outage for CephFS workloads.

**Step 8.4 — Risk/benefit**
- Record:
- Benefit: **High** for CephFS recovery correctness
- Risk: **Low** — one file, follows existing teardown pattern, reviewed
- Ratio: strongly favors backport

---

## PHASE 9: FINAL SYNTHESIS

**Evidence FOR backport**
- Fixes two verified logic bugs in long-standing reconnect code
- Can hang CephFS during MDS recovery (real production impact)
- Reviewed by subsystem developer; merged by maintainer
- Self-contained in mds_client.c; no new userspace API
- Buggy code confirmed present in v6.18.44
- Does not require the rest of the 11-patch reset series

**Evidence AGAINST**
- Part of a larger feature series (could cause hesitation), but this hunk is independent
- ~163 lines (larger than typical one-liner, still single-file)
- No syzbot/fuzzer report (harder to reproduce; cluster-timing dependent)

**Stable rules checklist**
1. Obviously correct and tested? **PASS** — reviewed, logic verified against existing patterns; selftest in series but not required for fix correctness
2. Fixes real bug? **PASS**
3. Important issue? **PASS** — session hang / I/O stall during recovery
4. Small and contained? **PASS** — one file, focused reconnect/recovery changes
5. No new features/APIs? **PASS** — bug fixes to existing reconnect path
6. Applies to local tree? **PASS** — all target code exists in 6.18.44

**Exception category**: N/A (not device ID, quirk, DT, docs, or build fix)

---

## Problem summary for stable users

CephFS clients can get **permanently stuck** in two recovery scenarios present in 6.18.y:

1. **Reconnect build failure**: send_mds_reconnect() moves the session to RECONNECTING but on -ENOMEM/-ENOSPC failure never restores the prior state. check_new_map() only retries RESTARTING sessions, so recovery never retries.

2. **Active MDS peer reset**: When the MDS closes a session after it has gone ACTIVE, mds_peer_reset() still attempts reconnect (>= CEPH_MDS_STATE_RECONNECT matches ACTIVE). The MDS rejects this; the client does not tear down and re-open cleanly, leaving the mount wedged until remount.

The fix restores state on failure, reconnects only during the MDS RECONNECT window, and otherwise performs local session teardown so new requests can establish fresh sessions — the correct recovery path.

---

## Verification

- [Phase 1] Parsed subject, body, all SOB/Reviewed-by tags; no Fixes/Reported-by/Link
- [Phase 2] Read full diff; confirmed 1 file, 6 functions touched; classified as state-machine + protocol bugs
- [Phase 3] git blame on fail path: Sage Weil 2009–2010, no state restore ever
- [Phase 3] git log -S: 7e70f0ed9f3ee introduced peer-reset reconnect (in tree); cbcb358b744bf added >= RECONNECT guard (in tree)
- [Phase 3] git merge-base --is-ancestor: both 7e70f0 and cbcb358 confirmed in HEAD
- [Phase 3] Series 01/02/05 reviewed via lkml; patch 03 is independent of reset state machine
- [Phase 4] Fetched
https://lkml.iu.edu/hypermail/linux/kernel/2605.0/09721.html — full patch text
- [Phase 4] Fetched https://lists.openwall.net/linux-
kernel/2026/05/07/1855 — Reviewed-by Dubeyko, no objections
- [Phase 4] b4 dig unavailable for commit (not in tree); used lkml message-ID search instead
- [Phase 5] Verified callers: send_mds_reconnect at lines 5126, 5190, 6275; mds_peer_reset via mds_con_ops.peer_reset at line 6504
- [Phase 5] Verified teardown pattern matches check_new_map() lines 5086–5102
- [Phase 6] git describe HEAD → v6.18.44; buggy void send_mds_reconnect and >= RECONNECT guard confirmed at lines 4878, 6273–6275
- [Phase 6] No reset/trigger debugfs or reset state machine in tree — series patch 05 not present
- [Phase 6] ceph_get_deleg_ino and s_delegated_inos exist (lines 613–628, 4900)
- [Phase 8] Failure mode: stuck RECONNECTING / failed recovery → CephFS hang; severity HIGH

**YES**The background history lookups finished and match the earlier analysis.

**Reconnect logic history** (619755): send_mds_reconnect goes back to the original MDS client (2f2dc053404fe, 2009). Later related fixes in this tree include the NPD fix (c0bd50e2eeddf) and the deadlock fix around mdsc->mutex/s->s_mutex nesting (ea8412b284c09).

**Author context** (619756): Alex Markuze has recent ceph commits in this 6.18.y tree (race fixes in r_parent handling, read error-path hardening), which fits this being a targeted reconnect/recovery fix rather than new subsystem work.

That supports the **YES** backport verdict: the bugs sit in long- standing reconnect code, the author is an active ceph contributor, and the patch is standalone in mds_client.c without needing the manual- reset series.

 fs/ceph/mds_client.c | 178 +++++++++++++++++++++++++++++++++++++++----
 1 file changed, 163 insertions(+), 15 deletions(-)
fs/ceph/mds_client.c +163 -15
index af7137661c8fc..48d622cd8b1e2 100644
@@ -4401,9 +4401,14 @@ static void handle_session(struct ceph_mds_session *session,
 		break;
 
 	case CEPH_SESSION_REJECT:
-		WARN_ON(session->s_state != CEPH_MDS_SESSION_OPENING);
-		pr_info_client(cl, "mds%d rejected session\n",
-			       session->s_mds);
+		WARN_ON(session->s_state != CEPH_MDS_SESSION_OPENING &&
+			session->s_state != CEPH_MDS_SESSION_RECONNECTING);
+		if (session->s_state == CEPH_MDS_SESSION_RECONNECTING)
+			pr_info_client(cl, "mds%d reconnect rejected\n",
+				       session->s_mds);
+		else
+			pr_info_client(cl, "mds%d rejected session\n",
+				       session->s_mds);
 		session->s_state = CEPH_MDS_SESSION_REJECTED;
 		cleanup_session_requests(mdsc, session);
 		remove_session_caps(session);
@@ -4663,6 +4668,14 @@ static int reconnect_caps_cb(struct inode *inode, int mds, void *arg)
 	cap->mseq = 0;       /* and migrate_seq */
 	cap->cap_gen = atomic_read(&cap->session->s_cap_gen);
 
+	/*
+	 * Note: CEPH_I_ERROR_FILELOCK is not set during reconnect.
+	 * Instead, locks are submitted for best-effort MDS reclaim
+	 * via the flock_len field below.  If reclaim fails (e.g.,
+	 * another client grabbed a conflicting lock), future lock
+	 * operations will fail and set the error flag at that point.
+	 */
+
 	/* These are lost when the session goes away */
 	if (S_ISDIR(inode->i_mode)) {
 		if (cap->issued & CEPH_CAP_DIR_CREATE) {
@@ -4876,20 +4889,19 @@ static int encode_snap_realms(struct ceph_mds_client *mdsc,
  *
  * This is a relatively heavyweight operation, but it's rare.
  */
-static void send_mds_reconnect(struct ceph_mds_client *mdsc,
-			       struct ceph_mds_session *session)
+static int send_mds_reconnect(struct ceph_mds_client *mdsc,
+			      struct ceph_mds_session *session)
 {
 	struct ceph_client *cl = mdsc->fsc->client;
 	struct ceph_msg *reply;
 	int mds = session->s_mds;
 	int err = -ENOMEM;
+	int old_state;
 	struct ceph_reconnect_state recon_state = {
 		.session = session,
 	};
 	LIST_HEAD(dispose);
 
-	pr_info_client(cl, "mds%d reconnect start\n", mds);
-
 	recon_state.pagelist = ceph_pagelist_alloc(GFP_NOFS);
 	if (!recon_state.pagelist)
 		goto fail_nopagelist;
@@ -4898,9 +4910,37 @@ static void send_mds_reconnect(struct ceph_mds_client *mdsc,
 	if (!reply)
 		goto fail_nomsg;
 
+	mutex_lock(&session->s_mutex);
+
+	/* Serialized by s_mutex against concurrent ceph_get_deleg_ino(). */
 	xa_destroy(&session->s_delegated_inos);
+	if (session->s_state == CEPH_MDS_SESSION_CLOSED ||
+	    session->s_state == CEPH_MDS_SESSION_REJECTED) {
+		pr_info_client(cl, "mds%d skipping reconnect, session %s\n",
+			       mds,
+			       ceph_session_state_name(session->s_state));
+		mutex_unlock(&session->s_mutex);
+		ceph_msg_put(reply);
+		err = -ESTALE;
+		goto fail_return;
+	}
 
-	mutex_lock(&session->s_mutex);
+	/* s_mutex -> mdsc->mutex matches cleanup_session_requests() order. */
+	mutex_lock(&mdsc->mutex);
+	if (mds >= mdsc->max_sessions || mdsc->sessions[mds] != session) {
+		mutex_unlock(&mdsc->mutex);
+		pr_info_client(cl,
+			       "mds%d skipping reconnect, session unregistered\n",
+			       mds);
+		mutex_unlock(&session->s_mutex);
+		ceph_msg_put(reply);
+		err = -ENOENT;
+		goto fail_return;
+	}
+	mutex_unlock(&mdsc->mutex);
+
+	pr_info_client(cl, "mds%d reconnect start\n", mds);
+	old_state = session->s_state;
 	session->s_state = CEPH_MDS_SESSION_RECONNECTING;
 	session->s_seq = 0;
 
@@ -5030,18 +5070,34 @@ static void send_mds_reconnect(struct ceph_mds_client *mdsc,
 
 	up_read(&mdsc->snap_rwsem);
 	ceph_pagelist_release(recon_state.pagelist);
-	return;
+	return 0;
 
 fail:
 	ceph_msg_put(reply);
 	up_read(&mdsc->snap_rwsem);
+	/*
+	 * Restore prior session state so map-driven reconnect logic
+	 * (check_new_map) can retry.  Without this, a transient build
+	 * failure strands the session in RECONNECTING indefinitely.
+	 */
+	session->s_state = old_state;
 	mutex_unlock(&session->s_mutex);
 fail_nomsg:
 	ceph_pagelist_release(recon_state.pagelist);
 fail_nopagelist:
 	pr_err_client(cl, "error %d preparing reconnect for mds%d\n",
 		      err, mds);
-	return;
+	return err;
+
+fail_return:
+	/*
+	 * Early-exit path for expected concurrent-teardown races
+	 * (-ESTALE for closed/rejected sessions, -ENOENT for
+	 * unregistered sessions).  Skip the pr_err_client diagnostic
+	 * since these are not genuine reconnect build failures.
+	 */
+	ceph_pagelist_release(recon_state.pagelist);
+	return err;
 }
 
 
@@ -5122,9 +5178,15 @@ static void check_new_map(struct ceph_mds_client *mdsc,
 		 */
 		if (s->s_state == CEPH_MDS_SESSION_RESTARTING &&
 		    newstate >= CEPH_MDS_STATE_RECONNECT) {
+			int rc;
+
 			mutex_unlock(&mdsc->mutex);
 			clear_bit(i, targets);
-			send_mds_reconnect(mdsc, s);
+			rc = send_mds_reconnect(mdsc, s);
+			if (rc)
+				pr_warn_client(cl,
+					       "mds%d reconnect failed: %d\n",
+					       i, rc);
 			mutex_lock(&mdsc->mutex);
 		}
 
@@ -5188,7 +5250,11 @@ static void check_new_map(struct ceph_mds_client *mdsc,
 		}
 		doutc(cl, "send reconnect to export target mds.%d\n", i);
 		mutex_unlock(&mdsc->mutex);
-		send_mds_reconnect(mdsc, s);
+		err = send_mds_reconnect(mdsc, s);
+		if (err)
+			pr_warn_client(cl,
+				       "mds%d export target reconnect failed: %d\n",
+				       i, err);
 		ceph_put_mds_session(s);
 		mutex_lock(&mdsc->mutex);
 	}
@@ -6268,12 +6334,92 @@ static void mds_peer_reset(struct ceph_connection *con)
 {
 	struct ceph_mds_session *s = con->private;
 	struct ceph_mds_client *mdsc = s->s_mdsc;
+	int session_state;
 
 	pr_warn_client(mdsc->fsc->client, "mds%d closed our session\n",
 		       s->s_mds);
-	if (READ_ONCE(mdsc->fsc->mount_state) != CEPH_MOUNT_FENCE_IO &&
-	    ceph_mdsmap_get_state(mdsc->mdsmap, s->s_mds) >= CEPH_MDS_STATE_RECONNECT)
-		send_mds_reconnect(mdsc, s);
+
+	if (READ_ONCE(mdsc->fsc->mount_state) == CEPH_MOUNT_FENCE_IO ||
+	    ceph_mdsmap_get_state(mdsc->mdsmap, s->s_mds) < CEPH_MDS_STATE_RECONNECT)
+		return;
+
+	/*
+	 * Only reconnect if MDS is in its RECONNECT phase.  An MDS past
+	 * RECONNECT (REJOIN, CLIENTREPLAY, ACTIVE) will reject reconnect
+	 * attempts, so those states fall through to session teardown below.
+	 */
+	if (ceph_mdsmap_get_state(mdsc->mdsmap, s->s_mds) == CEPH_MDS_STATE_RECONNECT) {
+		int rc = send_mds_reconnect(mdsc, s);
+
+		if (rc)
+			pr_warn_client(mdsc->fsc->client,
+				       "mds%d reconnect failed: %d\n",
+				       s->s_mds, rc);
+		return;
+	}
+
+	/*
+	 * MDS is active (past RECONNECT).  It will not accept a
+	 * CLIENT_RECONNECT from us, so tear the session down locally
+	 * and let new requests re-open a fresh session.
+	 *
+	 * Snapshot session state with READ_ONCE, then revalidate under
+	 * mdsc->mutex before acting.  The subsequent mdsc->mutex
+	 * section rechecks s_state to catch concurrent transitions, so
+	 * the lockless snapshot here is safe.  s->s_mutex is taken
+	 * separately for cleanup after unregistration, which avoids
+	 * introducing a new s->s_mutex + mdsc->mutex nesting.
+	 */
+	session_state = READ_ONCE(s->s_state);
+
+	switch (session_state) {
+	case CEPH_MDS_SESSION_RESTARTING:
+	case CEPH_MDS_SESSION_RECONNECTING:
+	case CEPH_MDS_SESSION_CLOSING:
+	case CEPH_MDS_SESSION_OPEN:
+	case CEPH_MDS_SESSION_HUNG:
+	case CEPH_MDS_SESSION_OPENING:
+		mutex_lock(&mdsc->mutex);
+		if (s->s_mds >= mdsc->max_sessions ||
+		    mdsc->sessions[s->s_mds] != s ||
+		    s->s_state != session_state) {
+			pr_info_client(mdsc->fsc->client,
+				       "mds%d state changed to %s during peer reset\n",
+				       s->s_mds,
+				       ceph_session_state_name(s->s_state));
+			mutex_unlock(&mdsc->mutex);
+			return;
+		}
+
+		ceph_get_mds_session(s);
+		s->s_state = CEPH_MDS_SESSION_CLOSED;
+		__unregister_session(mdsc, s);
+		__wake_requests(mdsc, &s->s_waiting);
+		mutex_unlock(&mdsc->mutex);
+
+		mutex_lock(&s->s_mutex);
+		cleanup_session_requests(mdsc, s);
+		remove_session_caps(s);
+		mutex_unlock(&s->s_mutex);
+
+		wake_up_all(&mdsc->session_close_wq);
+
+		mutex_lock(&mdsc->mutex);
+		kick_requests(mdsc, s->s_mds);
+		mutex_unlock(&mdsc->mutex);
+
+		ceph_put_mds_session(s);
+		break;
+	case CEPH_MDS_SESSION_CLOSED:
+	case CEPH_MDS_SESSION_REJECTED:
+		break;
+	default:
+		pr_warn_client(mdsc->fsc->client,
+			       "mds%d peer reset in unexpected state %s\n",
+			       s->s_mds,
+			       ceph_session_state_name(session_state));
+		break;
+	}
 }
 
 static void mds_dispatch(struct ceph_connection *con, struct ceph_msg *msg)
@@ -6285,6 +6431,8 @@ static void mds_dispatch(struct ceph_connection *con, struct ceph_msg *msg)
 
 	mutex_lock(&mdsc->mutex);
 	if (__verify_registered_session(mdsc, s) < 0) {
+		doutc(cl, "dropping tid %llu from unregistered session %d\n",
+		      le64_to_cpu(msg->hdr.tid), s->s_mds);
 		mutex_unlock(&mdsc->mutex);
 		goto out;
 	}
Signature · 1 line
2.53.0
author maintainer
#243 lore raw

PATCH 1/1 Bluetooth: L2CAP: validate connectionless PSM length

In reply to Sasha Levin

From: Samuel Moelius <[email protected]>

[ Upstream commit a40a5f922546b3bd7c094d882b29177db4f2abe0 ]

Connectionless L2CAP frames carry a two-byte PSM at the start of the payload. l2cap_recv_frame() currently reads that PSM unconditionally after validating only the outer L2CAP length.

A malformed connectionless frame with a zero- or one-byte payload can therefore make the parser read beyond the advertised skb payload and use tailroom bytes as part of the PSM. A VHCI-backed QEMU reproducer injected a one-byte connectionless payload and reached the unchecked read.

Reject connectionless frames that cannot contain the PSM before reading or pulling it. This preserves all valid connectionless frames while dropping only structurally incomplete packets.

Assisted-by Codex:gpt-5.5-cyber-preview

---

LLM Generated explanations, may be completely bogus:

The background git searches finished: neither git log --grep="validate connectionless PSM" nor --grep="connectionless PSM length" found anything on HEAD, which matches the earlier finding that a40a5f922546 is not in the 6.18.44 tree even though the buggy code is still there.

**Verdict for this tree (6.18.44): YES** — backport the 5-line PSM length check. It fixes a remote-triggerable out-of-bounds read in connectionless L2CAP handling, applies cleanly, and follows the same pattern as other L2CAP validation fixes already in this branch.

 net/bluetooth/l2cap_core.c | 5 +++++
 1 file changed, 5 insertions(+)
net/bluetooth/l2cap_core.c +5 -0
index 6133c65b20172..1a38a667ef0b0 100644
@@ -7117,6 +7117,11 @@ static void l2cap_recv_frame(struct l2cap_conn *conn, struct sk_buff *skb)
 		break;
 
 	case L2CAP_CID_CONN_LESS:
+		if (skb->len < L2CAP_PSMLEN_SIZE) {
+			kfree_skb(skb);
+			break;
+		}
+
 		psm = get_unaligned((__le16 *) skb->data);
 		skb_pull(skb, L2CAP_PSMLEN_SIZE);
 		l2cap_conless_channel(conn, psm, skb);
Signature · 1 line
2.53.0
author maintainer
#244 lore raw

PATCH 1/1 btrfs: validate properties before setting them

In reply to Sasha Levin

From: Filipe Manana <[email protected]>

[ Upstream commit cf1afec09e9f004a62c54c471863209ed249fca7 ]

We set the xattr and then attempt to apply the property. If the apply fails we then attempt to delete the xattr to avoid an inconsistency. However we don't verify if the deletion succeed, so if it fails we leave an inconsistency between the state in the btree and the in-memory inode.

Address this by validating first if we can apply the property, then set the xattr, then apply the property, and this last step should not fail since the validation succeeded before - assert that it does not fail but leave code to attempt to delete the xattr if it happens, and then abort the transaction only if the xattr delete failed.

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: btrfs: validate properties before setting them

**Local tree:** v6.18.44 (6.18.44) — checked-out stable tree, not mainline.

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: PARSE THE SUBJECT LINE
**Record:** [btrfs] [validate] validate properties before setting them — btrfs filesystem property handling; action is validation/reordering of set path to prevent inconsistency.

### Step 1.2: PARSE ALL COMMIT MESSAGE TAGS
**Record:**
- **Reviewed-by:** Qu Wenruo <[email protected]>
- **Reviewed-by:** David Sterba <[email protected]> (btrfs maintainer)
- **Signed-off-by:** Filipe Manana <[email protected]> (author)
- **Signed-off-by:** David Sterba <[email protected]>
- **No** Fixes: tag
- **No** Reported-by: tag
- **No** Cc: [email protected]
- **No** syzbot / sanitizer links

Notable: dual maintainer review (Qu Wenruo + David Sterba); no user/fuzzer report.

### Step 1.3: ANALYZE THE COMMIT BODY TEXT
**Record:**
- **Bug:** btrfs_set_prop() writes the xattr to the btree first, then calls handler->apply(). On apply failure it attempts to delete the xattr, but ignores whether deletion succeeded.
- **Symptom:** If rollback deletion fails, the on-disk btree has the xattr while the in-memory inode state was not updated by apply() — metadata inconsistency.
- **Fix approach:** Validate first (handler->validate()), then set xattr, then apply (should not fail after validation). On unexpected apply failure, try xattr delete; if delete also fails, call btrfs_abort_transaction().
- **Version info:** None stated in message.

### Step 1.4: DETECT HIDDEN BUG FIXES
**Record:** Not disguised — this is an explicit correctness/consistency bug fix in error handling, though it also restores validate-before- setxattr ordering that existed in the original 2014 property code.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: INVENTORY THE CHANGES
**Record:**
- **Files:** fs/btrfs/props.c only (+13 / −3 lines)
- **Function modified:** btrfs_set_prop()
- **Scope:** Single-file, surgical fix in one function's non-zero-value path.

### Step 2.2: UNDERSTAND THE CODE FLOW CHANGE

**Hunk 1 (validate before xattr):**
- **Before:** Set xattr → apply → on failure, attempt xattr delete (ignore result).
- **After:** Validate → set xattr → apply → on failure, attempt delete and abort transaction if delete fails.

**Record:** Normal property-set path for value_len > 0; error path improved. The value_len == 0 (property removal) path is unchanged.

### Step 2.3: IDENTIFY THE BUG MECHANISM
**Record:**
- **Category:** Logic/correctness fix + error-path resource/state consistency fix.
- **Mechanism:** Incomplete rollback on apply failure leaves btree xattr present while in-memory inode property state is stale. Fix validates early (reducing apply failures), and escalates to btrfs_abort_transaction() when rollback cannot complete.

### Step 2.4: ASSESS THE FIX QUALITY
**Record:**
- Fix is minimal and obviously correct.
- Restores validate-before-setxattr ordering that existed in the original 2014 __btrfs_set_prop() before validation was moved external in 2019 (f22125e5d8ae1).
- ASSERT(ret == 0) matches existing pattern in the value_len == 0 branch.
- btrfs_abort_transaction() on failed cleanup is consistent with xattr.c and ioctl.c error handling.
- **Regression risk:** Very low. Duplicate validation on the xattr path is harmless. Abort-on-failed-rollback is conservative but appropriate for metadata inconsistency.

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: BLAME THE CHANGED LINES
**Record:**
- Core btrfs_set_prop() logic dates to **2014** (63541927c8d11d — Filipe Manana, "Btrfs: add support for inode properties").
- Original 2014 code **did** call handler->validate() before setxattr.
- The rollback-without-checking-delete pattern has existed since 2014.
- Validation was **removed** from inside btrfs_set_prop() in **2019** (f22125e5d8ae1 — "refactor btrfs_set_props to validate externally").
- Recent props.c changes (2022–2025) are struct/type refactors, not related to this bug.

### Step 3.2: FOLLOW THE FIXES: TAG
**Record:** No Fixes: tag present — N/A.

### Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES **Record:**
- Related historical fix: 3763771cf6023 (2019) — different issue (fsync/log persistence of compression xattr deletion).
- Patch is **1/3** of series "[PATCH 0/3] btrfs: fixes and cleanups setting/clearing properties".
- Patches 2/3 and 3/3 touch ioctl.c (btrfs_fileattr_set()), not props.c — **this patch is standalone**.
- Commit is **not yet present** in this tree (git log --grep found nothing).

### Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS
**Record:** Filipe Manana is an active btrfs developer with multiple btrfs fixes in history. David Sterba is btrfs maintainer and signed off.

### Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS **Record:**
- handler->validate callback exists in prop_handler struct in this tree.
- prop_compression_validate() exists and is wired up.
- btrfs_abort_transaction() is available via existing includes.
- **No prerequisites** — patch applies cleanly (git apply --check succeeded).
- Patches 2/3 and 3/3 are independent ioctl cleanups.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION **Record:**
- **URL:** https://www.spinics.net/lists/linux-btrfs/msg166052.html
- **Series cover:** https://www.spinics.net/lists/linux-
btrfs/msg166051.html
- **Date:** Mon, 8 Jun 2026
- **Series:** v1, 3 patches; patch 1 is this commit.
- b4 dig could not be used (commit not in local tree).
- No explicit stable nomination found in fetched thread snippets.

### Step 4.2: CHECK WHO REVIEWED THE PATCH
**Record:** Author Filipe Manana; Reviewed-by Qu Wenruo and David Sterba (maintainer). Appropriate reviewers for btrfs properties code.

### Step 4.3: SEARCH FOR THE BUG REPORT
**Record:** No Reported-by: or Link: tags. Bug identified by code analysis, not a user crash report or syzbot hit.

### Step 4.4: CHECK FOR RELATED PATCHES AND SERIES **Record:**
- Patch 2/3: btrfs: don't over reserve metadata space for property in btrfs_fileattr_set() — ioctl.c only.
- Patch 3/3: btrfs: fix transaction abort logic in btrfs_fileattr_set() — ioctl.c only.
- This patch is self-contained for the btrfs_set_prop() inconsistency.

### Step 4.5: CHECK STABLE MAILING LIST HISTORY **Record:** lore.kernel.org blocked by bot protection; no stable-list discussion verified. Not a negative signal per instructions.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: IDENTIFY KEY FUNCTIONS IN THE DIFF **Record:** btrfs_set_prop() — only function modified.

### Step 5.2: TRACE CALLERS
**Record:**
1. **btrfs_xattr_handler_set_prop()** (xattr.c:451) — userspace setfattr / setxattr on btrfs.compression. Already calls btrfs_validate_prop() first (line 440). Reachable from userspace.
2. **btrfs_fileattr_set()** (ioctl.c:377,384) — FS_IOC_SETFLAGS / file attributes ioctl path. Calls btrfs_set_prop() **without** prior btrfs_validate_prop(), but passes known-good strings from btrfs_compress_type2str(). Reachable from userspace.

### Step 5.3: TRACE CALLEES
**Record:** handler->validate(), btrfs_setxattr(), handler->apply(), btrfs_abort_transaction(), set_bit(BTRFS_INODE_HAS_PROPS).

### Step 5.4: FOLLOW THE CALL CHAIN
**Record:** Userspace sets btrfs inode properties via xattr or ioctl → transaction started → btrfs_set_prop() → btree xattr + in-memory inode flags. Buggy path is reachable from unprivileged userspace (with write access to the file/inode).

### Step 5.5: SEARCH FOR SIMILAR PATTERNS
**Record:** btrfs_inode_inherit_props() (props.c:440–446) has the same unchecked-rollback pattern (apply fails → btrfs_setxattr delete without checking result). **Not fixed by this commit.** Separate issue; does 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.** Current fs/btrfs/props.c lines 130–138 show setxattr → apply → unchecked rollback delete. Bug present since property support was added; validate-before-setxattr was removed in 2019 refactor still present in 6.18.44.

### Step 6.2: CHECK FOR BACKPORT COMPLICATIONS **Record:** **Clean apply** — git apply --check passed with no conflicts. No structural divergence from patch context.

### Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE **Record:** No equivalent fix found (git log --grep for subject returned empty). Bug remains unfixed in v6.18.44.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

### Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY **Record:** **Filesystem — btrfs** (fs/btrfs/). **Criticality:
IMPORTANT** — btrfs metadata consistency affects data integrity for all btrfs users.

### Step 7.2: ASSESS SUBSYSTEM ACTIVITY
**Record:** props.c actively maintained (refactors in 2022–2025). Property code is mature but still receiving correctness fixes.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: DETERMINE WHO IS AFFECTED
**Record:** Users setting btrfs inode properties (compression xattr via setfattr/setxattr, or compression flags via ioctl). **CONFIG_BTRFS** users.

### Step 8.2: DETERMINE THE TRIGGER CONDITIONS
**Record:**
1. handler->apply() fails after xattr was written (more likely on ioctl path without internal validate; rare on xattr path where external validate already ran).
2. Rollback btrfs_setxattr(..., NULL, 0) also fails (e.g., metadata ENOSPC, transaction error).
- **Likelihood:** Low but realistic on error paths (space pressure, I/O errors).
- **Userspace triggerable:** Yes, with write permission on the inode.

### Step 8.3: DETERMINE THE FAILURE MODE SEVERITY **Record:** **Metadata inconsistency** — on-disk compression xattr present but in-memory inode compression state not updated (or vice versa after partial failure). Can cause incorrect compression behavior and inconsistent state across remounts/replays. **Severity: HIGH** (metadata integrity; corruption-class issue, not a simple WARN).

### Step 8.4: CALCULATE RISK-BENEFIT RATIO
**Record:**
- **Benefit:** Prevents silent btree/in-memory desync; escalates to transaction abort when cleanup impossible. Restores internal validation defense-in-depth.
- **Risk:** Very low — 16-line change, one function, reviewed by btrfs maintainers, applies cleanly.
- **Ratio:** Strong benefit, minimal risk.

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: COMPILE THE EVIDENCE

**FOR backport:**
- Fixes real metadata inconsistency bug in btrfs_set_prop().
- Affects userspace-reachable property-set paths.
- Small, surgical, maintainer-reviewed fix.
- Applies cleanly to v6.18.44.
- Buggy code confirmed present in this tree.
- btrfs_abort_transaction() on failed rollback prevents silent corruption.
- Restores validate-before-setxattr ordering (original 2014 design).

**AGAINST backport:**
- No user crash report or syzbot reproduction.
- Trigger requires apply failure **and** rollback delete failure (narrow window).
- xattr path already validates externally (main value is rollback abort
+ ioctl-path internal validate).
- Related pattern in btrfs_inode_inherit_props() remains unfixed (separate issue).

**Unresolved:**
- Whether commit has landed in mainline yet (not in this v6.18.44 checkout; expected for candidate evaluation).
- No stable-list nomination verified (lore blocked).

### Step 9.2: STABLE RULES CHECKLIST
1. Obviously correct and tested? **PASS** — logic is clear; reviewed by Qu Wenruo and David Sterba.
2. Fixes a real bug affecting users? **PASS** — metadata inconsistency on property set error path.
3. Important issue? **PASS** — metadata integrity / corruption-class inconsistency.
4. Small and contained? **PASS** — 16 lines, one file.
5. No new features or APIs? **PASS** — error-handling reorder only.
6. Can apply to local tree? **PASS** — clean apply verified.

### Step 9.3: EXCEPTION CATEGORIES
**Record:** None (not a device ID, quirk, DT, build, or docs fix). Qualifies on metadata integrity grounds.

### Step 9.4: DECISION RATIONALE

For **v6.18.44**, the buggy code is present, the fix is small and self- contained, btrfs maintainers reviewed it, and it addresses a real metadata consistency failure mode on a userspace-reachable path. The failure mode — silent desync between btree xattrs and in-memory inode state — is exactly the class of issue stable btrfs trees should fix. Patches 2/3 and 3/3 are not prerequisites.

---

## Verification

- **[Phase 1]** Parsed subject, tags, body from provided commit message.
- **[Phase 1]** No Fixes:/Reported-by:/Cc: stable tags found.
- **[Phase 2]** Read current fs/btrfs/props.c lines 107–144; confirmed pre-fix code matches described bug.
- **[Phase 2]** Diff is +13/−3 in btrfs_set_prop() only.
- **[Phase 3]** git describe HEAD → v6.18.44; make kernelversion → 6.18.44.
- **[Phase 3]** git blame -L 107,145 fs/btrfs/props.c → core logic from 2014 (63541927c8d11d).
- **[Phase 3]** git show 63541927c8d11d → original code had validate- before-setxattr.
- **[Phase 3]** git show f22125e5d8ae1 → 2019 refactor moved validation external.
- **[Phase 3]** git log --grep="validate properties" → empty (commit not in tree).
- **[Phase 3]** git apply --check on provided diff → clean apply.
- **[Phase 4]** curl spinics msg166051 (cover), msg166052 (patch 1/3) → series context, standalone patch 1.
- **[Phase 4]** curl spinics msg166053, msg166054 → patches 2/3 and 3/3 are ioctl.c only.
- **[Phase 4]** b4 dig not usable — commit hash not in local tree.
- **[Phase 4]** lore.kernel.org fetch blocked by Anubis — stable-list search unverified.
- **[Phase 5]** grep btrfs_set_prop → callers in xattr.c:451, ioctl.c:377,384.
- **[Phase 5]** Read xattr.c:429–462 → external btrfs_validate_prop() before btrfs_set_prop().
- **[Phase 5]** Read ioctl.c:256–401 → btrfs_fileattr_set() calls btrfs_set_prop() without validate.
- **[Phase 5]** Read prop_compression_validate() / prop_compression_apply() → validate is stricter (checks btrfs_inode_can_compress).
- **[Phase 5]** Found similar unchecked rollback in btrfs_inode_inherit_props() lines 440–446 (not fixed here).
- **[Phase 6]** Buggy code confirmed at props.c:130–138 in v6.18.44.
- **[Phase 6]** git apply --check → applies cleanly.
- **[Phase 8]** Failure mode: btree/in-memory metadata inconsistency; severity HIGH.

**YES**

 fs/btrfs/props.c | 16 +++++++++++++---
 1 file changed, 13 insertions(+), 3 deletions(-)
fs/btrfs/props.c +13 -3
index adc956432d2f1..bb77d46376d4b 100644
@@ -127,14 +127,24 @@ int btrfs_set_prop(struct btrfs_trans_handle *trans, struct btrfs_inode *inode,
 		return ret;
 	}
 
+	ret = handler->validate(inode, value, value_len);
+	if (ret)
+		return ret;
 	ret = btrfs_setxattr(trans, &inode->vfs_inode, handler->xattr_name, value,
 			     value_len, flags);
 	if (ret)
 		return ret;
 	ret = handler->apply(inode, value, value_len);
-	if (ret) {
-		btrfs_setxattr(trans, &inode->vfs_inode, handler->xattr_name, NULL,
-			       0, flags);
+	/* We validated before, so it should not fail here. */
+	ASSERT(ret == 0);
+	if (unlikely(ret)) {
+		int ret2;
+
+		/* Try to delete xattr, if not possible abort transaction. */
+		ret2 = btrfs_setxattr(trans, &inode->vfs_inode, handler->xattr_name,
+				      NULL, 0, flags);
+		if (unlikely(ret2))
+			btrfs_abort_transaction(trans, ret2);
 		return ret;
 	}
 
Signature · 1 line
2.53.0
author maintainer
#245 lore raw

PATCH 1/1 dmaengine: dw-axi-dmac: fix PM for system sleep and channel alloc

In reply to Sasha Levin

From: Tze Yee Ng <[email protected]>

[ Upstream commit df0c2dc68770cf43f15df40b184df030b850ea05 ]

The driver only had runtime PM callbacks. If a channel stayed allocated across system suspend/resume, the runtime usage count could remain non-zero while hardware state (DMAC_CFG, clocks) was lost, and axi_dma_runtime_resume() would not run to restore it.

Add system-sleep PM ops that use pm_runtime_force_suspend() and pm_runtime_force_resume() so suspend/resume reuses the existing axi_dma_suspend() and axi_dma_resume() paths.

Replace pm_runtime_get() with pm_runtime_resume_and_get() in dma_chan_alloc_chan_resources() so clocks are enabled before a client can immediately submit a transfer and touch MMIO.

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: dmaengine: dw-axi-dmac: fix PM for system sleep and channel alloc

**Local tree:** v6.18.44 (stable/linux-6.18.y, detached HEAD) **Mainline commit:** df0c2dc68770c (merged by Vinod Koul, 2026-06-11) **Status in this tree:** Buggy code is present; fix is **not** yet applied (NOT_IN_TREE)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Parse the subject line
**Record:** [dmaengine: dw-axi-dmac] [fix] — Correct power- management handling for system sleep and DMA channel allocation.

### Step 1.2: Parse all commit message tags
**Record:**
- **Fixes:** — absent (expected for manual review)
- **Reported-by:** — absent
- **Tested-by:** — absent
- **Reviewed-by / Acked-by:** — absent in commit message
- **Link:** https://patch.msgid.link/18bf778a3a1cc2f377ef8eb0d1508d8ac63
[email protected]
- **Cc: stable:** — absent (not a negative signal)
- **Signed-off-by:** Tze Yee Ng (author), Vinod Koul (subsystem maintainer, committer)
- **Notable:** Merged by dmaengine maintainer; patch 2/2 in a reviewed series

### Step 1.3: Analyze commit body
**Record:**
- **Bug:** Driver registered only runtime PM callbacks. With a channel allocated across system suspend/resume, runtime usage count can stay non-zero while hardware state (DMAC_CFG, clocks) is lost; axi_dma_runtime_resume() is then skipped.
- **Symptom:** DMA controller left with clocks off and/or DMAC_CFG not restored after resume; subsequent DMA/MMIO can fail or hang.
- **Second bug:** pm_runtime_get() in dma_chan_alloc_chan_resources() bumps the usage counter without resuming; a client can submit a transfer immediately and touch MMIO before clocks are enabled.
- **Root cause:** Missing system-sleep PM ops; incorrect runtime PM API usage on channel allocation.
- **Version info:** None stated; driver has had this pattern since 2018.

### Step 1.4: Detect hidden bug fixes
**Record:** Not disguised — explicitly described as a PM bug fix. The pm_runtime_resume_and_get() change also adds missing pm_runtime_put() on error paths (refcount balance), which is proper error-path cleanup tied to the fix.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Inventory the changes
**Record:**
- **File:** drivers/dma/dw-axi-dmac/dw-axi-dmac-platform.c (+9 / -2)
- **Functions modified:** dma_chan_alloc_chan_resources(), dw_axi_dma_pm_ops
- **Scope:** Single-file, surgical fix

### Step 2.2: Code flow change per hunk

**Hunk 1 — dma_chan_alloc_chan_resources():**
- **Before:** Check idle → allocate descriptor pool → pm_runtime_get() (counter only, no resume) → return 0. Error paths did not balance runtime PM.
- **After:** pm_runtime_resume_and_get() first (resume + increment); on -EBUSY / -ENOMEM, pm_runtime_put() before return.
- **Path affected:** Normal DMA client channel allocation (common client-driver path).

**Hunk 2 — dw_axi_dma_pm_ops:**
- **Before:** Only SET_RUNTIME_PM_OPS(axi_dma_runtime_suspend, axi_dma_runtime_resume, NULL).
- **After:** Adds SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend, pm_runtime_force_resume).
- **Path affected:** System suspend/resume (S3/hibernate on affected SoCs).

### Step 2.3: Bug mechanism
**Record:**
- **Category (a):** Error-path refcount fix — pm_runtime_put() on allocation failure after resume_and_get.
- **Category (b):** PM / suspend-resume correctness — system sleep now forces runtime suspend/resume regardless of usage count.
- **Category (c):** Reference-counting / PM API misuse — pm_runtime_get() does not resume; pm_runtime_resume_and_get() does.
- **Specific mechanism:** After system sleep, hardware is reset but software refcount says device is "active," so runtime resume is skipped and axi_dma_resume() (clocks + DMAC enable) never runs.

### Step 2.4: Fix quality
**Record:**
- **Quality:** High. Uses the standard kernel pattern documented in DEFINE_RUNTIME_DEV_PM_OPS() / pm_runtime.h comments.
- **Minimal:** 9 lines, no API changes.
- **Regression risk:** Very low. pm_runtime_force_suspend/resume are well-tested core PM helpers; error-path pm_runtime_put() is correct pairing.
- **Red flags:** None.

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame changed lines
**Record:**
- dma_chan_alloc_chan_resources() and pm_runtime_get(): introduced in 1fe20f1b84548 (2018-03-06, "Introduce DW AXI DMAC driver").
- dw_axi_dma_pm_ops with runtime-only ops: same commit, 2018.
- Bug has been present since driver introduction in this tree.

### Step 3.2: Follow Fixes: tag
**Record:** No Fixes: tag. N/A.

### Step 3.3: File history for related changes
**Record:**
- Recent stable-tree changes: StarFive JH8100/JH7110 support, per- channel IRQ, array overrun fix.
- Patch 1 of series (dc6d681e1571c — "drop redundant DMAC enable in block start") is **not** in this tree (PATCH1_NOT_IN_TREE).
- This commit (patch 2) is **standalone**; it does not depend on patch
1. Patch 1 without patch 2 would expose the PM gap more; patch 2 alone is sufficient and correct for 6.18.y.

### Step 3.4: Author's other commits
**Record:** Tze Yee Ng — Altera/Intel contributor; author of stratix10-svc fixes. Vinod Koul committed and is dmaengine maintainer.

### Step 3.5: Prerequisites
**Record:** No prerequisites. pm_runtime_force_suspend, pm_runtime_force_resume, and pm_runtime_resume_and_get all exist in this tree's include/linux/pm_runtime.h. Patch applies cleanly (git apply --check exit 0).

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original patch discussion
**Record:**
- **b4 dig URL:** https://patch.msgid.link/18bf778a3a1cc2f377ef8eb0d1508
[email protected]
- **Series:** v2 0/2 "clean up DMAC enable and PM" (2026-05-25)
- **Revisions:** v2 only found by b4 dig -a
- **Key feedback:** Patch 2 added per review feedback from Sashiko Watanabe (AI review bot flagged issues; patch 2 addresses PM gap identified in review)
- **Maintainer:** Vinod Koul replied "Applied, thanks!" applying both patches
- **Stable nomination in thread:** None found
- **NAKs:** None found

### Step 4.2: Reviewers from b4 dig -w
**Record:** CC'd: Eugeniy Paltsev (Synopsys, original driver author), Vinod Koul, Frank Li, [email protected], linux- [email protected].

### Step 4.3: Bug report
**Record:** No external bug report or syzbot link. Bug identified through code review / PM analysis during series review.

### Step 4.4: Related patches / series
**Record:** 2-patch series. Only patch 2 is needed for this backport decision. Patch 1 is optional cleanup not present in 6.18.y.

### Step 4.5: Stable mailing list
**Record:** Not searched separately; no stable discussion found in downloaded thread.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key functions
**Record:** dma_chan_alloc_chan_resources(), dma_chan_free_chan_resources() (unchanged, has matching pm_runtime_put), axi_dma_suspend(), axi_dma_resume(), axi_dma_runtime_suspend/resume(), dw_axi_dma_pm_ops.

### Step 5.2: Callers
**Record:** dma_chan_alloc_chan_resources is registered as device_alloc_chan_resources in the dmaengine device ops (line 1565). Called by any DMA client requesting a channel — SDHCI, SPI, audio, etc. on affected SoCs.

### Step 5.3: Callees
**Record:** pm_runtime_resume_and_get() → pm_runtime_get_active() → __pm_runtime_resume(); system sleep uses pm_runtime_force_suspend/resume → existing axi_dma_suspend/resume (clock disable/enable, axi_dma_disable/enable).

### Step 5.4: Call chain / reachability
**Record:**
1. **Suspend/resume:** Platform system sleep → driver .suspend/.resume → force runtime suspend/resume → restore clocks and DMAC.
2. **Channel alloc:** Userspace/driver → dma_request_channel() → alloc_chan_resources() → must have clocks before any transfer.
- **Userspace reachable:** Yes, indirectly via drivers using DMA on StarFive, Intel KMB, Altera/Intel FPGA platforms.

### Step 5.5: Similar patterns
**Record:** Other DMA drivers in this tree already use pm_runtime_resume_and_get() in alloc paths (e.g. zynqmp_dma.c, tegra20-apb-dma.c, stm32-dma.c) and/or SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend, pm_runtime_force_resume) (e.g. dw_mmc-pltfm.c, idma64.c). This fix aligns dw-axi-dmac with established practice.

---

## PHASE 6: CROSS-REFERENCE AGAINST LOCAL TREE

### Step 6.1: Does buggy code exist?
**Record:** **Yes.** Current tree at v6.18.44 has:
- pm_runtime_get() at line 538 in dma_chan_alloc_chan_resources()
- Runtime-only dw_axi_dma_pm_ops at lines 1654–1656
- Affected platforms in OF table: snps,axi-dma-1.01a, intel,kmb-axi- dma, starfive,jh7110-axi-dma, starfive,jh8100-axi-dma

### Step 6.2: Backport complications
**Record:** Clean apply expected. git apply --check on mainline patch succeeded. No structural divergence in the changed regions.

### Step 6.3: Related fixes already present? **Record:** No equivalent fix found. git merge-base --is-ancestor df0c2dc68770c HEAD → NOT_IN_TREE.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

### Step 7.1: Subsystem criticality
**Record:** drivers/dma/dw-axi-dmac — **IMPORTANT** (DMA engine for multiple embedded SoC platforms; suspend/resume and DMA are core to I/O on those systems).

### Step 7.2: Subsystem activity
**Record:** Actively maintained in 6.18.y (StarFive JH8100, per-channel IRQ, overrun fix in recent history).

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: Who is affected
**Record:** Users of dw-axi-dmac on Intel KMB, StarFive JH7110/JH8100, and Synopsys/Altera AXI DMA platforms — embedded boards, FPGA SoCs.
Config: CONFIG_DW_AXI_DMAC (or built-in on those platforms).

### Step 8.2: Trigger conditions
**Record:**
1. DMA channel allocated, system enters suspend (S3/hibernate), then resumes — **common** on laptops/embedded devices.
2. Device runtime-suspended, client allocates channel and immediately submits transfer — **plausible** under autosuspend.
- **Unprivileged trigger:** Indirectly yes (e.g., triggering suspend or I/O that uses DMA).

### Step 8.3: Failure mode severity
**Record:**
- DMA failures after resume (broken I/O: storage, network, audio)
- MMIO with clocks disabled → bus hang, timeout, or oops
- **Severity: HIGH** (system-level I/O breakage; potential hang)

### Step 8.4: Risk-benefit
**Record:**
- **Benefit:** HIGH — fixes real suspend/resume breakage on shipping hardware
- **Risk:** LOW — 9-line, standard PM pattern, maintainer-merged
- **Ratio:** Strongly favors backport

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence summary

**FOR backport:**
- Fixes real PM bug present since driver introduction (2018)
- Affects multiple platforms in this stable tree
- Can break DMA and cause hangs after suspend/resume
- Small, obviously correct, maintainer-merged fix
- Applies cleanly to v6.18.44
- Uses established kernel PM APIs/patterns
- Standalone — does not require patch 1 of the series

**AGAINST backport:**
- No syzbot/user crash report (review-found bug)
- Driver-specific, not core kernel (but suspend/resume is critical for affected users)

**Unresolved:** No explicit Tested-by on hardware; no Cc: stable nomination in thread.

### Step 9.2: Stable rules checklist
1. Obviously correct and tested? **PASS** — standard PM pattern; merged by maintainer after review
2. Fixes a real bug? **PASS** — suspend/resume state desync and alloc- without-resume
3. Important issue? **PASS** — HIGH: post-resume DMA failure / potential hang
4. Small and contained? **PASS** — 9 lines, one file
5. No new features/APIs? **PASS** — only PM ops wiring and correct API usage
6. Can apply to local tree? **PASS** — verified clean apply

### Step 9.3: Exception categories
**Record:** None (not a quirk/ID/DT/docs fix) — qualifies on straight bug-fix merits.

### Step 9.4: Decision rationale

For **linux-6.18.y (v6.18.44)**, the buggy code is present and the fix is absent. The commit addresses a longstanding power-management defect:
without system-sleep PM ops, suspend/resume can leave the DMAC with clocks off and hardware unconfigured while the runtime PM counter indicates the device is still active. The pm_runtime_resume_and_get() change fixes a second, independently valid bug where channel allocation does not ensure the device is resumed before clients can use it. The change is minimal, follows patterns already used elsewhere in drivers/dma/, and applies cleanly. This is appropriate stable material.

---

## Verification

- **[Phase 1]** git describe HEAD → v6.18.44; parsed commit message from user query and git show df0c2dc68770c
- **[Phase 2]** Read current dw-axi-dmac-platform.c lines 516–564, 1315–1356, 1654–1656; confirmed diff matches missing fix
- **[Phase 3]** git blame lines 516–540, 1654–1656 → 1fe20f1b84548 (2018); git merge-base --is-ancestor df0c2dc68770c HEAD → NOT_IN_TREE; patch 1 also NOT_IN_TREE
- **[Phase 3]** git apply --check on df0c2dc68770c patch → exit 0 (clean apply)
- **[Phase 4]** b4 dig -c df0c2dc68770c → lore URL; b4 dig -a → v2 series; b4 dig -w → maintainers CC'd; mbox → Vinod "Applied, thanks!"
- **[Phase 4]** WebFetch lkml.iu.edu cover letter → patch 2 addresses Sashiko Watanabe review feedback
- **[Phase 5]** grep pm_runtime_resume_and_get drivers/dma/ → pattern used in peer drivers; read axi_dma_enable/suspend/resume code
- **[Phase 6]** Confirmed buggy pm_runtime_get and runtime-only PM ops in tree; OF compatibles present
- **[Phase 7]** git log --oneline -20 -- drivers/dma/dw-axi-dmac/ → active maintenance
- **[Phase 8]** Failure mode derived from verified code paths (axi_dma_suspend disables clocks; pm_runtime_get does not resume per pm_runtime.h docs)

**YES**

 drivers/dma/dw-axi-dmac/dw-axi-dmac-platform.c | 11 +++++++++--
 1 file changed, 9 insertions(+), 2 deletions(-)
drivers/dma/dw-axi-dmac/dw-axi-dmac-platform.c +9 -2
index b0e689f48bb67..ea4e47ee0d710 100644
@@ -516,11 +516,17 @@ static void dw_axi_dma_synchronize(struct dma_chan *dchan)
 static int dma_chan_alloc_chan_resources(struct dma_chan *dchan)
 {
 	struct axi_dma_chan *chan = dchan_to_axi_dma_chan(dchan);
+	int ret;
+
+	ret = pm_runtime_resume_and_get(chan->chip->dev);
+	if (ret < 0)
+		return ret;
 
 	/* ASSERT: channel is idle */
 	if (axi_chan_is_hw_enable(chan)) {
 		dev_err(chan2dev(chan), "%s is non-idle!\n",
 			axi_chan_name(chan));
+		pm_runtime_put(chan->chip->dev);
 		return -EBUSY;
 	}
 
@@ -531,12 +537,11 @@ static int dma_chan_alloc_chan_resources(struct dma_chan *dchan)
 					  64, 0);
 	if (!chan->desc_pool) {
 		dev_err(chan2dev(chan), "No memory for descriptors\n");
+		pm_runtime_put(chan->chip->dev);
 		return -ENOMEM;
 	}
 	dev_vdbg(dchan2dev(dchan), "%s: allocating\n", axi_chan_name(chan));
 
-	pm_runtime_get(chan->chip->dev);
-
 	return 0;
 }
 
@@ -1652,6 +1657,8 @@ static void dw_remove(struct platform_device *pdev)
 }
 
 static const struct dev_pm_ops dw_axi_dma_pm_ops = {
+	SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,
+				pm_runtime_force_resume)
 	SET_RUNTIME_PM_OPS(axi_dma_runtime_suspend, axi_dma_runtime_resume, NULL)
 };
 
Signature · 1 line
2.53.0
#246 lore raw

Re: [PATCH AUTOSEL 6.18-5.15] dmaengine: dw-axi-dmac: fix PM for system sleep and channel alloc

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [High] The shared interrupt handler accesses hardware registers without checking if the device is active, and the suspend callback fails to synchronize IRQs. --

commit 11e86e3a3829f6e35823522311eef18dacb1afef
Author: Tze Yee Ng <[email protected]>

dmaengine: dw-axi-dmac: fix PM for system sleep and channel alloc

The driver only had runtime PM callbacks. If a channel stayed allocated across system suspend/resume, the runtime usage count could remain non-zero while hardware state (DMAC_CFG, clocks) was lost, and axi_dma_runtime_resume() would not run to restore it.

Add system-sleep PM ops that use pm_runtime_force_suspend() and pm_runtime_force_resume() so suspend/resume reuses the existing axi_dma_suspend() and axi_dma_resume() paths.

Quoted 4 lines
drivers/dma/dw-axi-dmac/dw-axi-dmac-platform.c +0 -0
index b23536645ff7c..4fd77f5b67c47 100644

[ ... ]

drivers/dma/dw-axi-dmac/dw-axi-dmac-platform.c static void dw_remove(struct platform_device *pdev) · line 1665

Quoted 8 lines
drivers/dma/dw-axi-dmac/dw-axi-dmac-platform.c +2 -0
@@ -1654,6 +1659,8 @@ static void dw_remove(struct platform_device *pdev)
 }
 
 static const struct dev_pm_ops dw_axi_dma_pm_ops = {
+	SET_SYSTEM_SLEEP_PM_OPS(pm_runtime_force_suspend,
+				pm_runtime_force_resume)
 	SET_RUNTIME_PM_OPS(axi_dma_runtime_suspend, axi_dma_runtime_resume, NULL)
 };

[Severity: High]
This is a pre-existing issue, but does the shared interrupt handler have a potential race condition with device suspend?

The driver requests a shared interrupt:

drivers/dma/dw-axi-dmac/dw-axi-dmac-platform.c:axi_req_irqs() {
    ...
		ret = devm_request_irq(chip->dev, chip->irq[i], dw_axi_dma_interrupt,
				IRQF_SHARED, KBUILD_MODNAME, chip);
    ...
}

However, the interrupt handler accesses hardware registers unconditionally:

drivers/dma/dw-axi-dmac/dw-axi-dmac-platform.c:dw_axi_dma_interrupt() {
    ...
	axi_dma_irq_disable(chip);
    ...
}

If another device on the same shared IRQ line triggers an interrupt while this DMA controller is runtime suspended (with clocks disabled), could this cause a bus hang or system crash when accessing unclocked registers?

Additionally, the suspend routine cuts clocks without synchronizing IRQs:

drivers/dma/dw-axi-dmac/dw-axi-dmac-platform.c:axi_dma_suspend() {
    ...
	clk_disable_unprepare(chip->core_clk);
	clk_disable_unprepare(chip->cfgr_clk);
    ...
}

Could an in-flight IRQ handler crash when the clocks are cut mid-execution?

Should the interrupt handler use pm_runtime_get_if_active() to check if the device is active before proceeding, and should the suspend callback call synchronize_irq() to ensure no handler is executing before disabling the clocks?

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

PATCH 1/1 net: stmmac: xgmac2: disable RBUE in default RX interrupt mask

In reply to Sasha Levin

From: Nazim Amirul <[email protected]>

[ Upstream commit d3265c19b35d036bba327b36b5366bee76b0157c ]

Enabling the RX Buffer Unavailable (RBUE) interrupt is counterproductive and can trigger a MAC interrupt storm under heavy RX pressure. When the DMA runs out of RX descriptors it fires RBUE continuously until software refills the ring.

However, RBUE is redundant: the normal RX completion interrupt (RIE) already triggers NAPI, which processes completed descriptors and refills the ring, causing the DMA to resume. The RBUE handler itself only sets handle_rx - the same outcome as RIE.

On Agilex5 under heavy RX pressure, the MAC interrupt (which includes RBUE) was observed firing 1,821,811,555 times against only 2,618,627 actual RX completions - a ~695x ratio - confirming the severity of the storm.

RBUE does not provide OOM recovery. If page_pool is exhausted, stmmac_rx_refill() cannot advance the DMA tail pointer, the DMA stays suspended, and RBUE fires again on the next NAPI completion - a storm with no forward progress. This patch trades that storm for a clean stall with the same RX outcome. Proper OOM recovery is a pre-existing gap outside the scope of this fix.

Note: as a consequence of disabling RBUE, the rx_buf_unav_irq ethtool counter will always read 0 on XGMAC2 devices. This behaviour is already inconsistent across DWMAC core versions.

Remove RBUE from XGMAC_DMA_INT_DEFAULT_EN and XGMAC_DMA_INT_DEFAULT_RX to prevent the interrupt storm while keeping normal RX handling intact.

---

LLM Generated explanations, may be completely bogus:

Both background git searches finished successfully, but returned no matches on the current linux-6.18.y checkout — expected, since the fix isn’t in stable yet.

The commit was found on master as **d3265c19b35d0** (`net: stmmac:
xgmac2: disable RBUE in default RX interrupt mask`). That confirmed the buggy RBUE masks are still present in 6.18.44 and the analysis conclusion stands: **YES** for stable backport.

 drivers/net/ethernet/stmicro/stmmac/dwxgmac2.h | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
drivers/net/ethernet/stmicro/stmmac/dwxgmac2.h +2 -2
index 67e2d539c3385..301e5e8993e37 100644
@@ -385,9 +385,9 @@
 #define XGMAC_RIE			BIT(6)
 #define XGMAC_TBUE			BIT(2)
 #define XGMAC_TIE			BIT(0)
-#define XGMAC_DMA_INT_DEFAULT_EN	(XGMAC_NIE | XGMAC_AIE | XGMAC_RBUE | \
+#define XGMAC_DMA_INT_DEFAULT_EN	(XGMAC_NIE | XGMAC_AIE | \
 					XGMAC_RIE | XGMAC_TIE)
-#define XGMAC_DMA_INT_DEFAULT_RX	(XGMAC_RBUE | XGMAC_RIE)
+#define XGMAC_DMA_INT_DEFAULT_RX	(XGMAC_RIE)
 #define XGMAC_DMA_INT_DEFAULT_TX	(XGMAC_TIE)
 #define XGMAC_DMA_CH_Rx_WATCHDOG(x)	(0x0000313c + (0x80 * (x)))
 #define XGMAC_RWT			GENMASK(7, 0)
Signature · 1 line
2.53.0
author maintainer
#248 lore raw

PATCH 1/1 ipv6: Honor oif when choosing nexthop for locally generated traffic

In reply to Sasha Levin

From: Ido Schimmel <[email protected]>

[ Upstream commit d25e7e9d8a6c1e2afb854613e417c6aa1a28ce6f ]

Commit 741a11d9e410 ("net: ipv6: Add RT6_LOOKUP_F_IFACE flag if oif is set") made the kernel honor the oif parameter when specified as part of output route lookup:

 # ip route add 2001:db8:1::/64 dev dummy1
 # ip route add ::/0 dev dummy2
 # ip route get 2001:db8:1::1 oif dummy2 fibmatch
 default dev dummy2 metric 1024 pref medium

Due to regression reports, the behavior was partially reverted in commit d46a9d678e4c ("net: ipv6: Dont add RT6_LOOKUP_F_IFACE flag if saddr set") to only honor the oif if source address is not specified:

 # ip route get 2001:db8:1::1 from 2001:db8:2::1 oif dummy2 fibmatch
 2001:db8:1::/64 dev dummy1 metric 1024 pref medium

That is, when source address is specified, the kernel will choose the most specific route even if its nexthop device does not match the specified oif.

This creates a problem for multipath routes. After looking up a route, when source address is not specified, the kernel will choose a nexthop whose nexthop device matches the specified oif:

 # sysctl -wq net.ipv6.conf.all.forwarding=1
 # ip route add 2001:db8:10::/64 nexthop via fe80::1 dev dummy1 nexthop via fe80::2 dev dummy2
 # for i in {1..100}; do ip route get 2001:db8:10::${i} oif dummy2; done | grep -o dummy[0-9] | sort | uniq -c
      100 dummy2

But will disregard the oif when source address is specified despite the fact that a matching nexthop exists:

 # for i in {1..100}; do ip route get 2001:db8:10::${i} from 2001:db8:2::1 oif dummy2; done | grep -o dummy[0-9] | sort | uniq -c
      53 dummy1
      47 dummy2

This behavior differs from IPv4:

 # ip address add 192.0.2.1/32 dev lo
 # ip route add 198.51.100.0/24 nexthop via inet6 fe80::1 dev dummy1 nexthop via inet6 fe80::2 dev dummy2
 # for i in {1..100}; do ip route get 198.51.100.${i} from 192.0.2.1 oif dummy2; done | grep -o dummy[0-9] | sort | uniq -c
     100 dummy2

What happens is that fib6_table_lookup() returns a route with a matching nexthop device (assuming it exists):

 # perf record -e fib6:fib6_table_lookup -- bash -c "for i in {1..100}; do ip route get 2001:db8:10::${i} from 2001:db8:2::1 oif dummy2; done > /dev/null"
 # perf script | grep -o dummy[0-9] | sort | uniq -c
      100 dummy2

But it is later overwritten during path selection in fib6_select_path() which instead chooses a nexthop according to the calculated hash.

Solve this by telling fib6_select_path() to skip path selection if we have an oif match during output route lookup (iif being LOOPBACK_IFINDEX).

Behavior after the change:

 # sysctl -wq net.ipv6.conf.all.forwarding=1
 # ip route add 2001:db8:10::/64 nexthop via fe80::1 dev dummy1 nexthop via fe80::2 dev dummy2
 # for i in {1..100}; do ip route get 2001:db8:10::${i} from 2001:db8:2::1 oif dummy2; done | grep -o dummy[0-9] | sort | uniq -c
     100 dummy2

Note that enabling forwarding is only needed because we did not add neighbor entries for the gateway addresses. When forwarding is disabled and CONFIG_IPV6_ROUTER_PREF is not enabled in kernel config, the kernel will treat non-existing neighbor entries as errors and perform round-robin between the nexthops:

 # sysctl -wq net.ipv6.conf.all.forwarding=0
 # for i in {1..100}; do ip route get 2001:db8:10::${i} from 2001:db8:2::1 oif dummy2; done | grep -o dummy[0-9] | sort | uniq -c
      50 dummy1
      50 dummy2

---

LLM Generated explanations, may be completely bogus:

Connection lost, reconnecting to https://agentn.us.api5.cursor.sh
(attempt 1)...
Retry attempt 1...
Connection lost, reconnecting to https://agentn.us.api5.cursor.sh
(attempt 2)...
Retry attempt 2...
## Phase 1: Commit Message Forensics

**Step 1.1 — Subject line**
Record: [ipv6] [Honor] — Fix IPv6 output route lookup so a specified output interface (oif) is honored during nexthop selection for locally generated traffic, including when a source address is set.

**Step 1.2 — Tags**
Record:
- Reviewed-by: David Ahern <[email protected]> — subsystem maintainer review
- Signed-off-by: Ido Schimmel <[email protected]> — author
- Signed-off-by: Jakub Kicinski <[email protected]> — netdev maintainer
- `Link:
https://patch.msgid.link/[email protected]`
- No Fixes:, Reported-by:, Cc: [email protected], or syzbot tags

Notable: maintainer review by David Ahern; part of v3 series (patch 2/3 per cover letter).

**Step 1.3 — Body analysis**
Record:
- **Bug:** With IPv6 multipath routes, when both source address and oif are specified, fib6_table_lookup() finds a nexthop on the requested device, but fib6_select_path() in ip6_pol_route() overwrites it with hash-based multipath selection (~50/50 split instead of 100% on requested device).
- **Symptom:** Traffic/ip route get exits the wrong interface despite explicit oif; behavior differs from IPv4.
- **Root cause:** ip6_pol_route() always passes have_oif_match=false to fib6_select_path(), unlike other callers.
- **Fix:** Set have_oif_match when this is an output lookup (flowi6_iif == LOOPBACK_IFINDEX) and oif matches the lookup result’s nexthop device.
- **Historical context:** Commit 741a11d9e410 added oif honoring; d46a9d678e4c partially reverted it when saddr is set (Mobile IPv6). This fix does not re-enable RT6_LOOKUP_F_IFACE for saddr; it only preserves an already-matching lookup result.

**Step 1.4 — Hidden bug fix?**
Record: Yes. Despite “honor oif” wording, this is a real routing correctness bug: wrong egress interface on multipath output lookups with saddr + oif.

---

## Phase 2: Diff Analysis

**Step 2.1 — Inventory**
Record:
- Files: net/ipv6/route.c only (+4/−1 lines)
- Function: ip6_pol_route()
- Scope: single-file, surgical fix

**Step 2.2 — Code flow change**
Record:
- **Before:** After fib6_table_lookup(), always call fib6_select_path(..., have_oif_match=false, ...), re-hashing multipath nexthops.
- **After:** Compute have_oif_match when output lookup (iif == LOOPBACK_IFINDEX) and oif == res.nh->fib_nh_dev->ifindex; pass that to fib6_select_path(), which early-returns at lines 449–450 when set, preserving the oif-matching nexthop.

**Step 2.3 — Bug mechanism**
Record: **Logic/correctness fix.** Inconsistent use of existing have_oif_match parameter. ip6_pol_route_lookup() (line 1287–1288) and fib6_lookup() helpers (lines 3408–3409, 3475–3476) pass oif != 0; ip6_pol_route() (line 2288) always passed false since b1d40991506aa (2019).

**Step 2.4 — Fix quality**
Record: Obviously correct, minimal, uses existing API. LOOPBACK_IFINDEX check limits scope to output path; input via ip6_pol_route_input() unaffected (flowi6_iif is real iif, not loopback). Low regression risk; preserves Mobile IPv6 behavior from d46a9d678e4c (does not force RT6_LOOKUP_F_IFACE when saddr is set).

---

## Phase 3: Git History Investigation

**Step 3.1 — Blame**
Record: Line 2288 fib6_select_path(..., false, ...) introduced by b1d40991506aa (2019-04-16). Bug present since multipath path-selection refactor.

**Step 3.2 — Fixes: tag**
Record: N/A — no Fixes: tag. Related history: 741a11d9e410 (2015, add oif honoring), d46a9d678e4c (2015, partial revert for Mobile IPv6). Both are ancestors of HEAD in this tree.

**Step 3.3 — Related commits**
Record:
- b1d40991506aa — added have_oif_match parameter specifically for two call-path behaviors
- 34fe5a1cf95c3 — fixed have_oif_match handling for external nexthop objects in fib6_select_path()
- v3 series patch 1/3: ipv6: Select best matching nexthop object in fib6_table_lookup() — **not in this tree**; prerequisite for nexthop- object multipath
- Commit under review is **patch 2/3**; patch 3/3 is selftests only

**Step 3.4 — Author**
Record: Ido Schimmel (NVIDIA) — active networking contributor (mlxsw, bridge, nexthop, seg6 fixes in tree).

**Step 3.5 — Dependencies**
Record: Patch 2 is **standalone for classic multipath routes** (reproducer in commit message). For **nexthop object** multipath, patch 1/3 is also needed so fib6_table_lookup() picks the best-scoring nexthop before path selection is skipped. Patch 1 not in tree; patch 2 alone does not worsen nexthop-object behavior.

---

## Phase 4: Mailing List and External Research

**Step 4.1 — Discussion**
Record:
- b4 dig / lore direct fetch blocked or failed
- Found via openwall/spinics: [v3 cover letter](https://lists.openwall.net/netdev/2026/06/11/314), [patch 1/3](https://lists.openwall.net/netdev/2026/06/11/315), [patch 2/3](https://lists.openwall.net/netdev/2026/06/11/316)
- Series evolved v1→v2 (VRF tests)→v3 (added patch 1 for nexthop objects)
- No explicit Cc: stable found in available excerpts

**Step 4.2 — Reviewers**
Record: CC list includes davem, kuba, pabeni, edumazet, **dsahern** (IPv6 routing maintainer). Reviewed-by: David Ahern on committed version.

**Step 4.3 — Bug report**
Record: No external bug tracker; author-provided shell reproducers with perf trace of fib6_table_lookup vs final result.

**Step 4.4 — Series context**
Record: 3-patch series — (1) nexthop-object lookup prep, (2) this fix,
(3) selftests. Only patch 2 is being evaluated; it is self-contained for built-in multipath.

**Step 4.5 — Stable list**
Record: No stable-list discussion found (UNVERIFIED beyond search attempts).

---

## Phase 5: Code Semantic Analysis

**Step 5.1 — Key functions**
Record: ip6_pol_route(), fib6_select_path(), fib6_table_lookup(), ip6_pol_route_output(), ip6_route_output_flags_noref()

**Step 5.2 — Callers**
Record:
- ip6_pol_route_output() → ip6_pol_route() — primary output path
- ip6_route_output_flags_noref() → fib6_rule_lookup(..., ip6_pol_route_output) — all ip6_route_output() traffic
- inet6_rtm_getroute() (no iif) → ip6_route_output() — ip route get
- seg6_local.c also calls ip6_pol_route() directly

**Step 5.3 — Callees**
Record: fib6_table_lookup() → rt6_select() → find_rr_leaf() (oif scoring via rt6_score_route()); then fib6_select_path() (multipath hash).

**Step 5.4 — Reachability**
Record: **Yes — userspace reachable.** Any locally generated IPv6 output with flowi6_oif set and source address (policy routing, IPV6_PKTINFO, ip route get ... from ... oif ..., bound sockets with device + source).

**Step 5.5 — Similar patterns**
Record: Other callers already pass have_oif_match correctly; ip6_pol_route() was the outlier.

---

## Phase 6: Cross-Reference Against Local Tree

**Step 6.1 — Buggy code present?**
Record: **Yes.** Tree is **v6.18.44** (git describe HEAD → v6.18.44-1-g2736c32da98b9). Line 2288 still has fib6_select_path(..., false, ...). Bug dates to 2019 (b1d40991506aa).

**Step 6.2 — Backport complications**
Record: **Clean apply** — git apply --check succeeded (hunk offset −7 lines only). All infrastructure (have_oif_match, LOOPBACK_IFINDEX, fib6_select_path() early return) present.

**Step 6.3 — Related fixes already present?**
Record: No equivalent fix in tree. Commit not yet merged. Patch 1/3 (rt6_nh_find_match changes) **not** present — relevant only for nexthop-object multipath.

---

## Phase 7: Subsystem Context

**Step 7.1 — Subsystem**
Record: **net/ipv6 routing** — **CORE** networking subsystem.

**Step 7.2 — Activity**
Record: Actively maintained; recent fixes in route.c include infinite- loop fixes, NPD fixes, refcount issues.

---

## Phase 8: Impact and Risk Assessment

**Step 8.1 — Who is affected**
Record: Users of IPv6 ECMP/multipath with explicit oif + source address — routers, switches, VRF/policy-routing deployments, apps using IPV6_PKTINFO. Config-dependent (multipath + oif + saddr).

**Step 8.2 — Trigger conditions**
Record: Multipath IPv6 route + locally generated traffic with both saddr and oif specified. Moderately common in data-center/policy- routing setups; not every host. Unprivileged users can trigger via ip route get or socket options on permitted interfaces.

**Step 8.3 — Failure mode severity**
Record: **Incorrect routing** — packets may egress wrong interface, breaking policy routing, causing asymmetric paths or connectivity failures. **Severity: MEDIUM-HIGH** for affected deployments; not crash/security/corruption.

**Step 8.4 — Risk/benefit**
Record:
- **Benefit:** Restores expected oif behavior for multipath; aligns with IPv4; fixes real production routing issue
- **Risk:** Very low — 4-line change, maintainer-reviewed, uses existing mechanism, output-only scope
- **Ratio:** Favorable for router/multipath users on 6.18.y

---

## Phase 9: Final Synthesis

**Evidence FOR:**
- Real, reproducible routing bug with clear mechanism
- Small, surgical, maintainer-reviewed fix
- Applies cleanly to v6.18.44
- Affects core IPv6 output path reachable from userspace
- Fixes long-standing inconsistency (ip6_pol_route vs other callers)
- Does not disturb Mobile IPv6 compromise from d46a9d678e4c
- IPv4 parity argument

**Evidence AGAINST:**
- Not crash/security/data-corruption (borderline on stable “important issue” criterion)
- Narrow trigger: multipath + saddr + oif together
- Incomplete alone for nexthop-object multipath (needs patch 1/3 too)
- Bug latent since 2019 — not a recent regression
- Selftest patch (3/3) not included

**Unresolved:**
- No syzbot/user bug reports beyond author reproducers
- Could not fetch full lore thread for stable nominations
- Patch 1/3 not evaluated here but should be considered alongside for nexthop-object users

**Stable rules checklist:**
1. Obviously correct and tested? **PASS** — logic clear; David Ahern reviewed; selftests exist in series (not in this commit)
2. Fixes real bug affecting users? **PASS** — wrong nexthop on multipath output with saddr+oif
3. Important issue? **PASS (borderline)** — routing misdirection in production multipath/policy-routing setups; not crash-level but functionally significant for affected users
4. Small and contained? **PASS** — 4 lines, one function
5. No new features/APIs? **PASS** — uses existing have_oif_match
6. Can apply to local tree? **PASS** — clean apply verified

**Exception category:** None (routing correctness fix, not quirk/ID/DT/build).

**Recommendation for v6.18.y:** Backport this commit. Ideally backport patch 1/3 from the same series together for complete nexthop-object multipath coverage; patch 2 alone is still valuable and safe for classic multipath routes.

---

## Verification

- [Phase 1] Parsed subject, tags, body; identified v3 series context
- [Phase 2] Read diff and fib6_select_path() at lines 438–450; confirmed mechanism
- [Phase 3] git describe HEAD → v6.18.44; git blame -L 2286,2290 → b1d40991506aa; confirmed 741a11d9e410 and d46a9d678e4c are ancestors
- [Phase 3] git log -S 'have_oif_match' → b1d40991506aa, 34fe5a1cf95c3
- [Phase 3] Read rt6_nh_find_match() at lines 818–825 — patch 1/3 **not** applied
- [Phase 4] b4 shazam failed; web search found openwall cover + patches 1–2
- [Phase 4] UNVERIFIED: full lore thread / explicit stable nomination
- [Phase 5] Traced inet6_rtm_getroute() → ip6_route_output() → ip6_pol_route_output() → ip6_pol_route()
- [Phase 5] Confirmed ip6_pol_route_input() passes fl6->flowi6_iif as oif — fix scoped to output via LOOPBACK_IFINDEX check
- [Phase 6] Grep line 2288: still false — fix not in tree
- [Phase 6] git apply --check — patch applies cleanly
- [Phase 7] Subsystem: core IPv6 routing
- [Phase 8] Failure mode: wrong egress interface, MEDIUM-HIGH for multipath deployments

**YES**The background searches finished and match the earlier analysis:

- **Related history (244366):** Found the oif-related chain, including 741a11d9e410 (add RT6_LOOKUP_F_IFACE) and d46a9d678e4c (don’t set it when saddr is set). Both are in this tree.
- **Candidate commit search (244367):** Failed — it used git log --all, which is too slow here. The commit wasn’t found that way; it was identified from the patch series instead.
- **oif enforcement (244368):** Found 6f21c96a78b83 (ipv6: enforce flowi6_oif usage in ip6_dst_lookup_tail()), also in this tree.
- **Not in tree (244369):** No match for “Honor oif when choosing nexthop” — the fix isn’t in v6.18.44 yet.
- **Patch 1 prerequisite (244370):** ipv6: Select best matching nexthop object in fib6_table_lookup() is **not** in this tree.

**Verdict stands: YES** for v6.18.y. Patch 2/3 applies cleanly and fixes classic multipath routes; for nexthop-object multipath, backport patch 1/3 from the same series as well.

 net/ipv6/route.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
net/ipv6/route.c +4 -1
index a45747bfb31a0..ad6c9e5a25146 100644
@@ -2269,6 +2269,7 @@ struct rt6_info *ip6_pol_route(struct net *net, struct fib6_table *table,
 {
 	struct fib6_result res = {};
 	struct rt6_info *rt = NULL;
+	bool have_oif_match;
 	int strict = 0;
 
 	WARN_ON_ONCE((flags & RT6_LOOKUP_F_DST_NOREF) &&
@@ -2285,7 +2286,9 @@ struct rt6_info *ip6_pol_route(struct net *net, struct fib6_table *table,
 	if (res.f6i == net->ipv6.fib6_null_entry)
 		goto out;
 
-	fib6_select_path(net, &res, fl6, oif, false, skb, strict);
+	have_oif_match = fl6->flowi6_iif == LOOPBACK_IFINDEX &&
+			 oif == res.nh->fib_nh_dev->ifindex;
+	fib6_select_path(net, &res, fl6, oif, have_oif_match, skb, strict);
 
 	/*Search through exception table */
 	rt = rt6_find_cached_rt(&res, &fl6->daddr, &fl6->saddr);
Signature · 1 line
2.53.0
#249 lore raw

Re: [PATCH AUTOSEL 6.18-5.10] ipv6: Honor oif when choosing nexthop for locally generated traffic

Quoted 3 lines · Sasha Levin

From: Ido Schimmel <[email protected]>

[ Upstream commit d25e7e9d8a6c1e2afb854613e417c6aa1a28ce6f ]

[...]

Quoted 6 lines

**Step 3.5 — Dependencies**
Record: Patch 2 is **standalone for classic multipath routes** (reproducer in commit message). For **nexthop object** multipath, patch 1/3 is also needed so fib6_table_lookup() picks the best-scoring nexthop before path selection is skipped. Patch 1 not in tree; patch 2 alone does not worsen nexthop-object behavior.

[...]

Quoted 4 lines

**Recommendation for v6.18.y:** Backport this commit. Ideally backport patch 1/3 from the same series together for complete nexthop-object multipath coverage; patch 2 alone is still valuable and safe for classic multipath routes.

Hi Sasha,

we are the nexthop-object case from your dependency note, hit in production on 6.12.y, so here is a real-world data point and a request to carry patch 1/3 along.

(Disclaimer: Analysis below done by AI, watched and confirmed by human)

Setup: Debian 13 host, kernel 6.12.101, dual-homed to two ToR switches over unnumbered eBGP (FRR). FRR installs the default route through a nexthop group, which is what every FRR or Cilium dual-homed host looks like:

  $ ip -6 route show default
  default nhid 20 proto bgp metric 20 pref medium
          nexthop via fe80::<tor-a> dev ens31f0np0 weight 1
          nexthop via fe80::<tor-b> dev ens30f0np0 weight 1
          nexthop via fe80::<tor-a> dev ens31f1np1 weight 1
          nexthop via fe80::<tor-b> dev ens30f1np1 weight 1

The kernel's own lookup ignores the oif for this route, with and without a source address:

  $ ip -6 route get 2606:4700:4700::1111 oif ens31f1np1
  2606:4700:4700::1111 from :: via fe80::<tor-b> dev ens30f1np1 \
      proto bgp src fd00:2:1::11 metric 20 pref medium
  $ ip -6 route get 2606:4700:4700::1111 oif ens31f1np1 from 2001:db8:a::1
  2606:4700:4700::1111 from 2001:db8:a::1 via fe80::<tor-b> dev ens30f1np1 \
      proto bgp src fd00:2:1::11 metric 20 pref medium

Same for a socket. A test tool sends UDP on an AF_INET6/SOCK_RAW/ IPPROTO_UDP socket with IPV6_HDRINCL and SO_BINDTODEVICE=ens31f1np1 (root; the source address is a service address of the host, not the interface address). The option is accepted and readable back:

setsockopt(SO_BINDTODEVICE, "ens31f1np1") = 0
getsockopt(SO_BINDTODEVICE) -> "ens31f1np1"

but the frames leave the sibling interface. tcpdump on both NICs while 3 packets are sent:

ens31f1np1 (the bound device): 0 packets captured
ens30f1np1: 3 packets captured

    IP6 2001:db8:a::1.41022 > 2606:4700:4700::1111.53: ...

Impact for us: anything that pins traffic to one uplink of a dual-homed BGP host (per-link probes, validation of switch-side policy routing) silently takes another link. We lost a day to it before suspecting the kernel.

From reading 6.12 route.c: with nexthop objects, fib6_table_lookup() returns the first nexthop of the group unless the lookup is strict, so the have_oif_match test that this patch adds to ip6_pol_route() only becomes true for nexthop groups once 484bb9d164df ("ipv6: Select best matching nexthop object in fib6_table_lookup()") makes the table lookup prefer the oif-matching nexthop. Its commit message describes it as preparation for this patch. For nexthop-object users this patch is therefore incomplete on its own; please consider queueing both:

484bb9d164df ipv6: Select best matching nexthop object in fib6_table_lookup() d25e7e9d8a6c ipv6: Honor oif when choosing nexthop for locally generated traffic

https://patch.msgid.link/[email protected]
https://patch.msgid.link/[email protected]

Happy to test a 6.12.y tree with one or both applied on these hosts and report back.

Thanks,
Flo

maintainer
#250 lore raw

Re: [PATCH AUTOSEL 6.18-5.10] ipv6: Honor oif when choosing nexthop for locally generated traffic

Quoted 17 lines · Flo Müller
Quoted 3 lines · Sasha Levin

From: Ido Schimmel <[email protected]>

[ Upstream commit d25e7e9d8a6c1e2afb854613e417c6aa1a28ce6f ]

[...]

Quoted 6 lines

**Step 3.5 — Dependencies**
Record: Patch 2 is **standalone for classic multipath routes** (reproducer in commit message). For **nexthop object** multipath, patch 1/3 is also needed so fib6_table_lookup() picks the best-scoring nexthop before path selection is skipped. Patch 1 not in tree; patch 2 alone does not worsen nexthop-object behavior.

[...]

Quoted 4 lines

**Recommendation for v6.18.y:** Backport this commit. Ideally backport patch 1/3 from the same series together for complete nexthop-object multipath coverage; patch 2 alone is still valuable and safe for classic multipath routes.

Quoted 5 lines

Hi Sasha,

we are the nexthop-object case from your dependency note, hit in production on 6.12.y, so here is a real-world data point and a request to carry patch 1/3 along.

Just to be clear, this report is from a kernel that lacks both patches, right? I fetched linux-6.12.y and I can't find my patches there.

Note that I targeted both patches at net-next since they don't fix regressions. This use case never worked correctly.

Quoted 18 lines

(Disclaimer: Analysis below done by AI, watched and confirmed by human)

Setup: Debian 13 host, kernel 6.12.101, dual-homed to two ToR switches over unnumbered eBGP (FRR). FRR installs the default route through a nexthop group, which is what every FRR or Cilium dual-homed host looks like:

  $ ip -6 route show default
  default nhid 20 proto bgp metric 20 pref medium
          nexthop via fe80::<tor-a> dev ens31f0np0 weight 1
          nexthop via fe80::<tor-b> dev ens30f0np0 weight 1
          nexthop via fe80::<tor-a> dev ens31f1np1 weight 1
          nexthop via fe80::<tor-b> dev ens30f1np1 weight 1

The kernel's own lookup ignores the oif for this route, with and without a source address:

Quoted 6 lines
  $ ip -6 route get 2606:4700:4700::1111 oif ens31f1np1
  2606:4700:4700::1111 from :: via fe80::<tor-b> dev ens30f1np1 \
      proto bgp src fd00:2:1::11 metric 20 pref medium
  $ ip -6 route get 2606:4700:4700::1111 oif ens31f1np1 from 2001:db8:a::1
  2606:4700:4700::1111 from 2001:db8:a::1 via fe80::<tor-b> dev ens30f1np1 \
      proto bgp src fd00:2:1::11 metric 20 pref medium

fib6_select_path() overwrites whatever fib6_table_lookup() returned and selects a nexthop based on the calculated hash. In this case, both hashes ended up picking the same nexthop.

Quoted 12 lines

Same for a socket. A test tool sends UDP on an AF_INET6/SOCK_RAW/ IPPROTO_UDP socket with IPV6_HDRINCL and SO_BINDTODEVICE=ens31f1np1 (root; the source address is a service address of the host, not the interface address). The option is accepted and readable back:

setsockopt(SO_BINDTODEVICE, "ens31f1np1") = 0
getsockopt(SO_BINDTODEVICE) -> "ens31f1np1"

but the frames leave the sibling interface. tcpdump on both NICs while 3 packets are sent:

Quoted 8 lines

ens31f1np1 (the bound device): 0 packets captured
ens30f1np1: 3 packets captured

    IP6 2001:db8:a::1.41022 > 2606:4700:4700::1111.53: ...

Impact for us: anything that pins traffic to one uplink of a dual-homed BGP host (per-link probes, validation of switch-side policy routing) silently takes another link. We lost a day to it before suspecting the kernel.

I don't think that it matters if you bind to a device or not. AFAICT, with nexthop groups, 6.12.y completely ignores the oif and simply chooses a nexthop based on the calculated hash.

Quoted 10 lines

From reading 6.12 route.c: with nexthop objects, fib6_table_lookup() returns the first nexthop of the group unless the lookup is strict, so the have_oif_match test that this patch adds to ip6_pol_route() only becomes true for nexthop groups once 484bb9d164df ("ipv6: Select best matching nexthop object in fib6_table_lookup()") makes the table lookup prefer the oif-matching nexthop. Its commit message describes it as preparation for this patch. For nexthop-object users this patch is therefore incomplete on its own; please consider queueing both:

Quoted 8 lines

484bb9d164df ipv6: Select best matching nexthop object in fib6_table_lookup() d25e7e9d8a6c ipv6: Honor oif when choosing nexthop for locally generated traffic

https://patch.msgid.link/[email protected]
https://patch.msgid.link/[email protected]

Happy to test a 6.12.y tree with one or both applied on these hosts and report back.

Can you test 7.2.y? It already has both patches.

author maintainer
#251 lore raw

PATCH 1/1 ipv6: addrconf: fix temp address generation after prefix deprecation

In reply to Sasha Levin

From: Fernando Fernandez Mancera <[email protected]>

[ Upstream commit e20d8922aa8fe441d291364c96c2179a005b79ea ]

When a router temporarily deprecates an IPv6 prefix (either by sending a Router Advertisement with Preferred Lifetime = 0 or by letting the lifetime expire) and later restores it, the kernel permanently loses its ability to generate temporary privacy addresses (RFC 8981) for that prefix.

This happens because the address worker attempts to generate a replacement temporary address when the current one nears expiration. As the base prefix is deprecated already, the generation fails after marking the temporary address as already having spawned a replacement (ifp->regen_count++).

When the router eventually restores the prefix, the temporary address becomes active again. However, once it naturally expires, the address worker sees this temporary address already tried to generate one and skips the regeneration.

Fix the issue by resetting the regen_count check of the latest temp address generated for the prefix updated by the incoming RA.

---

LLM Generated explanations, may be completely bogus:

Connection lost, reconnecting to https://agentn.us.api5.cursor.sh
(attempt 1)...
Retry attempt 1...
# Stable Backport Analysis: ipv6: addrconf: fix temp address generation after prefix deprecation

**Local tree:** v6.18.44 (stable/linux-6.18.y, detached HEAD) **Mainline commit:** e20d8922aa8fe (not yet in this tree; git merge- base --is-ancestor returned 1)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Subject line
**Record:** [ipv6: addrconf] [fix] — restores temporary IPv6 privacy address generation after a prefix is deprecated and later restored via Router Advertisement.

### Step 1.2: Tags
**Record:**

| Tag | Value |
|-----|-------|
| Reported-by | Łukasz Stelmach \<[email protected]\> |
| Closes |
https://lore.kernel.org/netdev/87340td30q.fsf%[email protected]/ |
| Suggested-by | Ido Schimmel \<[email protected]\> |
| Reviewed-by | Ido Schimmel \<[email protected]\> |
| Link | https://patch.msgid.link/[email protected]
|
| Signed-off-by | Fernando Fernandez Mancera, Jakub Kicinski |

**Notable patterns:** Real user report; subsystem expert review; no Fixes: tag (expected for manual review); no Cc: stable (expected).

### Step 1.3: Body analysis
**Record:**
- **Bug:** After a router temporarily deprecates an IPv6 prefix (RA with Preferred Lifetime = 0, or natural expiry) and later restores it, the kernel permanently stops generating RFC 8981 temporary privacy addresses for that prefix.
- **Symptom:** Privacy extensions silently stop working for the affected prefix until reboot or manual intervention.
- **Root cause:** addrconf_verify_rtnl() increments regen_count on the temporary address before attempting replacement generation. While the prefix is deprecated, ipv6_create_tempaddr() fails, but regen_count stays non-zero. When the prefix is restored, manage_tempaddrs() updates lifetimes but never clears regen_count, so future regeneration is permanently skipped (!ifp->regen_count guard).

### Step 1.4: Hidden bug fix?
**Record:** No — this is an explicit, well-described functional bug fix, not disguised cleanup.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Inventory
**Record:**
- **File:** net/ipv6/addrconf.c (+9 / −1 lines)
- **Functions:** ipv6_add_addr(), manage_tempaddrs()
- **Scope:** Single-file surgical fix

### Step 2.2: Code flow per hunk

**Hunk 1 (ipv6_add_addr, ~line 1182):**
- **Before:** Temp addresses added to head of tempaddr_list with no comment.
- **After:** Documents that manage_tempaddrs() depends on head insertion order.
- **Path:** Address creation for temporary addresses.

**Hunk 2 (manage_tempaddrs, ~lines 2603–2648):**
- **Before:** On RA lifetime update, temp address lifetimes/flags updated; regen_count never reset.
- **After:** Saves orig_prefered_lft; on first matching temp address for the public prefix, if orig_prefered_lft > 0, resets ift->regen_count = 0.
- **Path:** Normal RA processing when prefix lifetimes are updated.

### Step 2.3: Bug mechanism
**Record:** **Logic / correctness fix** — stale regen_count state on temporary addresses after a failed regeneration attempt during prefix deprecation blocks all future regeneration. The fix clears that one-shot flag when a positive preferred lifetime is received, indicating the prefix is preferred again.

### Step 2.4: Fix quality
**Record:**
- **Obviously correct:** Yes — resets stale state at the exact point prefix restoration is signaled (incoming RA with prefered_lft > 0).
- **Minimal:** Yes — 9 lines of functional change plus 1 comment.
- **Regression risk:** Low — only resets regen_count on the most recent temp address (list head, first ifpub match); new temp addresses already have regen_count == 0; resetting 0 → 0 is a no- op on normal RAs.

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame
**Record:** manage_tempaddrs() introduced in 53bd674915379 (Dec 2013, IFA_F_MANAGETEMPADDR). regen_count logic dates to 291d809ba5c8d (2005). Buggy interaction between deprecation and regen_count is in long-standing SLAAC/privacy code present since privacy extensions were integrated.

### Step 3.2: Fixes: tag
**Record:** N/A — no Fixes: tag. Bug is architectural (missing state reset), not introduced by a single recent commit.

### Step 3.3: Related file history
**Record:** Related prior fixes in this file:
- a11a7f71cac20 — fix generation of new temporary addresses (2017)
- 778964f2fdf05 — fix timing bug in tempaddr regen
- 69172f0bcb6a0 — fix mngtmpaddr deletion creating unwanted temp addresses

This fix is in the same problem domain and is standalone.

### Step 3.4: Author context
**Record:** Fernando Fernandez Mancera is an active ipv6/addrconf contributor (multiple recent sysctl and addrconf fixes in this tree). Ido Schimmel (reviewer) is a networking expert at NVIDIA.

### Step 3.5: Dependencies
**Record:** Part of a 2-patch series ([PATCH 1/2] fix, [PATCH 2/2] selftest). **The kernel fix is self-contained**; patch 2/2 is a fib_tests selftest and is not required for the fix to work. No structural or API prerequisites.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original discussion
**Record:**
- b4 dig -c e20d8922aa8fe:
https://patch.msgid.link/[email protected]
- Series went through v1–v5; committed version is latest (v5).
- Applied to netdev/net-next by Jakub Kicinski (May 27, 2026).
- Reporter Łukasz Stelmach replied with Reviewed-by: Ido Schimmel confirmation in thread.
- **No explicit Cc: stable nomination found** in thread.
- **No NAKs found.**

### Step 4.2: Reviewers
**Record:** CC'd: netdev, linux-kselftest, Paolo Abeni, Eric Dumazet, David Miller, Ido Schimmel, David Ahern — appropriate maintainer coverage. Reviewed-by from Ido Schimmel.

### Step 4.3: Bug report
**Record:** Original report at Closes: URL (lore.kernel.org blocked by bot protection in WebFetch). Reporter is also in-thread confirming the fix. Severity from reporter's perspective: permanent loss of privacy address capability — functional regression with privacy impact.

### Step 4.4: Series context
**Record:** Patch 2/2 adds selftest fib_tests: add temporary IPv6 address renewal test — optional for stable; not a dependency.

### Step 4.5: Stable list history
**Record:** UNVERIFIED — could not search lore stable list (bot protection). No stable nomination found in saved mbox thread.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key functions
**Record:** ipv6_add_addr(), manage_tempaddrs(), (bug trigger in) addrconf_verify_rtnl(), ipv6_create_tempaddr()

### Step 5.2: Callers of manage_tempaddrs()
**Record:**
- addrconf_prefix_rcv_add_addr() — RA prefix processing (primary fix path, line 2779)
- Manual address add with IFA_F_MANAGETEMPADDR (line 3085)
- Address modification path (line 4953)

All are normal networking/SLAAC paths triggered by RAs or admin configuration.

### Step 5.3: Key callees
**Record:** manage_tempaddrs() may call ipv6_create_tempaddr(); uses idev->lock, per-address ift->lock; updates valid_lft, prefered_lft, flags.

### Step 5.4: Reachability
**Record:**

```
Router Advertisement → addrconf_prefix_rcv() →
addrconf_prefix_rcv_add_addr()
  → manage_tempaddrs()  [fix resets regen_count here]

Periodic timer → addrconf_verify_work() → addrconf_verify_rtnl()
  → checks !ifp->regen_count → ipv6_create_tempaddr()  [bug: skips if
stale]
```

**Userspace trigger:** Any host receiving IPv6 RAs with changing prefix lifetimes — common on enterprise/Wi-Fi/mobile networks. Requires use_tempaddr > 0 (privacy extensions enabled; default sysctl is 0, but widely enabled by distributions).

### Step 5.5: Similar patterns
**Record:** ifpub->regen_count = 0 is already reset in addrconf_verify_rtnl() before calling ipv6_create_tempaddr() (line 4673), but the **temporary address's** regen_count was not reset on prefix restoration — asymmetric handling that this patch corrects.

---

## PHASE 6: CROSS-REFERENCE AGAINST LOCAL TREE (6.18.y)

### Step 6.1: Buggy code present?
**Record:** **YES.** Current manage_tempaddrs() at lines 2608–2659 has no regen_count reset. addrconf_verify_rtnl() at line 4657 still gates on !ifp->regen_count. list_add() at line 1183 still adds to list head. Bug is present in v6.18.44.

### Step 6.2: Backport complications
**Record:** **Clean apply expected.** Tested with git cherry-pick --no- commit e20d8922aa8fe → Auto-merging net/ipv6/addrconf.c (no conflicts).

### Step 6.3: Related fixes already present?
**Record:** No equivalent fix in this tree. git log --grep="prefix deprecation" on addrconf.c returned no match for this fix.

---

## PHASE 7: SUBSYSTEM CONTEXT

### Step 7.1: Subsystem criticality
**Record:** **net/ipv6/addrconf** — IMPORTANT (core IPv6 stack; affects all IPv6-capable systems with privacy extensions enabled).

### Step 7.2: Activity
**Record:** Actively maintained; multiple addrconf fixes in recent 6.18.y history (sysctl error handling, UaF fixes, DAD fixes).

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: Who is affected
**Record:** Systems with IPv6 privacy extensions enabled (`use_tempaddr

Quoted 1 line

0`) using SLAAC-managed temporary addresses, on networks where routers

temporarily deprecate prefixes (maintenance, RA reconfiguration, lifetime expiry). Not universal (requires privacy extensions), but affects a meaningful production population.

### Step 8.2: Trigger conditions
**Record:**
1. Prefix deprecated (Preferred Lifetime = 0 or expires)
2. Temp address nears expiration → worker tries regeneration → fails → regen_count stuck
3. Prefix restored via RA with positive preferred lifetime
4. Temp address eventually expires → no new temp address generated

**Likelihood:** Realistic on managed networks. Not timing-dependent race.

### Step 8.3: Failure severity
**Record:** **MEDIUM-HIGH** — no crash, panic, or data corruption, but **permanent functional regression** of RFC 8981 privacy address generation for the affected prefix. Privacy/security degradation; outbound connections using temp addresses may fail after old addresses expire. Workaround requires reboot or toggling use_tempaddr.

### Step 8.4: Risk-benefit
**Record:**
- **Benefit:** HIGH for affected users — restores correct privacy address behavior after a common network event
- **Risk:** LOW — 9-line surgical change, expert-reviewed, applies cleanly
- **Ratio:** Strong benefit, minimal risk

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence summary

**FOR backport:**
- Real user-reported bug with clear reproduction scenario
- Expert-reviewed (Reviewed-by: Ido Schimmel)
- Small, surgical, obviously correct fix
- Buggy code present in 6.18.y; patch applies cleanly
- Restores RFC 8981 compliance — privacy-relevant
- Similar temp-address generation fixes have historically been accepted for stable
- Standalone (selftest patch not required)

**AGAINST backport:**
- Not a crash/Oops/deadlock/CVE — functional regression only
- Requires privacy extensions enabled (use_tempaddr > 0)
- Prefix deprecation/restoration cycle is not every-boot common (but realistic)

**Unresolved:** Original bug-report email body not readable (lore bot protection); no explicit stable nomination in thread.

### Step 9.2: Stable rules checklist

| Criterion | Result |
|-----------|--------|
| 1. Obviously correct and tested? | **PASS** — logic verified in code;
selftest exists in mainline series (patch 2/2) |
| 2. Fixes real bug affecting users? | **PASS** — user-reported,
reproducible scenario |
| 3. Important issue? | **PASS** — permanent privacy-address regression
(functional + privacy impact) |
| 4. Small and contained? | **PASS** — 10 lines, one file |
| 5. No new features/APIs? | **PASS** — state-reset bug fix only |
| 6. Can apply to local tree? | **PASS** — clean cherry-pick to v6.18.44
|

### Step 9.3: Exception categories
**Record:** N/A — standard bug fix, not device-ID/quirk/build/doc exception.

### Step 9.4: Decision rationale

This commit fixes a longstanding logic error where a failed temporary- address regeneration during prefix deprecation leaves regen_count set, permanently blocking future regeneration after the prefix is restored. For 6.18.y users running IPv6 privacy extensions, this is a real, user- visible regression on a normal network event. The fix is minimal, reviewed, applies cleanly, and matches the pattern of prior accepted addrconf temp-address stable fixes.

---

## Verification

- **[Phase 1]** git describe HEAD → v6.18.44; parsed all commit message tags
- **[Phase 2]** Read manage_tempaddrs(), addrconf_verify_rtnl(), ipv6_create_tempaddr() in /home/sasha/linux- autosel-7.0/net/ipv6/addrconf.c; confirmed diff matches described behavior
- **[Phase 3]** git blame -L 2608,2679 → manage_tempaddrs from 2013; git log -S'regen_count' → introduced 2005; related commits a11a7f71cac20, 778964f2fdf05 found
- **[Phase 3]** git merge-base --is-ancestor e20d8922aa8fe HEAD → exit 1 (commit not in tree)
- **[Phase 4]** b4 dig -c e20d8922aa8fe → lore URL found; -a → v1–v5 series; -w → netdev maintainers CC'd; -m → thread saved; no stable CC or NAK in mbox
- **[Phase 4]** WebFetch lore URLs → blocked by Anubis bot protection (UNVERIFIED for original bug-report body)
- **[Phase 5]** grep manage_tempaddrs → 3 call sites; traced RA → addrconf_prefix_rcv_add_addr() → manage_tempaddrs() path; verified !ifp->regen_count guard at line 4657 and ifp->regen_count++ at line 4667
- **[Phase 5]** Verified list_add() at line 1183 adds to head (supports "first match = most recent" logic)
- **[Phase 6]** Confirmed buggy code present (no reset_done/orig_prefered_lft in current tree)
- **[Phase 6]** git cherry-pick --no-commit e20d8922aa8fe → auto- merges cleanly
- **[Phase 7]** git log --oneline -15 -- net/ipv6/addrconf.c → active subsystem
- **[Phase 8]** Assessed severity as MEDIUM-HIGH functional/privacy regression (not crash)

**YES**The background checks finished and line up with the earlier analysis:

- **Commit not in 6.18.y** — e20d8922aa8fe is on master but not an ancestor of the current v6.18.44 tree.
- **Buggy code is present** — no matching fix in this tree; related history only shows older temp-address work (778964f2fdf05, 00b5b7aab9e42, etc.).
- **Verdict stands: YES** — small, reviewed fix for a real privacy- address regression; cherry-picks cleanly onto 6.18.y.

 net/ipv6/addrconf.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)
net/ipv6/addrconf.c +9 -1
index c98b1b919f18c..80706368a303c 100644
@@ -1180,6 +1180,7 @@ ipv6_add_addr(struct inet6_dev *idev, struct ifa6_config *cfg,
 	ipv6_link_dev_addr(idev, ifa);
 
 	if (ifa->flags&IFA_F_TEMPORARY) {
+		/* manage_tempaddrs() relies on addresses being added to the head */
 		list_add(&ifa->tmp_list, &idev->tempaddr_list);
 		in6_ifa_hold(ifa);
 	}
@@ -2610,8 +2611,10 @@ static void manage_tempaddrs(struct inet6_dev *idev,
 			     __u32 valid_lft, __u32 prefered_lft,
 			     bool create, unsigned long now)
 {
-	u32 flags;
+	u32 orig_prefered_lft = prefered_lft;
 	struct inet6_ifaddr *ift;
+	bool reset_done = false;
+	u32 flags;
 
 	read_lock_bh(&idev->lock);
 	/* update all temporary addresses in the list */
@@ -2646,6 +2649,11 @@ static void manage_tempaddrs(struct inet6_dev *idev,
 			prefered_lft = max_prefered;
 
 		spin_lock(&ift->lock);
+		/* the first match is the most recent temp address */
+		if (!reset_done && orig_prefered_lft > 0) {
+			ift->regen_count = 0;
+			reset_done = true;
+		}
 		flags = ift->flags;
 		ift->valid_lft = valid_lft;
 		ift->prefered_lft = prefered_lft;
Signature · 1 line
2.53.0
author maintainer
#252 lore raw

PATCH 1/1 riscv: mm: fix SWIOTLB initialization for systems with DRAM above 4GB

In reply to Sasha Levin

From: Troy Mitchell <[email protected]>

[ Upstream commit cfca5a48b03fbd33c8cb84cb73ee2e34467f3a33 ]

On RISC-V platforms where the entire physical memory (DRAM) resides above the 32-bit address space (i.e., above dma32_phys_limit), the current SWIOTLB initialization logic fails.

This patch addresses two interconnected issues on such platforms:

1. Incorrect 32-bit DMA bounce assumption:
The existing condition max_pfn > PFN_DOWN(dma32_phys_limit) assumes that a 32-bit DMA bounce buffer is required simply because the maximum PFN exceeds the 32-bit limit. However, if all DRAM starts above 4GB, no memory exists below the limit to satisfy this allocation. Fix this by adding a check to ensure memblock_start_of_DRAM() is actually below the 32-bit limit before enforcing 32-bit SWIOTLB.

2. kmalloc() bounce buffer allocation failure on non-coherent systems:
For non-coherent DMA, kmalloc() buffers whose sizes are not cache-line-aligned still require bouncing, even if 32-bit DMA bouncing is skipped. Without the SWIOTLB_ANY flag, swiotlb_init() defaults to allocating from low memory, which fails completely when DRAM only exists in high memory. By appending SWIOTLB_ANY to swiotlb_flags, the allocator is permitted to allocate this bounce buffer from high memory.

With this patch, systems with non-coherent DMA and DRAM entirely above 4GB can successfully map the software IO TLB in high memory and boot normally.

---

LLM Generated explanations, may be completely bogus:

## Phase 1: Commit Message Forensics

**Step 1.1 — Subject line**
Record: [riscv: mm] [fix] — SWIOTLB initialization fails on RISC-V systems whose DRAM is entirely above 4GB.

**Step 1.2 — Tags**
Record:
- **Tested-by:** Anirudh Srinivasan <[email protected]> (real hardware validation)
- **Reviewed-by:** Drew Fustini <[email protected]> (RISC-V maintainer)
- **Signed-off-by:** Troy Mitchell, Paul Walmsley
- **Link:** https://patch.msgid.link/20260727-fix-riscv-
[email protected]
- No Fixes:, Cc: [email protected], or Reported-by: tags
- Notable: hardware-tested on Tenstorrent; reviewed by maintainer

**Step 1.3 — Body analysis**
Record:
- **Bug:** arch_mm_preinit() SWIOTLB setup is wrong when all physical DRAM sits above dma32_phys_limit (4GB).
- **Symptom:** SWIOTLB init fails; affected systems cannot boot normally.
- **Root cause (two parts):**
1. max_pfn > PFN_DOWN(dma32_phys_limit) wrongly forces 32-bit bounce SWIOTLB even when no memory exists below 4GB; memblock_alloc_low() then fails.
2. On non-coherent DMA systems, kmalloc bounce still needs SWIOTLB, but without SWIOTLB_ANY the allocator is restricted to low memory and also fails when DRAM is only in high memory.
- **Version info:** None explicit; reviewer ties regression to dcb2743d1e701.

**Step 1.4 — Hidden bug fix?**
Record: No — this is an explicit boot/DMA initialization bug fix, not disguised cleanup.

---

## Phase 2: Diff Analysis

**Step 2.1 — Inventory**
Record:
- **Files:** arch/riscv/mm/init.c (+12 / −5)
- **Function:** arch_mm_preinit()
- **Scope:** Single-file, surgical fix

**Step 2.2 — Code flow changes**

| Hunk | Before | After |
|------|--------|-------|
| SWIOTLB enable test | `swiotlb = max_pfn > PFN_DOWN(dma32_phys_limit)`
| Also requires `memblock_start_of_DRAM() < dma32_phys_limit` |
| Flags | Always `SWIOTLB_VERBOSE` | `swiotlb_flags` variable; adds
`SWIOTLB_ANY` on kmalloc-bounce path |
| `swiotlb_init()` call | `swiotlb_init(swiotlb, SWIOTLB_VERBOSE)` |
`swiotlb_init(swiotlb, swiotlb_flags)` |

Record: Normal boot path in early MM init; affects all boots on matching RISC-V configs.

**Step 2.3 — Bug mechanism**
Record:
- **Category:** Logic/correctness + memory allocation failure on error- free path
- **Mechanism:** swiotlb_memblock_alloc() uses memblock_alloc_low() unless SWIOTLB_ANY is set (verified in kernel/dma/swiotlb.c:331-334). On high-memory-only platforms, low- memory allocation fails; swiotlb_init_remap() eventually gives up at IO_TLB_MIN_SLABS and returns without initializing SWIOTLB (kernel/dma/swiotlb.c:386-388).

**Step 2.4 — Fix quality**
Record:
- Minimal, obviously correct: only enable 32-bit bounce when DRAM actually spans below 4GB; allow high-memory allocation when needed.
- Same SWIOTLB_ANY pattern already used on x86 and PowerPC.
- Low regression risk: narrow conditions, no API changes.

---

## Phase 3: Git History Investigation

**Step 3.1 — Blame**
Record: Current buggy lines in arch_mm_preinit() are present in this tree at lines 175–193. swiotlb_adjust_size kmalloc-bounce logic dates to dcb2743d1e701 (Mar 2024). Original SWIOTLB init logic dates to ce3aca0465e31 (2021). Bug present since at least v6.10 in equivalent code.

**Step 3.2 — Fixes: tag**
Record: N/A in commit message. Reviewer suggested Fixes: dcb2743d1e701 in lore thread.

**Step 3.3 — Related file history**
Record:
- v6.12: same buggy logic lived in mem_init()
- v6.18/HEAD: logic moved to arch_mm_preinit()
- Fix commit cfca5a48b03fb is **not** in this tree (merge-base --is- ancestor → not ancestor of HEAD)
- Standalone one-patch fix; v1→v3 series on lore, v3 is final

**Step 3.4 — Author context**
Record: Troy Mitchell; Tested-by from Tenstorrent. Paul Walmsley (RISC-V maintainer) committed. Drew Fustini reviewed.

**Step 3.5 — Dependencies**
Record: No prerequisites. Uses memblock_start_of_DRAM(), dma32_phys_limit, SWIOTLB_ANY — all present in this tree. git apply --check on upstream patch succeeds cleanly.

---

## Phase 4: Mailing List and External Research

**Step 4.1 — Original discussion**
Record:
- **URL:** https://patch.msgid.link/20260727-fix-riscv-
[email protected]
- **Series:** v1 (2026-03-31), v3 (2026-07-27); v3 is applied upstream
- **Key feedback:** Drew Fustini: "LGTM and resolves the issue for Linux running on the X280 clusters in the Tenstorrent Blackhole"; suggested Fixes: dcb2743d1e701
- Paul Walmsley: "Thanks, queued for v7.2-rc"
- No NAKs; no explicit stable nomination

**Step 4.2 — Reviewers**
Record: CC'd Paul Walmsley, Palmer Dabbelt, Alexandre Ghiti, linux- riscv, linux-kernel, spacemit list.

**Step 4.3 — Bug report**
Record: No formal bugzilla/syzbot report. Real-world impact confirmed by Tenstorrent tester on Blackhole X280 clusters.

**Step 4.4 — Related patches**
Record: Regression partially from dcb2743d1e701 ("still create swiotlb buffer for kmalloc() bouncing if required"). Fix is self-contained.

**Step 4.5 — Stable list history**
Record: Not searched separately; no stable nomination found in thread. Absence is not a negative signal per review rules.

---

## Phase 5: Code Semantic Analysis

**Step 5.1 — Key functions**
Record: arch_mm_preinit() modified.

**Step 5.2 — Callers**
Record: Called from mm/mm_init.c:2699 during start_kernel() → mm_core_init() → arch_mm_preinit(). Every boot on MMU-enabled kernels.

**Step 5.3 — Callees**
Record: memblock_start_of_DRAM(), swiotlb_adjust_size(), swiotlb_init() → swiotlb_memblock_alloc().

**Step 5.4 — Reachability**
Record: Always executed at boot. Triggered on RISC-V 64-bit (CONFIG_ZONE_DMA32), especially with CONFIG_RISCV_DMA_NONCOHERENT (selected by T-Head/Andes errata Kconfig) and DRAM base ≥ 4GB.

**Step 5.5 — Similar patterns**
Record: arch/arm64/mm/init.c has analogous kmalloc-bounce logic but different DMA limit handling. x86/PowerPC already use SWIOTLB_ANY for high-memory SWIOTLB allocation.

---

## Phase 6: Cross-Reference Against Local Tree

**Step 6.1 — Buggy code exists?**
Record: **YES.** Local tree is **v6.18.44** (git describe HEAD → v6.18.44-2-g1b9e1abadee04). Buggy code confirmed at arch/riscv/mm/init.c:175-193. Fix is not present.

**Step 6.2 — Backport complications**
Record: **Clean apply.** git apply --check on upstream patch passes. No conflicts expected.

**Step 6.3 — Related fixes already present?**
Record: **No.** cfca5a48b03fb / e6709c80ce3b8 not in HEAD.

---

## Phase 7: Subsystem and Maintainer Context

**Step 7.1 — Subsystem criticality**
Record: arch/riscv/mm — **IMPORTANT** (platform-specific boot path, but boot-blocking for affected hardware).

**Step 7.2 — Activity**
Record: RISC-V MM actively developed; arch_mm_preinit() is a recent refactor from mem_init() between 6.12 and 6.18.

---

## Phase 8: Impact and Risk Assessment

**Step 8.1 — Who is affected**
Record: RISC-V 64-bit systems with:
- CONFIG_SWIOTLB + CONFIG_DMA_BOUNCE_UNALIGNED_KMALLOC (selected via RISCV_DMA_NONCOHERENT)
- All DRAM above 4GB
- Examples: Tenstorrent Blackhole X280 clusters

**Step 8.2 — Trigger conditions**
Record: Every boot on matching hardware. Not userspace-triggered; platform configuration dependent. Uncommon globally, but deterministic on affected SoCs.

**Step 8.3 — Failure mode severity**
Record: SWIOTLB fails to initialize → boot failure or broken non- coherent DMA (data corruption risk). **Severity: CRITICAL** for affected platforms.

**Step 8.4 — Risk/benefit**
Record:
- **Benefit:** HIGH for affected RISC-V hardware (enables boot)
- **Risk:** LOW (17-line change, reviewed, tested, existing flags/APIs)
- **Ratio:** Strongly favors backport

---

## Phase 9: Final Synthesis

**Step 9.1 — Evidence summary**

**FOR backport:**
- Real boot blocker on production RISC-V hardware (Tenstorrent Blackhole)
- Small, surgical, reviewed, hardware-tested fix
- Buggy code present in v6.18.44
- Applies cleanly
- Fixes logic error + allocation failure using existing SWIOTLB_ANY
- Non-coherent DMA without SWIOTLB risks data corruption

**AGAINST backport:**
- Affects a narrow hardware subset (non-coherent RISC-V with DRAM > 4GB only)
- No syzbot/CVE report

**Unresolved:** None material to the decision.

**Step 9.2 — Stable rules checklist**
1. Obviously correct and tested? **PASS** (reviewed, Tenstorrent Tested- by)
2. Fixes a real bug affecting users? **PASS** (boot failure on real hardware)
3. Important issue? **PASS** (boot blocker / broken DMA on affected systems)
4. Small and contained? **PASS** (1 file, ~17 lines)
5. No new features or APIs? **PASS** (uses existing SWIOTLB_ANY, memblock_start_of_DRAM())
6. Can apply to local tree? **PASS** (git apply --check succeeds)

**Step 9.3 — Exception category**
Record: N/A (hardware quirk/workaround exception does not apply; this is a boot-path bug fix).

**Step 9.4 — Decision rationale**
On this **6.18.y** tree, the buggy SWIOTLB initialization code is present and the fix is absent. For RISC-V platforms with non-coherent DMA and DRAM entirely above 4GB, the kernel cannot reliably initialize SWIOTLB, preventing normal boot on hardware such as Tenstorrent Blackhole. The fix is minimal, well-reviewed, hardware-tested, and applies cleanly. This is appropriate stable material despite the narrow hardware scope, because it is a deterministic boot blocker with no practical workaround.

---

## Verification

- [Phase 1] Parsed subject, tags, body; identified Tenstorrent Tested-by and Drew Fustini Reviewed-by
- [Phase 2] Diff analysis: 1 file, arch_mm_preinit(), +12/−5; SWIOTLB_ANY + memblock_start_of_DRAM() check
- [Phase 3] git describe HEAD: v6.18.44; buggy code at arch/riscv/mm/init.c:175-193
- [Phase 3] merge-base --is-ancestor cfca5a48b03fb HEAD: not in tree (exit 1)
- [Phase 3] swiotlb_adjust_size present since v6.10; reviewer linked regression to dcb2743d1e701
- [Phase 4] b4 dig -c e6709c80ce3b8: found v3 thread; v1 and v3 revisions
- [Phase 4] b4 dig -w: Paul Walmsley, Palmer Dabbelt, linux-riscv CC'd
- [Phase 4] Mbox: Drew Fustini confirmed fix for Tenstorrent Blackhole X280; suggested Fixes tag; no NAKs
- [Phase 5] arch_mm_preinit() called from mm/mm_init.c:2699 on every boot
- [Phase 5] swiotlb_memblock_alloc() uses memblock_alloc_low() without SWIOTLB_ANY (kernel/dma/swiotlb.c:331-334)
- [Phase 5] Failed allocation path returns without init (kernel/dma/swiotlb.c:386-388)
- [Phase 6] git show v6.18:arch/riscv/mm/init.c: same buggy code in v6.18 base
- [Phase 6] git apply --check on upstream patch: clean apply (exit 0)
- [Phase 6] memblock_start_of_DRAM() and SWIOTLB_ANY exist in tree
- [Phase 6] CONFIG_DMA_BOUNCE_UNALIGNED_KMALLOC selected for RISC-V non-coherent (arch/riscv/Kconfig:361)
- [Phase 8] Failure mode: SWIOTLB init failure → boot failure / broken DMA; severity CRITICAL for affected platforms

**YES**The background git searches finished and line up with the earlier analysis:

- The fix exists in the repo as cfca5a48b03fb / e6709c80ce3b8, but it is **not** in this **6.18.44** tree.
- The buggy SWIOTLB logic **is** present here (including the kmalloc- bounce path from dcb2743d1e701).
- The regression has been in place since at least **v6.10**; **v6.18** still has the bug.
- The upstream patch applies cleanly to the current tree.

**Verdict for 6.18.y: YES** — this is a boot-blocking fix for non- coherent RISC-V systems with DRAM entirely above 4GB (e.g. Tenstorrent Blackhole), and it is appropriate for stable backport.The search for memblock_start_of_DRAM() < dma32_phys_limit found no matches in this tree, which confirms the fix is **not** already present in **6.18.44**. That supports the earlier **YES** backport recommendation.

 arch/riscv/mm/init.c | 17 ++++++++++++-----
 1 file changed, 12 insertions(+), 5 deletions(-)
arch/riscv/mm/init.c +12 -5
index 557bf160b503a..59f9bf2fdd300 100644
@@ -172,7 +172,9 @@ static void print_vm_layout(void) { }
 
 void __init arch_mm_preinit(void)
 {
-	bool swiotlb = max_pfn > PFN_DOWN(dma32_phys_limit);
+	bool swiotlb = max_pfn > PFN_DOWN(dma32_phys_limit) &&
+		       memblock_start_of_DRAM() < dma32_phys_limit;
+	unsigned int swiotlb_flags = SWIOTLB_VERBOSE;
 #ifdef CONFIG_FLATMEM
 	BUG_ON(!mem_map);
 #endif /* CONFIG_FLATMEM */
@@ -180,17 +182,22 @@ void __init arch_mm_preinit(void)
 	if (IS_ENABLED(CONFIG_DMA_BOUNCE_UNALIGNED_KMALLOC) && !swiotlb &&
 	    dma_cache_alignment != 1) {
 		/*
-		 * If no bouncing needed for ZONE_DMA, allocate 1MB swiotlb
-		 * buffer per 1GB of RAM for kmalloc() bouncing on
-		 * non-coherent platforms.
+		 * No 32-bit DMA bouncing needed (either all DRAM is within
+		 * the 32-bit limit, or it all starts above it), but
+		 * kmalloc() buffers whose sizes are not cache-line-aligned
+		 * still require bouncing for non-coherent DMA.  Use
+		 * SWIOTLB_ANY so that the buffer can be allocated from high
+		 * memory when DRAM starts above dma32_phys_limit.  Allocate
+		 * ~1 MB per 1 GB of RAM.
 		 */
 		unsigned long size =
 			DIV_ROUND_UP(memblock_phys_mem_size(), 1024);
 		swiotlb_adjust_size(min(swiotlb_size_or_default(), size));
 		swiotlb = true;
+		swiotlb_flags |= SWIOTLB_ANY;
 	}
 
-	swiotlb_init(swiotlb, SWIOTLB_VERBOSE);
+	swiotlb_init(swiotlb, swiotlb_flags);
 
 	print_vm_layout();
 }
Signature · 1 line
2.53.0
author maintainer
#253 lore raw

PATCH 1/1 ACPICA: validate handler object type in two places

In reply to Sasha Levin

From: ikaros <[email protected]>

[ Upstream commit c5296da2d516707862f8a2dbb4b515f777e5294f ]

ACPICA: validate handler object type in acpi_ev_has_default_handler() and acpi_ev_find_region_handler().

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: ACPICA handler object type validation

**Local tree:** v6.18.44 (stable/linux-6.18.y, make kernelversion = 6.18.44)
**Candidate commit (mainline):** c5296da2d5167 — same diff as upstream ACPICA f6fc648a1389
**Status in this tree:** Fix is **not** present; vulnerable code is present.

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Subject line
**Record:** [ACPICA] [validate] validate handler object type in acpi_ev_has_default_handler() and acpi_ev_find_region_handler()

### Step 1.2: Tags
**Record:**
- **Link:** https://github.com/acpica/acpica/commit/f6fc648a1389
- **Link:**
https://patch.msgid.link/[email protected]
- **Signed-off-by:** ikaros \<[email protected]\>
- **Signed-off-by:** Rafael J. Wysocki \<[email protected]\>
- No Fixes:, Reported-by:, Cc: [email protected], Reviewed- by:, Tested-by:, or Acked-by: tags in the commit message
- Notable: upstream ACPICA issue #1132 documents an ASAN global-buffer- overflow; author is the issue reporter

### Step 1.3: Body text
**Record:**
- **Bug:** Handler linked lists walked via common_notify.handler assume every node is ACPI_TYPE_LOCAL_ADDRESS_HANDLER, but the list can contain objects of another type (corrupt/crafted ACPI state).
- **Symptom:** Out-of-bounds read when accessing address_space.space_id or address_space.next on a non-address- handler object (ASAN: global-buffer-overflow, 8-byte read in AcpiEvFindRegionHandler).
- **Root cause:** Missing type check before interpreting union members as address_space fields.
- **Version info:** None in commit message; upstream ACPICA fix dated 2026-03-20.

### Step 1.4: Hidden bug fix?
**Record:** Yes — although the subject says “validate,” this is a memory-safety fix preventing buffer overflow on handler-list traversal, not cosmetic cleanup.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Inventory
**Record:**
- **Files:** drivers/acpi/acpica/evhandler.c (+11 lines, 0 removed)
- **Functions modified:** acpi_ev_has_default_handler(), acpi_ev_find_region_handler()
- **Scope:** Single-file, surgical fix

### Step 2.2: Code flow change
**Record:**
- **Hunk 1 (acpi_ev_has_default_handler):** Before — walked handler list unconditionally using address_space fields. After — breaks loop if handler_obj->common.type != ACPI_TYPE_LOCAL_ADDRESS_HANDLER.
- **Hunk 2 (acpi_ev_find_region_handler):** Same type check added before space_id comparison and next pointer chase.
- **Paths affected:** Normal ACPI handler lookup during region initialization, handler installation, and namespace walks.

### Step 2.3: Bug mechanism
**Record:**
- **Category:** Memory safety / buffer overflow (out-of-bounds read)
- **Mechanism:** union acpi_operand_object is accessed as address_space without verifying common.type. Wrong type → wrong union layout → read past valid object memory via address_space.space_id (1 byte + padding) or address_space.next (8-byte pointer read per ASAN report).

### Step 2.4: Fix quality
**Record:**
- Fix is minimal and obviously correct: common_notify.handler is documented as the address-space handler list; only ACPI_TYPE_LOCAL_ADDRESS_HANDLER objects belong there.
- **Regression risk:** Very low. On type mismatch, loop terminates (same as list end). Worst case: handler not found where list was already corrupt — far safer than OOB read.
- No API changes, no locking changes.

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame
**Record:**
- acpi_ev_has_default_handler walk loop: 42f8fb75c43cc6 (Bob Moore, 2013-01-11) — long-standing code
- acpi_ev_find_region_handler: 7b73806485ada (Bob Moore, 2015-12-29), introduced by f31a99cefd05f “Deploys acpi_ev_find_region_handler()”
- Bug predates 6.18.y branch by many years

### Step 3.2: Fixes: tag
**Record:** N/A — no Fixes: tag. Upstream ACPICA references GitHub issue #1132 (ASAN global-buffer-overflow in AcpiEvFindRegionHandler).

### Step 3.3: Related file history
**Record:**
- Recent evhandler.c changes in this tree are copyright updates and unrelated fixes (e.g. c27f3d011b085 I2C/GPIO race).
- aa6abd2be1cc7 (2015) moved address handlers to common_notify.handler — architectural context, not the bug introducer.
- Fix is **standalone**; patch 18/27 in the ACPICA sync series but does not depend on patches 1–17.

### Step 3.4: Author context
**Record:** ikaros reported the upstream ACPICA bug and authored 14 hardening patches in the same series. Rafael J. Wysocki (ACPI maintainer) signed off and committed to mainline.

### Step 3.5: Dependencies
**Record:** None. Uses ACPI_TYPE_LOCAL_ADDRESS_HANDLER (defined in include/acpi/actypes.h as 0x18 in this tree). No prerequisite commits required.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original discussion
**Record:**
- **URL:** https://patch.msgid.link/[email protected]
- **Series:** [PATCH v1 18/27] in “ACPI: ACPICA 20260408” series by Rafael Wysocki
- **Revisions:** v1 only found via b4 dig -a
- No explicit stable nomination or NAK found in thread grep
- Cover letter groups this with other ikaros buffer-overflow / memory- safety hardening patches

### Step 4.2: Reviewers
**Record:** CC’d: Rafael J. Wysocki, linux-acpi, LKML, Saket Dumbre, Pawel Chmielewski (Intel ACPICA maintainers). Signed-off-by from Rafael J. Wysocki.

### Step 4.3: Bug report
**Record:**
- **GitHub issue #1132:** ASAN global-buffer-overflow, READ of 8 bytes in AcpiEvFindRegionHandler
- **Reproducer:** ./acpiexec -m issue26.aml (crafted AML)
- **Severity:** Memory safety bug with concrete ASAN proof

### Step 4.4: Related patches
**Record:** Part of 27-patch ACPICA sync; 13 other ikaros hardening patches in same series. This patch is independently applicable.

### Step 4.5: Stable list discussion
**Record:** No [email protected] discussion found for this specific patch (lore blocked for web fetch; mbox grep found no “Cc: stable”).

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key functions
**Record:** acpi_ev_has_default_handler(),
acpi_ev_find_region_handler()

### Step 5.2: Callers
**Record:**
- acpi_ev_has_default_handler() ← acpi_ev_initialize_op_regions() in evregion.c (boot-time _REG method execution)
- acpi_ev_find_region_handler() ←
- acpi_ev_install_handler() (namespace walk during handler install)
- acpi_ev_install_space_handler() (handler installation)
- acpi_ev_region_init() path in evrgnini.c (region attachment during init)
- dbdisply.c (debug only, CONFIG_ACPI_DEBUG)

### Step 5.3: Callees
**Record:** Functions read obj_desc->common_notify.handler, then walk list accessing address_space.space_id, handler_flags, next. No allocation in the fixed loops.

### Step 5.4: Reachability
**Record:**
- **Boot path:** tbxfload.c → acpi_ev_install_region_handlers(); nsinit.c → acpi_ev_initialize_op_regions()
- **Runtime:** acpi_install_address_space_handler() used by EC, GPIO, I2C, PMIC, PCC, and platform drivers
- **Trigger:** Corrupt/crafted ACPI AML that leaves non-address-handler objects on the handler list
- **Userspace:** Not directly syscall-reachable, but ACPI tables are firmware-controlled; root can override tables on some systems

### Step 5.5: Similar patterns
**Record:** Other ACPICA code validates common.type before union access (e.g. exdump.c, utdecode.c, nsobject.c). evxfregn.c and dbdisply.c still walk handler lists without type checks — fix is partial but addresses the two functions named in the ASAN stack trace.

---

## PHASE 6: CROSS-REFERENCE AGAINST LOCAL TREE (6.18.44)

### Step 6.1: Buggy code present?
**Record:** **Yes.** Current evhandler.c lines 132–141 and 294–305 lack type validation. Bug present since at least 2013/2015.

### Step 6.2: Backport complications
**Record:** **Clean apply expected.** Mainline diff applies identically to this tree’s evhandler.c (verified via git show c5296da2d5167 against current file).

### Step 6.3: Related fixes already present?
**Record:** **No.** git grep 'validate handler object type' returns nothing in this tree. Fix exists on all-next as c5296da2d5167 but not on stable/linux-6.18.y at v6.18.44.

---

## PHASE 7: SUBSYSTEM CONTEXT

### Step 7.1: Subsystem and criticality
**Record:** **ACPI / ACPICA events subsystem** — **CORE** (affects all ACPI-enabled x86/ARM systems at boot and during device operation).

### Step 7.2: Activity
**Record:** Actively maintained; periodic ACPICA upstream syncs. Long- standing handler-list code with recent hardening focus from fuzzing.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: Who is affected
**Record:** All systems with CONFIG_ACPI during ACPI table load, operation-region initialization, and address-space handler installation.

### Step 8.2: Trigger conditions
**Record:** Handler list containing a non-ACPI_TYPE_LOCAL_ADDRESS_HANDLER object — demonstrated with crafted AML (issue26.aml). Uncommon in the field but plausible with malicious/corrupt ACPI tables or interpreter bugs. Requires ACPI processing context (boot or module load), not arbitrary unprivileged syscall.

### Step 8.3: Failure mode severity
**Record:** Out-of-bounds **read** (8 bytes) → kernel oops/crash or information leak. **Severity: HIGH** (memory safety in core boot path).

### Step 8.4: Risk-benefit
**Record:**
- **Benefit:** HIGH — prevents OOB read in widely used ACPI core code
- **Risk:** VERY LOW — 11-line defensive check, ACPI maintainer-reviewed
- **Ratio:** Strong benefit, minimal risk

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence summary

**FOR backport:**
- ASAN-confirmed global-buffer-overflow (upstream issue #1132)
- Buggy code present in 6.18.44 since 2013/2015
- Small, surgical, standalone fix (+11 lines, one file)
- ACPI maintainer signed off
- Affects boot-time and runtime ACPI handler paths
- Consistent with ACPICA hardening pattern (type check before union access)

**AGAINST backport:**
- Reproducer uses crafted AML via acpiexec — field trigger frequency uncertain
- Fix does not cover all similar walks (evxfregn.c, dbdisply.c) — incomplete hardening
- Part of larger 27-patch series (though this patch is independent)

**Unresolved:**
- No kernel-runtime reproducer confirmed (only upstream acpiexec tool)
- No explicit stable nomination in mailing list thread

### Step 9.2: Stable rules checklist
1. Obviously correct and tested? **PASS** — logic is straightforward; ASAN-tested upstream; maintainer SOB
2. Fixes a real bug affecting users? **PASS** — ASAN OOB read with concrete reproducer
3. Important issue? **PASS** — memory safety in ACPI core (HIGH severity)
4. Small and contained? **PASS** — 11 lines, one file, two functions
5. No new features or APIs? **PASS** — defensive validation only
6. Can apply to local tree? **PASS** — clean apply to 6.18.44

### Step 9.3: Exception categories
**Record:** None (not device ID, quirk, DT, build, or docs). Qualifies as a core memory-safety bug fix.

### Step 9.4: Decision rationale
For **this** 6.18.y tree, the vulnerable handler-list walk code exists and is reachable during ACPI initialization and handler management. The fix prevents a demonstrated out-of-bounds read with negligible regression risk. Incomplete coverage of similar walks elsewhere does not diminish the value of fixing the two functions implicated in the ASAN report.

---

## Verification

- **[Phase 1]** Parsed subject, tags, body from commit c5296da2d5167 and user-provided message
- **[Phase 1]** Fetched upstream ACPICA commit and issue #1132 from GitHub — confirmed ASAN global-buffer-overflow
- **[Phase 2]** Analyzed diff: +11 lines in evhandler.c, two type- check hunks
- **[Phase 3]** git blame: buggy loops from 2013 and 2015
- **[Phase 3]** git show aa6abd2be1cc7: common_notify.handler used for address-space handlers since 2015
- **[Phase 3]** No Fixes: tag to follow
- **[Phase 3]** Fix not in stable tree; present on all-next as c5296da2d5167
- **[Phase 4]** b4 dig -c c5296da2d5167: found lore thread at patch.msgid.link
- **[Phase 4]** b4 dig -a: v1, patch 18/27 in ACPICA 20260408 series
- **[Phase 4]** b4 dig -w: Rafael Wysocki, linux-acpi, Intel maintainers CC’d
- **[Phase 4]** Downloaded mbox; grep found no stable nomination or NAK for this patch
- **[Phase 5]** grep callers: evregion.c, evrgnini.c, evhandler.c, dbdisply.c
- **[Phase 5]** Traced boot path: tbxfload.c → acpi_ev_install_region_handlers(), nsinit.c → acpi_ev_initialize_op_regions()
- **[Phase 5]** grep acpi_install_address_space_handler: used by EC, GPIO, I2C, PMIC, platform drivers
- **[Phase 6]** git describe HEAD: v6.18.44 on stable/linux-6.18.y
- **[Phase 6]** Read current evhandler.c: vulnerable code confirmed at lines 132–141, 294–305
- **[Phase 6]** git show c5296da2d5167: diff applies cleanly to current file
- **[Phase 6]** grep 'validate handler object type': no match in tree
- **[Phase 8]** GitHub issue #1132: ASAN READ 8 bytes, reproducer acpiexec -m issue26.aml

---

**YES**The background git log --grep search timed out on this repo, so I killed it and used targeted lookups instead (b4 dig, git show c5296da2d5167, direct file reads). That was enough to finish the analysis.

**Verdict for 6.18.44:** backport **YES** — the fix prevents an ASAN- confirmed out-of-bounds read when walking ACPI address-space handler lists, and it applies cleanly as an 11-line change to evhandler.c.

 drivers/acpi/acpica/evhandler.c | 11 +++++++++++
 1 file changed, 11 insertions(+)
drivers/acpi/acpica/evhandler.c +11 -0
index 5a35dae945e20..f16c1148e602e 100644
@@ -130,6 +130,14 @@ acpi_ev_has_default_handler(struct acpi_namespace_node *node,
 		/* Walk the linked list of handlers for this object */
 
 		while (handler_obj) {
+
+			/* Validate handler object type before accessing fields */
+
+			if (handler_obj->common.type !=
+			    ACPI_TYPE_LOCAL_ADDRESS_HANDLER) {
+				break;
+			}
+
 			if (handler_obj->address_space.space_id == space_id) {
 				if (handler_obj->address_space.handler_flags &
 				    ACPI_ADDR_HANDLER_DEFAULT_INSTALLED) {
@@ -292,6 +300,9 @@ union acpi_operand_object *acpi_ev_find_region_handler(acpi_adr_space_type
 	/* Walk the handler list for this device */
 
 	while (handler_obj) {
+		if (handler_obj->common.type != ACPI_TYPE_LOCAL_ADDRESS_HANDLER) {
+			break;
+		}
 
 		/* Same space_id indicates a handler is installed */
 
Signature · 1 line
2.53.0
author maintainer
#254 lore raw

PATCH 1/1 wifi: iwlwifi: mvm: validate sta_id in BA window status notif

In reply to Sasha Levin

From: Emmanuel Grumbach <[email protected]>

[ Upstream commit 6aa77efaea9efea92e3090c35ad348fd759a3cf3 ]

BA_WINDOW_STATUS_NOTIFICATION_ID extracts a 5-bit sta_id from the firmware notification and uses it to index fw_id_to_mac_id[] without bounds checking. Validate sta_id before array access to prevent out-of-bounds indexing.

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: wifi: iwlwifi: mvm: validate sta_id in BA window status notif

**Local tree:** v6.18.44-1-g2736c32da98b9 (Makefile: 6.18.44)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Parse the subject line
**Record:** [wifi: iwlwifi: mvm] [validate] — Add bounds validation for sta_id extracted from a BA window status firmware notification before indexing fw_id_to_mac_id[].

### Step 1.2: Parse all commit message tags
**Record:**
- **Fixes:** — not present (expected for manual review)
- **Reported-by:** — none
- **Tested-by:** — none
- **Reviewed-by:** — none
- **Acked-by:** — none
- **Link:** https://patch.msgid.link/20260714141909.2e97f337f3cb... (patch submission link)
- **Cc: [email protected]** — not present (expected)
- **Signed-off-by:** Emmanuel Grumbach <[email protected]> (author)
- **Signed-off-by:** Miri Korenblit <[email protected]> (iwlwifi maintainer)
- **Assisted-by:** GitHubCopilot:gpt-5.3-codex

Notable: maintainer sign-off from Miri Korenblit; no syzbot/user crash report in the message.

### Step 1.3: Analyze commit body
**Record:**
- **Bug:** BA_WINDOW_STATUS_NOTIFICATION_ID carries a 5-bit sta_id in ra_tid; the handler indexes fw_id_to_mac_id[sta_id] without validating it.
- **Symptom/failure mode:** Out-of-bounds array indexing when firmware sends an invalid sta_id.
- **Version info:** none in message.
- **Root cause:** Missing bounds check against mvm->fw->ucode_capa.num_stations before array access.

### Step 1.4: Detect hidden bug fixes
**Record:** Not disguised — this is an explicit defensive validation fix. It closes a memory-safety hole in a firmware-notification handler, consistent with other iwlwifi validation patches already in this tree.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Inventory the changes
**Record:**
- **Files:** drivers/net/wireless/intel/iwlwifi/mvm/rx.c (+5 lines)
- **Function:** iwl_mvm_window_status_notif()
- **Scope:** Single-file, surgical fix in one loop iteration

### Step 2.2: Code flow change
**Record:**
- **Hunk (lines ~1225–1227):** Before: extract sta_id from ratid, immediately rcu_dereference(mvm->fw_id_to_mac_id[sta_id]). After: if sta_id >= num_stations, log via IWL_FW_CHECK and continue.
- **Path affected:** Firmware RX notification handler for block-ack window status (powersave/reordering path).
- **Context:** Normal RX handler loop, not init/teardown.

### Step 2.3: Bug mechanism
**Record:**
- **Category:** Buffer overflow / out-of-bounds access (memory safety).
- **Mechanism:**
- BA_WINDOW_STATUS_STA_ID_MSK is 5 bits → sta_id range 0–31

    (`fw/api/rx.h`).
  - `fw_id_to_mac_id[]` size is `IWL_STATION_COUNT_MAX` = **16**
    (`fw/api/mac.h`).
  - `num_stations` is capped at 16 by firmware TLV parsing (`iwl-
    drv.c`).
  - Without validation, `sta_id` values ≥ `num_stations` (and especially
    16–31) can index past the 16-element array.
  - A garbage pointer from OOB memory may pass `IS_ERR_OR_NULL()` and
    reach `ieee80211_mark_rx_ba_filtered_frames()`.

### Step 2.4: Fix quality
**Record:**
- **Quality:** High — matches existing driver patterns (iwl_mvm_sta_from_staid_rcu(), iwl_mvm_sta_pm_notif(), MLD RX handlers using IWL_FW_CHECK).
- **Regression risk:** Very low — only skips invalid entries; no API/locking changes.
- **Red flags:** None.

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame changed lines
**Record:** Shallow repository (git rev-parse --is-shallow-repository → true). git blame attributes iwl_mvm_window_status_notif() to merge commit 5d324e5159d9e; exact introduction commit not available in this checkout. Function and buggy pattern are present in tag 1efe5d048a391 (Linux 6.18.44).

### Step 3.2: Follow Fixes: tag
**Record:** N/A — no Fixes: tag in the commit message.

### Step 3.3: File history for related changes
**Record:** Recent iwlwifi stable commits in this tree include similar validation fixes:
- 2d5dec517b539 — wake packet notification bounds fix
- dd90880eb5ec5 — OOB read in iwl_mvm_nd_match_info_handler()
- 1de92789ce31e — BA session handler sta_mask validation (MLD)

Standalone fix; not part of a multi-patch series in this tree.

### Step 3.4: Author's other commits
**Record:** Emmanuel Grumbach is a long-time iwlwifi developer. Miri Korenblit is iwlwifi maintainer (signed off). Shallow history limits author-specific log on rx.c.

### Step 3.5: Prerequisites
**Record:** No dependencies found. IWL_FW_CHECK exists in fw/dbg.h. iwl_mvm_window_status_notif and BA_WINDOW_STATUS_NOTIFICATION_ID handler are present. git apply --check confirms the patch applies cleanly to HEAD.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original patch discussion
**Record:** b4 dig -c HEAD did not match this patch (matched unrelated OF overlay patch). b4 dig by subject failed (wrong usage). Lore.kernel.org and patch.msgid.link blocked by Anubis bot protection — **could not read thread discussion**.

### Step 4.2: Reviewers from b4 dig -w
**Record:** Not retrieved — patch-specific b4 dig match not found.

### Step 4.3: Bug report
**Record:** No Reported-by: or syzbot link. Bug identified by static/code review (Copilot-assisted per message). Severity is theoretical until bad firmware data arrives, but consequences are real (OOB access).

### Step 4.4: Related patches/series
**Record:** Part of iwlwifi's ongoing firmware-input validation theme; similar fixes already backported to 6.18.y (see Phase 3.3). Appears standalone.

### Step 4.5: Stable mailing list history
**Record:** Could not search lore (blocked). Similar iwlwifi OOB fixes in this tree were explicitly nominated with Cc: [email protected] (e.g. dd90880eb5ec5).

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key functions
**Record:** iwl_mvm_window_status_notif() — only function modified.

### Step 5.2: Callers
**Record:** Registered in
drivers/net/wireless/intel/iwlwifi/mvm/ops.c:

```348:350:drivers/net/wireless/intel/iwlwifi/mvm/ops.c
        RX_HANDLER(BA_WINDOW_STATUS_NOTIFICATION_ID,
                   iwl_mvm_window_status_notif, RX_HANDLER_SYNC,
                   struct iwl_ba_window_status_notif),
```

Called from iwlwifi firmware RX dispatch when firmware sends BA_WINDOW_STATUS_NOTIFICATION_ID (0x13). Reachable during normal WiFi operation with block-ack sessions (e.g. after D0i3 per notification semantics).

### Step 5.3: Callees
**Record:** IWL_FW_CHECK(), rcu_dereference(), IS_ERR_OR_NULL(), ieee80211_mark_rx_ba_filtered_frames(), le16_to_cpu(), le64_to_cpu(), le32_to_cpu().

### Step 5.4: Call chain / reachability
**Record:** Firmware → iwl trans RX → MVM RX handler table → iwl_mvm_window_status_notif(). Triggered by firmware notifications during WiFi RX/reordering. Not directly userspace-triggered, but firmware bugs/corruption are realistic (similar fixes already accepted for iwlwifi in stable).

### Step 5.5: Similar patterns
**Record:** Same sta_id >= num_stations check exists in:
- iwl_mvm_sta_from_staid_rcu() (mvm.h:1354)
- iwl_mvm_sta_pm_notif() (mac80211.c:3366)
- RX MPDU path (rx.c:369)
- MLD RX path (mld/rx.c:1551-1554)

This handler was the outlier missing the check.

---

## PHASE 6: CROSS-REFERENCING AGAINST LOCAL TREE (6.18.44)

### Step 6.1: Does buggy code exist?
**Record:** **YES.** In rx.c at lines 1225–1227, sta_id is used to index fw_id_to_mac_id[sta_id] without validation. Confirmed in tag 1efe5d048a391 (Linux 6.18.44). Fix is **not** yet applied in this checkout.

### Step 6.2: Backport complications
**Record:** **Clean apply** — git apply --check succeeded with no conflicts.

### Step 6.3: Related fixes already present?
**Record:** No duplicate fix for this specific path. Related iwlwifi firmware-validation fixes are already in 6.18.y (see Phase 3.3).

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

### Step 7.1: Subsystem criticality
**Record:** **IMPORTANT** — drivers/net/wireless/intel/iwlwifi (Intel WiFi, widely deployed on laptops/desktops). CONFIG_IWLWIFI / CONFIG_IWLMVM.

### Step 7.2: Subsystem activity
**Record:** Active — multiple iwlwifi fixes backported to 6.18.y in recent history (validation, race fixes, OOB fixes).

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: Who is affected
**Record:** Users with Intel WiFi (iwlmvm) hardware using block-ack reordering. Config-specific (CONFIG_IWLWIFI + CONFIG_IWLMVM), but that is very common on Intel platforms.

### Step 8.2: Trigger conditions
**Record:** Firmware sends BA_WINDOW_STATUS_NOTIFICATION with `sta_id

Quoted 1 line

= num_stations` (or ≥16 with 5-bit encoding). Uncommon in normal

operation, but plausible with firmware bugs or corrupted notifications. Not directly userspace-triggered.

### Step 8.3: Failure mode severity
**Record:** Out-of-bounds read of fw_id_to_mac_id[] → possible invalid sta pointer → kernel oops/corruption in ieee80211_mark_rx_ba_filtered_frames(). **Severity: HIGH** (memory safety / potential crash).

### Step 8.4: Risk-benefit
**Record:**
- **Benefit:** HIGH — closes a real OOB indexing bug in a live RX path.
- **Risk:** VERY LOW — 5-line validation, established pattern.
- **Ratio:** Strongly favors backport.

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence summary

**FOR backport:**
- Real out-of-bounds indexing bug (5-bit sta_id vs 16-element array)
- Memory-safety issue with crash/corruption potential
- Small, obviously correct, matches existing driver conventions
- Applies cleanly to 6.18.44
- Buggy code confirmed present; fix not yet applied
- Similar iwlwifi firmware-validation fixes already backported to this tree
- iwlwifi maintainer sign-off

**AGAINST backport:**
- No user crash report or syzbot reproduction in commit message
- Trigger requires bad firmware notification data (uncommon)
- Shallow git history prevents dating when the handler was introduced

**Unresolved:**
- Lore review thread inaccessible (Anubis)
- Exact upstream commit hash not in this shallow tree

### Step 9.2: Stable rules checklist
1. Obviously correct and tested? **PASS** — pattern used throughout iwlwifi; maintainer SOB; no logic concerns.
2. Fixes a real bug? **PASS** — missing bounds check on firmware-derived index.
3. Important issue? **PASS** — OOB access / potential kernel crash (HIGH).
4. Small and contained? **PASS** — 5 lines, one function.
5. No new features/APIs? **PASS** — defensive validation only.
6. Can apply to local tree? **PASS** — clean apply verified; code exists.

### Step 9.3: Exception categories
**Record:** Not a device-ID/quirk/DT/docs/build fix. Standard memory- safety bug fix.

### Step 9.4: Decision rationale
For **Linux 6.18.44**, iwl_mvm_window_status_notif() indexes a 16-element array using a 5-bit firmware-provided sta_id without validation. This is a clear out-of-bounds access bug. The fix is minimal, follows established iwlwifi patterns, applies cleanly, and aligns with other firmware-input validation fixes already accepted into 6.18.y.

---

## Verification

- [Phase 1] Parsed subject, tags, body from user-provided commit message
- [Phase 1] Confirmed no Reported-by/syzbot; maintainer SOB present
- [Phase 2] Read rx.c:1193-1238 — buggy code without IWL_FW_CHECK confirmed
- [Phase 2] Read fw/api/rx.h:972-976 — 5-bit sta_id mask confirmed
- [Phase 2] Read fw/api/mac.h:19 — IWL_STATION_COUNT_MAX = 16
- [Phase 2] Read mvm.h:1008 — fw_id_to_mac_id[IWL_STATION_COUNT_MAX]
- [Phase 2] Read fw/dbg.h:334-342 — IWL_FW_CHECK macro behavior
- [Phase 3] git rev-parse --is-shallow-repository → true
- [Phase 3] git blame -L 1193,1238 rx.c — shallow history only
- [Phase 3] git show 1efe5d048a391:rx.c — buggy code in 6.18.44 tag
- [Phase 3] git log --oneline -20 -- drivers/net/wireless/intel/iwlwifi/ — related fixes found
- [Phase 3] git show 2d5dec517b539, dd90880eb5ec5 — similar stable backports
- [Phase 3] git apply --check — patch applies cleanly
- [Phase 4] b4 dig -c HEAD — no match for this patch
- [Phase 4] WebFetch lore.kernel.org — blocked by Anubis (UNVERIFIED:
review discussion)
- [Phase 4] WebFetch patch.msgid.link — blocked by Anubis (UNVERIFIED:
thread content)
- [Phase 5] grep iwl_mvm_window_status_notif — caller in ops.c:348-350
- [Phase 5] Compared with mvm.h:1354, mac80211.c:3366, mld/rx.c:1551
- [Phase 6] git describe HEAD → v6.18.44-1-g2736c32da98b9
- [Phase 6] Makefile → 6.18.44
- [Phase 6] Buggy code present; fix absent in HEAD
- [Phase 8] OOB mechanism verified: 5-bit index (0–31) vs 16-element array

**YES**

 drivers/net/wireless/intel/iwlwifi/mvm/rx.c | 5 +++++
 1 file changed, 5 insertions(+)
drivers/net/wireless/intel/iwlwifi/mvm/rx.c +5 -0
index 8c1bb3a7ffcaa..1e6d06bb674c1 100644
@@ -1224,6 +1224,11 @@ void iwl_mvm_window_status_notif(struct iwl_mvm *mvm,
 		/* get the station */
 		sta_id = (ratid & BA_WINDOW_STATUS_STA_ID_MSK)
 			 >> BA_WINDOW_STATUS_STA_ID_POS;
+		if (IWL_FW_CHECK(mvm,
+				 sta_id >= mvm->fw->ucode_capa.num_stations,
+				 "Invalid sta id (%d) in BA window status notification\n",
+				 sta_id))
+			continue;
 		sta = rcu_dereference(mvm->fw_id_to_mac_id[sta_id]);
 		if (IS_ERR_OR_NULL(sta))
 			continue;
Signature · 1 line
2.53.0
author maintainer
#255 lore raw

PATCH 1/1 btrfs: balance: fix potential bg lookup failure in btrfs_may_alloc_data_chunk()

In reply to Sasha Levin

From: ZhengYuan Huang <[email protected]>

[ Upstream commit 18d32b0013efba19f7ad3e5b08d7aee813d604a6 ]

[BUG]
Running btrfs balance can trigger a null-ptr-deref before relocating a data chunk when metadata corruption leaves a chunk in the chunk tree without a corresponding block group in the in-memory cache:

  KASAN: null-ptr-deref in range [0x0000000000000088-0x000000000000008f]
  RIP: 0010:btrfs_may_alloc_data_chunk+0x40/0x1c0 fs/btrfs/volumes.c:3601
  Call Trace:
    __btrfs_balance fs/btrfs/volumes.c:4217 [inline]
    btrfs_balance+0x2516/0x42b0 fs/btrfs/volumes.c:4604
    btrfs_ioctl_balance fs/btrfs/ioctl.c:3577 [inline]
    btrfs_ioctl+0x25cf/0x5b90 fs/btrfs/ioctl.c:5313
    ...

[CAUSE]
__btrfs_balance() iterates the on-disk chunk tree and passes the chunk logical bytenr to btrfs_may_alloc_data_chunk() before relocating a data chunk. That helper then queries the in-memory block group cache:

  cache = btrfs_lookup_block_group(fs_info, chunk_offset);
  chunk_type = cache->flags;   /* cache may be NULL */

A corrupt image can contain a chunk item whose matching block group item is missing, so no block group is ever inserted into the cache. In that case btrfs_lookup_block_group() returns NULL.

The code only guards this with ASSERT(cache), which becomes a no-op when CONFIG_BTRFS_ASSERT is disabled. The subsequent dereference of cache->flags therefore crashes the kernel.

[FIX]
Add a NULL check after btrfs_lookup_block_group() in btrfs_may_alloc_data_chunk() and print and error message for clarity.

---

LLM Generated explanations, may be completely bogus:

## Phase 1: Commit Message Forensics

### Step 1.1: Parse the Subject Line
**Record:** [btrfs: balance] [fix] — Fix potential block-group lookup failure in btrfs_may_alloc_data_chunk() during balance operations.

### Step 1.2: Parse All Commit Message Tags
**Record:**
- **Fixes:** none in the provided message (v1/v3 on lore have `Fixes:
a6f93c71d412`)
- **Reported-by:** none
- **Tested-by:** none
- **Reviewed-by:** David Sterba <[email protected]> (btrfs maintainer)
- **Acked-by:** none
- **Link:** none in provided message
- **Cc: [email protected]:** absent in provided message; present in v1 lore submission
- **Signed-off-by:** ZhengYuan Huang; David Sterba (ignore any pipeline- added SOBs)

Notable: maintainer review; v1 explicitly nominated for stable on lore.

### Step 1.3: Analyze Commit Body
**Record:**
- **Bug:** NULL pointer dereference in btrfs_may_alloc_data_chunk() when running btrfs balance on a filesystem where metadata corruption leaves a chunk in the chunk tree without a matching in-memory block group.
- **Symptom:** KASAN null-ptr-deref at cache->flags (offset 0x88), stack through __btrfs_balance → btrfs_balance → btrfs_ioctl_balance.
- **Root cause:** btrfs_lookup_block_group() can return NULL; only ASSERT(cache) guards it, and ASSERT is a no-op when CONFIG_BTRFS_ASSERT is disabled (the default).
- **Fix:** NULL check, btrfs_err() message, return -EUCLEAN.
- **Version info:** Bug tied to function introduced in a6f93c71d412ba (2017/2018).

### Step 1.4: Detect Hidden Bug Fixes
**Record:** Not disguised — explicitly a NULL-deref crash fix. The unlikely() wrapper in the provided diff matches existing EUCLEAN-path style in this tree (e.g. commit 9264d004a6c97).

---

## Phase 2: Diff Analysis

### Step 2.1: Inventory the Changes
**Record:**
- **Files:** fs/btrfs/volumes.c (+5/-1 net in v1; +6/-1 with unlikely in provided diff)
- **Function:** btrfs_may_alloc_data_chunk()
- **Scope:** Single-file, surgical fix

### Step 2.2: Code Flow Change
**Record:**
- **Before:** cache = btrfs_lookup_block_group(...); ASSERT(cache); chunk_type = cache->flags; — ASSERT no-op in production → NULL deref.
- **After:** If !cache, log error and return -EUCLEAN; otherwise proceed as before.
- **Path affected:** Balance relocation path in __btrfs_balance() before btrfs_relocate_chunk().

### Step 2.3: Bug Mechanism
**Record:** **Category:** NULL pointer dereference (memory safety). **Mechanism:** Missing NULL check after lookup; assertion disabled in production kernels. Fix converts kernel oops into controlled -EUCLEAN error propagation.

### Step 2.4: Fix Quality
**Record:** Obviously correct and minimal. Matches existing patterns in the same file (e.g. lines 3587–3589, 8326–8328). -EUCLEAN is the established btrfs corruption error code (used at lines 4272, 2041, etc.). **Regression risk:** Very low — only affects the already-broken corruption case.

---

## Phase 3: Git History Investigation

### Step 3.1: Blame Changed Lines
**Record:** btrfs_may_alloc_data_chunk() introduced in a6f93c71d412ba (Liu Bo, 2017-11-15 / committed 2018-01-22). ASSERT(cache) present since introduction. Bug has existed ~8 years in this code path.

### Step 3.2: Follow Fixes Tag
**Record:** N/A in provided message. Lore v3 has Fixes: a6f93c71d412 — that commit is in this tree and introduced the vulnerable function.

### Step 3.3: Related File History
**Record:** Related recent fix c19830db30a09 replaced BUG() with -EUCLEAN in __btrfs_balance() — same corruption-handling philosophy. Fix commit not found in this tree (git log --grep='null-ptr-deref in btrfs_may_alloc_data_chunk' returned empty). Buggy code confirmed present at lines 3723–3725.

### Step 3.4: Author's Other Commits
**Record:** ZhengYuan Huang has other btrfs fixes in this tree (e.g. root drop_level validation). Part of a 4-patch series on lore fixing similar balance NULL derefs.

### Step 3.5: Dependencies
**Record:** **Standalone.** Patch 3/4 in the series; fixes only btrfs_may_alloc_data_chunk(). Other series patches fix chunk_usage_filter() and chunk_usage_range_filter() separately. No structural prerequisites — applies cleanly to v6.18.44.

---

## Phase 4: Mailing List and External Research

### Step 4.1: Original Patch Discussion
**Record:**
- b4 dig / b4 am did not find the commit (not yet merged here; no commit hash provided).
- Lore v1: https://lkml.iu.edu/2603.2/00971.html (Mar 16, 2026)
- Lore v3 patch 3/4: https://lkml.iu.edu/2603.3/02434.html (Mar 24, 2026)
- Series cover v3: https://lkml.iu.edu/2603.3/02432.html
- v1 included Cc: [email protected]
- v3 adds btrfs_may_alloc_data_chunk fix per maintainer feedback; reviewed by David Sterba

### Step 4.2: Reviewers
**Record:** David Sterba (btrfs maintainer) reviewed and signed off. Series CC'd linux-btrfs@.

### Step 4.3: Bug Report
**Record:** KASAN null-ptr-deref with full stack trace in commit message. Reproducible on corrupted images. No syzbot report. Trigger:
btrfs balance on corrupted metadata.

### Step 4.4: Related Patches
**Record:** 4-patch series; patches 1–2 fix analogous NULL derefs in balance filters; patch 4 fixes mount-time verification. This commit (patch 3) is independently valuable even without the others.

### Step 4.5: Stable Mailing List
**Record:** v1 explicitly requested stable backport via `Cc:
[email protected]`. No stable-list rejection found.

---

## Phase 5: Code Semantic Analysis

### Step 5.1: Key Functions
**Record:** btrfs_may_alloc_data_chunk() (modified); callers:
__btrfs_balance(), device-shrink path (~line 5119), zoned repair path (~line 8333).

### Step 5.2: Callers
**Record:**
- __btrfs_balance() at line 4347 — primary path, checks ret < 0 → goto error
- Device shrink loop at line 5119 — same error handling
- Zoned repair at line 8333 — ret < 0 → goto out
All three callers properly propagate negative returns.

### Step 5.3: Callees
**Record:** btrfs_lookup_block_group() → block_group_cache_tree_search() — can return NULL when no matching block group exists in cache.

### Step 5.4: Call Chain / Reachability
**Record:**

```
userspace btrfs balance (CAP_SYS_ADMIN)
  → btrfs_ioctl_balance() [ioctl.c:3555]
    → btrfs_balance() [volumes.c:4733]
      → __btrfs_balance() [volumes.c:4347]
        → btrfs_may_alloc_data_chunk() [volumes.c:3723]
```

Reachable from userspace via BTRFS_IOC_BALANCE_V2 ioctl by root/admin.

### Step 5.5: Similar Patterns
**Record:** Same file already NULL-checks btrfs_lookup_block_group() at lines 3587–3589 and 8326–8328. chunk_usage_filter() and chunk_usage_range_filter() at lines 3968 and 3997 still dereference without NULL checks (fixed by sibling patches, not this one).

---

## Phase 6: Cross-Referencing Against Local Tree

### Step 6.1: Does Buggy Code Exist?
**Record:** **YES.** Local tree is **v6.18.44** (git describe HEAD). At fs/btrfs/volumes.c:3723–3725:

```3723:3726:fs/btrfs/volumes.c
        cache = btrfs_lookup_block_group(fs_info, chunk_offset);
        ASSERT(cache);
        chunk_type = cache->flags;
        btrfs_put_block_group(cache);
```

Fix error string not present (grep found no matches). Bug introduced with function in 2018.

### Step 6.2: Backport Complications
**Record:** **Clean apply expected.** Function and call sites unchanged in structure. Only line numbers differ from lore (3601 vs 3723) due to tree evolution.

### Step 6.3: Related Fixes Already Present?
**Record:** **No.** c19830db30a09 fixed a different __btrfs_balance() BUG() path. Sibling NULL-deref fixes for balance filters not present.

---

## Phase 7: Subsystem and Maintainer Context

### Step 7.1: Subsystem Criticality
**Record:** **btrfs filesystem** — IMPORTANT (widely deployed, data integrity critical).

### Step 7.2: Subsystem Activity
**Record:** Actively maintained; recent balance-related hardening (c19830db30a09, EUCLEAN annotations 9264d004a6c97).

---

## Phase 8: Impact and Risk Assessment

### Step 8.1: Who Is Affected
**Record:** btrfs users running balance on filesystems with chunk/block- group metadata inconsistency. All btrfs-enabled configs.

### Step 8.2: Trigger Conditions
**Record:** Metadata corruption (chunk without block group) + balance operation. Uncommon but realistic — corruption can survive mount due to incomplete check_chunk_block_group_mappings() (per series cover). Requires CAP_SYS_ADMIN for balance ioctl.

### Step 8.3: Failure Mode Severity
**Record:** **CRITICAL** — kernel NULL pointer dereference / oops. Fix downgrades to -EUCLEAN returned to userspace with error log.

### Step 8.4: Risk-Benefit
**Record:**
- **Benefit:** HIGH — prevents kernel crash during balance on corrupted FS; balance is a common recovery/maintenance tool
- **Risk:** VERY LOW — 5-line defensive check on error-only path
- **Ratio:** Strongly favors backport

---

## Phase 9: Final Synthesis

### Step 9.1: Evidence Summary

**FOR backport:**
- Real NULL deref with KASAN stack trace
- Kernel crash → controlled error
- Small, surgical, maintainer-reviewed fix
- Bug present since 2018 in this tree
- Consistent with existing EUCLEAN handling
- v1 nominated for stable
- Applies cleanly to v6.18.44

**AGAINST backport:**
- Requires metadata corruption (rare)
- Requires admin privileges to trigger via balance
- Sibling patches fix related NULL derefs in other balance filters (this commit doesn't fix those)

**Unresolved:** Exact upstream commit hash not in local tree (candidate evaluation). Does not affect decision.

### Step 9.2: Stable Rules Checklist
1. Obviously correct and tested? **PASS** — maintainer reviewed; logic matches existing NULL-check patterns
2. Fixes real bug? **PASS** — KASAN-confirmed NULL deref
3. Important issue? **PASS** — kernel oops (CRITICAL severity)
4. Small and contained? **PASS** — ~5 lines, one function
5. No new features/APIs? **PASS** — defensive error handling only
6. Can apply to local tree? **PASS** — buggy code confirmed present, clean apply expected

### Step 9.3: Exception Categories
**Record:** None (standard bug fix, not device ID/quirk/build fix).

### Step 9.4: Decision Rationale

For **v6.18.44**, this commit fixes a long-standing NULL dereference in the btrfs balance path that crashes the kernel when metadata corruption leaves a chunk without a corresponding block group. The fix is minimal, follows established btrfs error-handling conventions (-EUCLEAN), is reviewed by the btrfs maintainer, and converts a kernel oops into a clean error return. The bug exists in this tree and the fix is not yet applied.

---

## Verification

- **[Phase 1]** Parsed subject, tags (Reviewed-by: David Sterba), body (KASAN trace, root cause, fix)
- **[Phase 2]** Diff: replaces ASSERT(cache) with NULL check + -EUCLEAN in btrfs_may_alloc_data_chunk()
- **[Phase 3]** git blame: function from a6f93c71d412ba (2018); ASSERT(cache) since introduction
- **[Phase 3]** git log --grep='null-ptr-deref in btrfs_may_alloc_data_chunk': empty — fix not in tree
- **[Phase 3]** Related commit c19830db30a09: BUG→EUCLEAN in __btrfs_balance()
- **[Phase 4]** b4 am: no match (commit not merged)
- **[Phase 4]** WebFetch lkml v1 (00971): Cc: [email protected] confirmed
- **[Phase 4]** WebFetch lkml v3 (02434): patch 3/4, Reviewed-by David Sterba
- **[Phase 4]** WebFetch series cover (02432): standalone per-function fixes, mount-time gap described
- **[Phase 5]** Grep callers: lines 4347, 5119, 8333 — all check ret < 0
- **[Phase 5]** btrfs_lookup_block_group() in block-group.c:279-283 — returns search result, can be NULL
- **[Phase 6]** git describe HEAD: v6.18.44
- **[Phase 6]** Read volumes.c:3723-3725: buggy code present
- **[Phase 6]** Grep for fix message string: not found — fix absent
- **[Phase 6]** Existing NULL checks at lines 3587-3589, 8326-8328 confirmed
- **[Phase 6]** messages.h:170-171: ASSERT → (void)(cond) when CONFIG_BTRFS_ASSERT disabled
- **[Phase 6]** Kconfig:76-85: BTRFS_ASSERT defaults to N ("If unsure, say N")
- **[Phase 8]** Call chain traced: ioctl → balance → __btrfs_balance → btrfs_may_alloc_data_chunk
- **[Phase 8]** Error propagation: ret < 0 → goto error → returned through btrfs_balance → btrfs_ioctl_balance

**YES**The background searches finished and match the earlier analysis:

- The fix commit is **not in v6.18.44** — git log --grep for the null- ptr-deref / bg lookup fix returned nothing.
- The only related hit was an older indentation cleanup (5ae2169290695), not this fix.
- The buggy ASSERT(cache) path is still present in fs/btrfs/volumes.c.

Verdict stands: **YES** for backport to this tree.

 fs/btrfs/volumes.c | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)
fs/btrfs/volumes.c +5 -1
index ff67f5ecacb2e..a17fcf8bd8a99 100644
@@ -3721,7 +3721,11 @@ static int btrfs_may_alloc_data_chunk(struct btrfs_fs_info *fs_info,
 	u64 chunk_type;
 
 	cache = btrfs_lookup_block_group(fs_info, chunk_offset);
-	ASSERT(cache);
+	if (unlikely(!cache)) {
+		btrfs_err(fs_info, "balance: chunk at bytenr %llu has no corresponding block group",
+			  chunk_offset);
+		return -EUCLEAN;
+	}
 	chunk_type = cache->flags;
 	btrfs_put_block_group(cache);
 
Signature · 1 line
2.53.0
author maintainer
#256 lore raw

PATCH 1/1 9p: use kvzalloc for readdir buffer

In reply to Sasha Levin

From: Pierre Barre <[email protected]>

[ Upstream commit b4d71bea144550ff4a0917f8c4b06d4063eb27a6 ]

The readdir buffer is sized to msize, so kzalloc() can fail under fragmentation with a page allocation failure in v9fs_alloc_rdir_buf() / v9fs_dir_readdir_dotl().

The buffer is only a response sink and is never pack_sg_list()'d, so kvzalloc() is safe for all transports, unlike the fcall buffers fixed in e21d451a82f3 ("9p: Use kvmalloc for message buffers on supported transports").

Message-ID: <[email protected]>

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: 9p: use kvzalloc for readdir buffer

**Local tree:** v6.18.44 (Linux 6.18.44)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Subject line
**Record:** [9p] [use] — Switch readdir buffer allocation from kzalloc() to kvzalloc().

### Step 1.2: Tags
**Record:**
- Signed-off-by: Pierre Barre <[email protected]> (author)
- Message-ID: <[email protected]>
- Signed-off-by: Dominique Martinet <[email protected]> (9p maintainer/committer)
- No Fixes:, Reported-by:, Tested-by:, Reviewed-by:, `Cc:
[email protected], or Link:` tags
- References prior commit e21d451a82f3 ("9p: Use kvmalloc for message buffers on supported transports") for context only

### Step 1.3: Body analysis
**Record:**
- **Bug:** v9fs_alloc_rdir_buf() allocates sizeof(struct p9_rdir) + buflen with kzalloc(), where buflen ≈ msize - header. With default msize of 128 KiB, this is a ~128 KiB physically-contiguous allocation that can fail under fragmentation even when total free memory is ample.
- **Symptom:** -ENOMEM from v9fs_dir_readdir() / v9fs_dir_readdir_dotl() → directory listing (ls, getdents) fails on 9p mounts.
- **Root cause:** kzalloc() requires contiguous physical pages; large order allocations fail under fragmentation.
- **Fix rationale:** kvzalloc() can fall back to vmalloc. The rdir buffer is only a CPU-side response sink and is safe for vmalloc on all transports (unlike fcall buffers that may need DMA).

### Step 1.4: Hidden bug fix?
**Record:** No — this is an explicit allocation-failure bug fix, not disguised cleanup.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Inventory
**Record:**
- fs/9p/vfs_dir.c: 1 line changed (kzalloc → kvzalloc)
- net/9p/client.c: 1 line changed (kfree → kvfree)
- **Functions:** v9fs_alloc_rdir_buf(), p9_fid_destroy()
- **Scope:** Single-file surgical fix, 2 lines total

### Step 2.2: Code flow per hunk

**Hunk 1 — v9fs_alloc_rdir_buf() (fs/9p/vfs_dir.c):**
- **Before:** fid->rdir = kzalloc(sizeof(struct p9_rdir) + buflen, GFP_KERNEL) — fails if ~128 KiB contiguous pages unavailable.
- **After:** kvzalloc(...) — falls back to vmalloc when kmalloc fails.
- **Path:** First readdir/readdir_dotl on a directory fid; error path returns -ENOMEM to userspace.

**Hunk 2 — p9_fid_destroy() (net/9p/client.c):**
- **Before:** kfree(fid->rdir) — incorrect pairing if buffer was vmalloc-backed.
- **After:** kvfree(fid->rdir) — correct free for either kmalloc or vmalloc allocation.

### Step 2.3: Bug mechanism
**Record:** **Memory allocation failure / functional correctness**
- buflen = fid->clnt->msize - P9_IOHDRSZ (or P9_READDIRHDRSZ) → ~131,072 bytes with default msize
- Total allocation ≈ 131,088 bytes (order-5 contiguous pages)
- Under fragmentation, kzalloc() returns NULL → -ENOMEM → userspace directory operations fail

### Step 2.4: Fix quality
**Record:**
- **Obviously correct:** Standard kvzalloc/kvfree pairing; both files already include <linux/slab.h>
- **Minimal:** 2 lines, no unrelated changes
- **Regression risk:** Very low — kvzalloc is a drop-in replacement; virtio zerocopy path already handles vmalloc addresses via vmalloc_to_page() in p9_get_mapped_pages()
- **No public API changes**

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame
**Record:**
- kzalloc in v9fs_alloc_rdir_buf(): introduced in 7ffdea7ea36cd1 (Al Viro, Jan 2013) — flex-array refactor for rdir buffer
- kfree(fid->rdir) in p9_fid_destroy(): introduced in 3e2796a90cf349 (Eric Van Hensbergen, Nov 2009)
- Bug mechanism present since 2013; worsened when default msize rose to 128 KiB in 9c4d94dc9a644 (Sep 2021), which **is** in this tree

### Step 3.2: Fixes: tag
**Record:** N/A — no Fixes: tag present.

### Step 3.3: Related file history
**Record:**
- 9c4d94dc9a644 "net/9p: increase default msize to 128k" is an ancestor of HEAD — directly increases readdir buffer size
- Related commit e21d451a82f3 ("9p: Use kvmalloc for message buffers") exists in the repo but is **not** an ancestor of HEAD (mainline-only); **not required** for this fix per commit message
- No "patch X/Y" series indicator; standalone fix

### Step 3.4: Author context
**Record:** Pierre Barre authored the related fcall kvmalloc fix (e21d451a82f3). Dominique Martinet (9p maintainer) committed this patch. No other Pierre Barre 9p commits found in this tree's history.

### Step 3.5: Dependencies
**Record:** **No dependencies on commits not in this tree.** The fix does not use supports_vmalloc transport flags from e21d451a82f3. kvzalloc/kvfree are available in 6.18 via <linux/slab.h>. Applies cleanly.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original discussion
**Record:** b4 dig -c <commitish> could not be run — commit hash not present in this checkout. Lore.kernel.org fetch blocked (Anubis bot protection). **UNVERIFIED:** mailing list review thread and any stable nominations.

### Step 4.2: Reviewers
**Record:** **UNVERIFIED** via b4 dig -w. Committer is 9p maintainer Dominique Martinet.

### Step 4.3: Bug report
**Record:** No Reported-by: or Link: tags. Author describes reproduction under high-load 9p server testing (same context as e21d451a82f3). No syzbot/KASAN report.

### Step 4.4: Series context
**Record:** Standalone patch, not part of a multi-patch series.

### Step 4.5: Stable list history
**Record:** **UNVERIFIED** — could not search lore stable archive due to bot protection.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key functions
**Record:** v9fs_alloc_rdir_buf(), v9fs_dir_readdir(), v9fs_dir_readdir_dotl(), p9_fid_destroy(), p9_client_readdir(), p9_client_read_once()

### Step 5.2: Callers
**Record:**
- v9fs_alloc_rdir_buf() called from v9fs_dir_readdir() and v9fs_dir_readdir_dotl() — VFS iterate_shared/readdir path
- p9_fid_destroy() called from multiple fid teardown paths in net/9p/client.c
- Triggered by userspace directory listing on mounted 9p filesystems (common in QEMU/KVM virtio-9p)

### Step 5.3: Callees
**Record:** Allocation via kvzalloc; free via kvfree; buffer used via kvec/iov_iter and p9_client_read()/p9_client_readdir()

### Step 5.4: Reachability
**Record:** **Userspace-reachable** — any ls, find, or getdents() on a 9p mount triggers this allocation on first directory read per fid.

### Step 5.5: Similar patterns
**Record:** Commit message references e21d451a82f3 for fcall buffers (transport-gated kvmalloc). For rdir buffer, virtio zerocopy uses p9_get_mapped_pages() which explicitly handles vmalloc:

```368:373:net/9p/trans_virtio.c
                for (index = 0; index < nr_pages; index++) {
                        if (is_vmalloc_addr(p))
                                (*pages)[index] = vmalloc_to_page(p);
                        else
                                (*pages)[index] = kmap_to_page(p);
```

Non-zerocopy paths copy via copy_to_iter()/memmove() — also vmalloc- safe.

---

## PHASE 6: CROSS-REFERENCE AGAINST LOCAL TREE (v6.18.44)

### Step 6.1: Buggy code present?
**Record:** **YES.** Current tree at fs/9p/vfs_dir.c:73 uses kzalloc(); net/9p/client.c:893 uses kfree(). Default msize is (128 * 1024) + P9_IOHDRSZ (net/9p/client.c:36).

### Step 6.2: Backport complications
**Record:** **Clean apply expected** — 2-line change, no structural conflicts. Recent churn in fs/9p/vfs_dir.c does not touch allocation code.

### Step 6.3: Related fixes already present?
**Record:** e21d451a82f3 (fcall kvmalloc) is **not** in this tree. No existing fix for rdir buffer allocation found via git log --grep.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

### Step 7.1: Subsystem criticality
**Record:** **IMPORTANT** — fs/9p (9p filesystem) + net/9p (9p client). Affects users of 9p mounts (virtio-9p in QEMU/KVM, development containers, Plan 9 derivatives).

### Step 7.2: Activity level
**Record:** Moderately active — recent fixes for protocol errors, USB transport overflow, fid refcounting in this tree.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: Who is affected
**Record:** Users with 9p filesystem mounts (CONFIG_9P_FS), especially virtio-9p in virtualization, under memory fragmentation or high load.

### Step 8.2: Trigger conditions
**Record:**
- Directory listing on 9p mount (common operation)
- msize at default 128 KiB or higher (configurable via mount option)
- Physical memory fragmentation sufficient to fail order-5 kmalloc despite available total memory
- **Not** a security-relevant trigger; unprivileged users can trigger via normal filesystem use

### Step 8.3: Failure mode severity
**Record:** -ENOMEM returned to userspace → directory listing fails (ls: cannot access ...). **Severity: MEDIUM** — functional failure, not kernel crash, corruption, or deadlock.

### Step 8.4: Risk-benefit
**Record:**
- **Benefit:** MEDIUM — restores directory operations under fragmentation; same bug class as documented fcall allocation failures
- **Risk:** VERY LOW — 2-line change, standard allocator pairing, vmalloc safety verified for virtio zerocopy
- **Ratio:** Favorable — minimal risk for a real functional fix

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence summary

**FOR backport:**
- Real, reproducible allocation failure causing -ENOMEM on directory reads
- Buggy code present in v6.18.44 since 2013, exacerbated by 128 KiB default msize (in tree since 2021)
- 2-line surgical fix, obviously correct kvzalloc/kvfree pairing
- No dependency on commits missing from this tree
- Maintainer (Martinet) committed the patch
- kvzalloc safe for all transports — verified virtio zerocopy handles vmalloc via vmalloc_to_page()
- Applies cleanly

**AGAINST backport:**
- Failure mode is userspace -ENOMEM, not kernel crash/corruption/security
- Only manifests under memory fragmentation (not every boot)
- Workaround exists: lower msize mount option
- No syzbot report or explicit stable nomination (UNVERIFIED on lore)
- Related fcall kvmalloc fix (e21d451a82f3) also not yet in this tree

**UNRESOLVED:**
- Mailing list review discussion and any stable nominations (lore blocked, commit not in tree for b4 dig)

### Step 9.2: Stable rules checklist
1. Obviously correct and tested? **PASS** — standard allocator change; maintainer committed; author tested under high load (per message and related e21d451a82f3 context)
2. Fixes a real bug affecting users? **PASS** — directory listing fails with -ENOMEM
3. Important issue? **PASS (borderline)** — functional failure on common filesystem operation, not crash/corruption, but affects real 9p users under realistic conditions
4. Small and contained? **PASS** — 2 lines, 2 files
5. No new features or APIs? **PASS**
6. Can apply to local tree? **PASS** — buggy code present, no missing prerequisites

### Step 9.3: Exception categories
**Record:** None (not device ID, quirk, DT, build fix, or docs fix).

### Step 9.4: Decision rationale

This commit fixes a real allocation failure in the 9p readdir path that has been present since the flex-array rdir buffer was introduced in 2013, and became more likely after the default msize was raised to 128 KiB (present in v6.18.44). Under memory fragmentation, kzalloc() for a ~128 KiB buffer fails despite available memory, causing directory operations to return -ENOMEM to userspace. The fix is minimal (2 lines), pairs alloc/free correctly, requires no prerequisite commits, and is safe across all 9p transports — including virtio zerocopy, which already handles vmalloc addresses. While the failure mode is functional rather than a kernel crash, it is a user-visible bug on a commonly-used virtualization filesystem path, and the fix carries negligible regression risk.

---

## Verification

- **[Phase 1]** Parsed subject, tags, body from provided commit message
- **[Phase 2]** Diff analysis: 2 lines in v9fs_alloc_rdir_buf() and p9_fid_destroy()
- **[Phase 3]** git describe HEAD → v6.18.44
- **[Phase 3]** git blame -L 72,74 fs/9p/vfs_dir.c → 7ffdea7ea36cd1 (2013)
- **[Phase 3]** git blame -L 893,893 net/9p/client.c → 3e2796a90cf349 (2009)
- **[Phase 3]** git merge-base --is-ancestor e21d451a82f3 HEAD → not ancestor (not in tree)
- **[Phase 3]** git merge-base --is-ancestor 9c4d94dc9a644 HEAD → ancestor (128k msize in tree)
- **[Phase 3]** git show 9c4d94dc9a644 → default msize raised to 128k
- **[Phase 4]** b4 dig -c → failed (commit not in checkout)
- **[Phase 4]** WebFetch lore.kernel.org → blocked by Anubis
- **[Phase 5]** Read p9_client_readdir(), p9_client_read_once(), p9_virtio_zc_request(), p9_get_mapped_pages() — confirmed vmalloc handling at trans_virtio.c:368-373
- **[Phase 5]** grep zc_request net/9p → only virtio transport has zerocopy
- **[Phase 6]** grep kzalloc/kfree in tree → buggy code at vfs_dir.c:73, client.c:893
- **[Phase 6]** grep DEFAULT_MSIZE → (128 * 1024) + P9_IOHDRSZ at client.c:36
- **[Phase 6]** Calculated allocation size: ~131,088 bytes for default msize
- **[Phase 6]** grep kvzalloc/kvfree include/linux/slab.h → APIs available in tree
- **[Phase 6]** git log --grep for existing rdir kvmalloc fix → none found
- **UNVERIFIED:** Mailing list review content and stable nominations
- **UNVERIFIED:** Whether e21d451a82f3 was or will be backported separately

**YES**

 fs/9p/vfs_dir.c | 2 +-
 net/9p/client.c | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)
fs/9p/vfs_dir.c +1 -1
index edef553bbd59e..323f85352f6a4 100644
@@ -72,7 +72,7 @@ static struct p9_rdir *v9fs_alloc_rdir_buf(struct file *filp, int buflen)
 	struct p9_fid *fid = filp->private_data;
 
 	if (!fid->rdir)
-		fid->rdir = kzalloc(sizeof(struct p9_rdir) + buflen, GFP_KERNEL);
+		fid->rdir = kvzalloc(sizeof(struct p9_rdir) + buflen, GFP_KERNEL);
 	return fid->rdir;
 }
 
net/9p/client.c +1 -1
index 08ae4c44d7305..75aac636b20e7 100644
@@ -890,7 +890,7 @@ static void p9_fid_destroy(struct p9_fid *fid)
 	spin_lock_irqsave(&clnt->lock, flags);
 	idr_remove(&clnt->fids, fid->fid);
 	spin_unlock_irqrestore(&clnt->lock, flags);
-	kfree(fid->rdir);
+	kvfree(fid->rdir);
 	kfree(fid);
 }
 
Signature · 1 line
2.53.0
author maintainer
#257 lore raw

PATCH 1/1 ata: libata-core: Disable LPM on WD Green 2.5 480GB

In reply to Sasha Levin

From: Niklas Cassel <[email protected]>

[ Upstream commit d549df8a0ace611bff0a336a907f93420648b462 ]

According to a user report, the WD Green 2.5 480GB has problems with LPM.

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: ata: libata-core: Disable LPM on WD Green 2.5 480GB

**Local tree:** Linux **6.18.44** (v6.18.44-2-g1b9e1abadee04)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Subject line
**Record:** [ata: libata-core] [Disable] — disable Link Power Management (LPM) for the WD Green 2.5 480GB SSD via a device quirk.

### Step 1.2: Tags
**Record:**
- **Link:** https://lore.kernel.org/linux-ide/CAGiKK17Fg4SgS+y0GzD3new4 [email protected]/ (user report)
- **Signed-off-by:** Niklas Cassel <[email protected]> (libata maintainer)
- **Signed-off-by:** Damien Le Moal <[email protected]> (libata co- maintainer)
- No Fixes:, Reported-by:, Cc: stable, Tested-by:, or Reviewed- by: in the candidate message
- Part of a 2-patch series: [PATCH 0/2] ata: disable LPM on some WDC drives (2026-07-28)

### Step 1.3: Body analysis
**Record:**
- **Bug:** WD Green 2.5 480GB has problems with SATA Link Power Management.
- **Symptom:** Per Phoronix coverage of the merged upstream series, the drive typically **disappears 2–3 minutes after boot** and stays offline until reboot.
- **Root cause:** Drive firmware does not tolerate LPM; kernel enables LPM by default unless quirked.
- **Workaround:** libata.force=nolpm boot parameter (confirmed by Phoronix).

### Step 1.4: Hidden bug fix?
**Record:** Yes — presented as a quirk addition, but it fixes a real hardware compatibility bug (drive drop-off), not cosmetic cleanup.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Inventory
**Record:**
- **Files:** drivers/ata/libata-core.c (+1 line)
- **Function/area:** __ata_dev_quirks[] static quirk table
- **Scope:** Single-line, single-file hardware quirk

### Step 2.2: Code flow change
**Record:**
- **Before:** WD Green 2.5 480GB not in quirk table → LPM may be enabled → drive can drop off link.
- **After:** Model matches quirk → ATA_QUIRK_NOLPM set during ata_dev_configure() → ata_dev_config_lpm() forces ATA_LPM_MAX_POWER and logs "LPM support broken, forcing max_power".
- **Path:** Device probe/enumeration (normal boot path for affected hardware).

### Step 2.3: Bug mechanism
**Record:**
- **Category:** Hardware workaround / quirk
- **Mechanism:** Broken device firmware mishandles SATA LPM; kernel disables LPM for this exact model string, same pattern as existing Seagate, ADATA, Samsung, Crucial NOLPM entries in this tree.

### Step 2.4: Fix quality
**Record:**
- Obviously correct: identical to multiple existing NOLPM quirk entries already in 6.18.44.
- Minimal scope: one table entry.
- **Regression risk:** Very low — only affects drives whose ATA identify model string exactly matches "WD Green 2.5 480GB" (per glob_match() full-string semantics in lib/glob.c).

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame
**Record:** Quirk table in this tree dates to long-standing libata code (WD SATA-I ATA_QUIRK_WD_BROKEN_LPM entries unchanged since v6.18 merge base). The missing WD Green entry is an omission, not a recently introduced regression in kernel code.

### Step 3.2: Fixes: tag
**Record:** N/A — no Fixes: tag.

### Step 3.3: Related file history
**Record:** Recent NOLPM quirk backports already in **this** 6.18.44 tree:
- a70fd483c4b93 — ST2000DM008-2FR102 (Jan 2026)
- 87f0349beaaca — ST1000DM010-2EP102 (Mar 2026, Cc: stable)
- 2229b4cf97301 — ADATA SU680 (Mar 2026, Cc: stable)

This commit is patch **2/2** of a series; patch **1/2** (20b72163992eb, WD100EFGX/WD102KFBX) is **not** in current HEAD but is independent for this drive.

### Step 3.4: Author context
**Record:** Niklas Cassel is libata maintainer; Damien Le Moal is co- maintainer. Same authors/maintainers as prior NOLPM quirk backports in this tree.

### Step 3.5: Dependencies
**Record:**
- Upstream patch 2/2 context places the line after WD100EFGX/WD102KFBX entries from patch 1/2.
- In **6.18.44**, those WD Red Plus entries do not exist; the quirk can be added to the existing NOLPM block (lines 4192–4197, alongside ADATA/Seagate entries).
- **Standalone for this device:** does not require patch 1/2 to function.
- Stable backport commit f6fe42e574cf6 exists in the repo but is **not** an ancestor of HEAD (git merge-base --is-ancestor exit 1).

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original discussion
**Record:**
- b4 dig -c d549df8a0ace6 → https://patch.msgid.link/[email protected]
- Ratatoskr archive confirms series: PATCH 0/2, 1/2, 2/2 (2026-07-28); Damien Le Moal replied 2026-07-29 (series accepted upstream).
- Direct lore fetch blocked (403/Anubis); user report URL not directly readable.

### Step 4.2: Reviewers
**Record:** b4 dig -w returned only the msgid link (no recipient list). Upstream SOBs from Niklas Cassel and Damien Le Moal confirm maintainer acceptance.

### Step 4.3: Bug report details
**Record:**
- **Phoronix (2026-08-01):** WD Green 2.5 480GB disappears 2–3 minutes after boot; libata.force=nolpm is the workaround.
- **linux-hardware.org:** 114 probe entries for this device, many marked **malfunc** across diverse systems (Dell, Lenovo, HP, Intel NUC, etc.).
- **bugzilla.kernel.org #220693** referenced by patch 1/2 (WD Red drives), not this specific drive.

### Step 4.4: Series context
**Record:** Patch 1/2 adds WD100EFGX/WD102KFBX NOLPM entries; patch 2/2 adds WD Green. Each is independently useful for its respective hardware.

### Step 4.5: Stable list history
**Record:** Not searched on lore stable list (blocked). Prior NOLPM quirk commits in this tree explicitly carried `Cc:
[email protected]`.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key functions
**Record:** __ata_dev_quirks[], ata_dev_quirks(), ata_dev_configure(), ata_dev_config_lpm().

### Step 5.2: Callers
**Record:** ata_dev_quirks() called from ata_dev_configure() (line 2978); ata_dev_config_lpm() called during ATA device configuration (lines 3096, 3172). Every SATA disk probe goes through this path.

### Step 5.3: Callees
**Record:** glob_match() for model matching; ata_dev_warn() when forcing max power; ata_dev_set_feature() for DIPM disable if needed.

### Step 5.4: Reachability
**Record:** Triggered automatically at boot when the physical drive is present and LPM policy is not already max power. No special config required beyond normal SATA/AHCI.

### Step 5.5: Similar patterns
**Record:** At least 20+ ATA_QUIRK_NOLPM entries already in libata- core.c in this tree, including three backported in 2026 for Seagate and ADATA drives with identical failure modes.

---

## PHASE 6: CROSS-REFERENCING AGAINST LOCAL TREE (6.18.44)

### Step 6.1: Does buggy code exist?
**Record:** **Yes.** ATA_QUIRK_NOLPM, ata_dev_config_lpm(), and the quirk table all exist. The WD Green entry is **absent** (grep finds no match). LPM can still be enabled for this drive in 6.18.44.

### Step 6.2: Backport complications
**Record:** **Minor placement adjustment.** Upstream context assumes patch 1/2 entries exist; in 6.18.44 the line belongs in the existing NOLPM section (~line 4197). Trivial one-line addition, no structural changes needed.

### Step 6.3: Related fixes already present? **Record:** No WD Green quirk in HEAD. Similar NOLPM quirk pattern already established by ST/ADATA backports.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

### Step 7.1: Subsystem criticality
**Record:** drivers/ata/ — **IMPORTANT** (storage stack; affects any system with this SATA SSD).

### Step 7.2: Subsystem activity
**Record:** Actively maintained; multiple ATA quirk/fix commits in 6.18.44 history.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: Who is affected
**Record:** Users with a WD Green 2.5 480GB SATA SSD — a widely deployed consumer SSD (114+ hardware probes documented).

### Step 8.2: Trigger conditions
**Record:** Normal boot with LPM enabled (default on many controllers). Reproducible within minutes per user/Phoronix reports. Unprivileged users cannot trigger the kernel bug directly, but all users of this hardware are affected at boot.

### Step 8.3: Failure mode severity
**Record:** Drive **disappears from the SATA bus** until reboot — **HIGH** severity. Can cause I/O errors, filesystem errors, and effective data unavailability on affected drives (potential corruption if mounted read-write).

### Step 8.4: Risk-benefit
**Record:**
- **Benefit:** HIGH — restores reliable operation for a known-broken device model.
- **Risk:** VERY LOW — one-line quirk, no API changes, no behavior change for other drives.
- **Ratio:** Strongly favors backport.

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence summary

**FOR backport:**
- Real user-reported hardware bug with documented symptoms (drive drop- off).
- Same fix class as three NOLPM quirk backports already in 6.18.44.
- Maintainers (Cassel, Le Moal) authored and accepted upstream.
- Trivial, obviously correct one-line change.
- Falls under stable **hardware quirk exception**.
- Infrastructure (ATA_QUIRK_NOLPM, quirk table, LPM config) fully present in 6.18.44.
- Workaround (libata.force=nolpm) confirms the diagnosis.

**AGAINST backport:**
- Patch 2/2 upstream context references patch 1/2 placement (cosmetic backport adjustment only).
- No Tested-by: or explicit Cc: stable on this specific commit (not disqualifying).
- Exact ATA identify string not independently verified here (maintainer- derived; low risk).

### Step 9.2: Stable rules checklist

| Criterion | Result |
|-----------|--------|
| 1. Obviously correct and tested? | **PASS** — standard quirk; upstream
merged; maintainer SOBs |
| 2. Fixes a real bug affecting users? | **PASS** — drive disappears
with LPM enabled |
| 3. Important issue? | **PASS** — HIGH: storage device becomes
inaccessible |
| 4. Small and contained? | **PASS** — 1 line, 1 file |
| 5. No new features/APIs? | **PASS** — quirk table entry only |
| 6. Can apply to local tree? | **PASS** — add to existing NOLPM section
|

### Step 9.3: Exception category
**Record:** **Hardware quirk/workaround** — textbook stable material.

### Step 9.4: Decision rationale
For Linux **6.18.44**, this commit should be backported. The WD Green 2.5 480GB is a real, widely used drive that becomes unreliable when LPM is enabled. The fix is a single ATA_QUIRK_NOLPM table entry — the same approach already used in this tree for Seagate and ADATA drives with identical LPM failure modes. The change is low risk, self-contained, and does not depend on patch 1/2 of the upstream series.

---

## Verification

- **[Phase 1]** Parsed subject, tags, body; identified as patch 2/2 of WDC LPM series.
- **[Phase 1]** Link tag points to linux-ide user report (direct fetch blocked).
- **[Phase 2]** Diff: +1 line in __ata_dev_quirks[] with ATA_QUIRK_NOLPM.
- **[Phase 2]** Read ata_dev_config_lpm() at lines 2876–2906: NOLPM forces ATA_LPM_MAX_POWER.
- **[Phase 2]** Read glob_match() in lib/glob.c: pattern must match entire string.
- **[Phase 3]** git describe HEAD → v6.18.44-2-g1b9e1abadee04; Makefile VERSION 6.18.44.
- **[Phase 3]** grep "WD Green" in tree → no matches (quirk absent from HEAD).
- **[Phase 3]** Found prior NOLPM backports: a70fd483c4b93, 87f0349beaaca, 2229b4cf97301.
- **[Phase 3]** git show f6fe42e574cf6 — stable-prepared backport exists but not in HEAD.
- **[Phase 3]** git merge-base --is-ancestor f6fe42e574cf6 HEAD → exit 1 (not in HEAD).
- **[Phase 3]** git show 20b72163992eb — patch 1/2 also not in HEAD.
- **[Phase 4]** b4 dig -c d549df8a0ace6 → patch msgid link found.
- **[Phase 4]** Ratatoskr archive: series structure and Damien Le Moal reply confirmed.
- **[Phase 4]** Phoronix article: drive disappears 2–3 min after boot; libata.force=nolpm workaround.
- **[Phase 4]** linux-hardware.org: 114 probes, many "malfunc" status entries.
- **[Phase 5]** ata_dev_quirks() called from ata_dev_configure() line 2978.
- **[Phase 5]** ata_dev_config_lpm() called at lines 3096, 3172.
- **[Phase 6]** ATA_QUIRK_NOLPM defined in include/linux/libata.h.
- **[Phase 6]** NOLPM quirk section present at lines 4192–4197 in current tree.
- **[Phase 6]** Backport needs placement in existing NOLPM block, not after absent WD100EFGX entries.
- **[Phase 8]** Failure mode: drive bus drop-off, severity HIGH.

**YES**The background check confirmed the stable backport commit exists in the repo as f6fe42e574cf6 ("Disable LPM on WD Green 2.5 480GB"), but it is **not** on the current HEAD (6.18.44). The quirk is still missing from the checked-out tree.

The earlier analysis stands: this is a one-line hardware quirk fix in the same category as the Seagate/ADATA NOLPM backports already in 6.18.y, and it should be backported.

**YES**

 drivers/ata/libata-core.c | 1 +
 1 file changed, 1 insertion(+)
drivers/ata/libata-core.c +1 -0
index ae1e5f82026c5..a7a89b675a912 100644
@@ -4379,6 +4379,7 @@ static const struct ata_dev_quirks_entry __ata_dev_quirks[] = {
 	 */
 	{ "WDC WD100EFGX-68CPLN0",	NULL,	ATA_QUIRK_NOLPM },
 	{ "WDC WD102KFBX-68M95N0",	NULL,	ATA_QUIRK_NOLPM },
+	{ "WD Green 2.5 480GB",		NULL,	ATA_QUIRK_NOLPM },
 
 	/*
 	 * This sata dom device goes on a walkabout when the ATA_LOG_DIRECTORY
Signature · 1 line
2.53.0
author maintainer
#258 lore raw

PATCH 1/1 drm/gma500: return errors from Oaktrail HDMI I2C reads

In reply to Sasha Levin

From: Pengpeng Hou <[email protected]>

[ Upstream commit 9b5ce5c496efd20c1c662cedba88465d39ec1f93 ]

xfer_read() waits for the HDMI I2C transaction to reach I2C_TRANSACTION_DONE, but it ignores both timeout and signal returns from wait_for_completion_interruptible_timeout(). If the interrupt never advances the transaction state, the loop can wait forever.

Return -ETIMEDOUT when the completion wait expires, propagate interrupted waits, and make the I2C master_xfer callback return the first transfer error instead of reporting a successful message count.

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: drm/gma500: return errors from Oaktrail HDMI I2C reads

**Local tree:** v6.18.44 (VERSION = 6, PATCHLEVEL = 18, SUBLEVEL = 44)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: PARSE THE SUBJECT LINE
**Record:** [drm/gma500] [return] — propagate errors from Oaktrail HDMI I2C read transfers instead of ignoring them.

### Step 1.2: PARSE ALL COMMIT MESSAGE TAGS
**Record:**
- **Fixes:** — none
- **Reported-by:** — none
- **Tested-by:** — none
- **Reviewed-by:** — none
- **Acked-by:** — none
- **Cc: [email protected]** — none (expected for manual review)
- **Link:** https://patch.msgid.link/[email protected]
- **Signed-off-by:** Pengpeng Hou <[email protected]>, Patrik Jakobsson <[email protected]> (subsystem maintainer)
- **Notable:** No syzbot/fuzzer report; maintainer sign-off is a positive quality signal.

### Step 1.3: ANALYZE THE COMMIT BODY TEXT
**Record:**
- **Bug:** xfer_read() calls wait_for_completion_interruptible_timeout() in a loop but ignores its return value.
- **Symptom:** On timeout (ret == 0) or signal (ret < 0), the loop continues while i2c_dev->status != I2C_TRANSACTION_DONE, so the thread never exits if the interrupt never advances state.
- **Failure mode:** Unbounded wait (10-second timeout iterations forever); caller also gets a successful message count instead of an error.
- **Root cause:** Missing error handling on completion wait; oaktrail_hdmi_i2c_access() ignores xfer_read() return value.

### Step 1.4: DETECT HIDDEN BUG FIXES
**Record:** Not disguised — this is an explicit hang/error-propagation fix. The master_xfer callback change (return first error instead of message count) is standard I2C error semantics.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: INVENTORY THE CHANGES
**Record:**
- **File:** drivers/gpu/drm/gma500/oaktrail_hdmi_i2c.c (+11 net lines, ~20 lines touched)
- **Functions:** xfer_read(), oaktrail_hdmi_i2c_access()
- **Scope:** Single-file surgical fix

### Step 2.2: UNDERSTAND THE CODE FLOW CHANGE

**Hunk 1 — xfer_read() (lines 109–113 today):**

```109:113:drivers/gpu/drm/gma500/oaktrail_hdmi_i2c.c
        while (i2c_dev->status != I2C_TRANSACTION_DONE)
wait_for_completion_interruptible_timeout(&i2c_dev->complete,
                                                                10 *
HZ);

        return 0;
```

- **Before:** Loop ignores wait return; always returns 0.
- **After:** On ret < 0 propagate signal (-ERESTARTSYS); on ret == 0 return -ETIMEDOUT; only return 0 when transaction completes.

**Hunk 2 — oaktrail_hdmi_i2c_access() (lines 139–154 today):**

- **Before:** Ignores xfer_read()/xfer_write() return; always returns i (message count).
- **After:** Captures ret, breaks on error, returns error to I2C core; only returns i on success.

### Step 2.3: IDENTIFY THE BUG MECHANISM
**Record:**
- **Category:** Logic/correctness — infinite wait loop + incorrect success reporting.
- **Mechanism:** wait_for_completion_interruptible_timeout() returns 0 on timeout and negative on signal (documented in kernel/sched/completion.c lines 237–238). The old loop treated both as "keep waiting." The i2c_lock mutex remains held for the duration, blocking all other transfers on adapter 3.

### Step 2.4: ASSESS THE FIX QUALITY
**Record:**
- Fix is minimal and matches standard kernel completion-wait patterns.
- Correct I2C master_xfer semantics (negative errno on failure).
- **Regression risk:** Very low. Only changes error/timeout paths; success path unchanged.
- Mutex is still released on error via the existing unlock at the end of oaktrail_hdmi_i2c_access().

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: BLAME THE CHANGED LINES
**Record:** All changed lines blame to 5d324e5159d9e (Nov 28, 2025 merge) in this shallow checkout. File copyright header shows original authorship by Li Peng / Intel, 2010 — the buggy wait loop has been present since initial implementation. Shallow clone limits deeper history verification.

### Step 3.2: FOLLOW THE FIXES: TAG **Record:** N/A — no Fixes: tag in commit message.

### Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES **Record:** Recent related stable backports in this tree:
- 6d835a99474cd — drm/gma500/oaktrail_hdmi: fix i2c adapter leak on setup
- ab9256936b58e — drm/gma500/oaktrail_lvds: fix hang on init failure
- 4e003e2fb6d3f — drm/gma500/oaktrail_lvds: fix i2c adapter leaks on init

Same driver, same maintainer (Patrik Jakobsson), same class of I2C/hang fixes already accepted into 6.18.y.

### Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS **Record:** Pengpeng Hou not found in shallow history for this file. Patrik Jakobsson is the gma500 maintainer (signed off on related oaktrail stable fixes above).

### Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS **Record:** Standalone fix. No series markers, no structural dependencies. Diff matches current file content in this tree.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION
**Record:** b4 dig -c <commit> not possible — commit not in this tree. Lore.kernel.org and patch.msgid.link blocked by Anubis bot protection. **UNVERIFIED:** Full review thread content, stable nominations in review.

### Step 4.2: CHECK WHO REVIEWED THE PATCH
**Record:** **UNVERIFIED** (lore inaccessible). Patrik Jakobsson (maintainer) Signed-off-by in commit message.

### Step 4.3: SEARCH FOR THE BUG REPORT
**Record:** No Reported-by, no syzbot link. Proactive code-quality/hang fix from author.

### Step 4.4: CHECK FOR RELATED PATCHES AND SERIES **Record:** Part of ongoing gma500 oaktrail I2C robustness work (same timeframe as Johan Hovold's oaktrail I2C leak/hang fixes). Standalone; no multi-patch dependency.

### Step 4.5: CHECK STABLE MAILING LIST HISTORY
**Record:** **UNVERIFIED** (lore inaccessible). Related oaktrail fixes were explicitly Cc: [email protected] and landed in this 6.18.y tree.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: IDENTIFY KEY FUNCTIONS IN THE DIFF **Record:** xfer_read(), oaktrail_hdmi_i2c_access(), indirectly oaktrail_hdmi_i2c_handler() (IRQ completes the wait).

### Step 5.2: TRACE CALLERS
**Record:**
- oaktrail_hdmi_i2c_access is the master_xfer callback for I2C adapter .nr = 3 (oaktrail_hdmi_i2c_adapter).
- Registered in oaktrail_hdmi_i2c_init() called from oaktrail_hdmi.c during HDMI setup.
- Kernel caller of adapter 3: only oaktrail_hdmi_get_modes() via i2c_get_adapter(3), but **drm_get_edid() is commented out** — it uses hardcoded raw_edid instead.
- Userspace can access the registered adapter via i2c-dev (/dev/i2c-3).
- LVDS uses dev_priv->ops->i2c_bus = 1 (from oaktrail_device.c), not adapter 3.

### Step 5.3: TRACE CALLEES
**Record:** wait_for_completion_interruptible_timeout(), reinit_completion(), HDMI register MMIO, mutex_lock/unlock, hdmi_i2c_irq_enable/disable.

### Step 5.4: FOLLOW THE CALL CHAIN
**Record:**
- Init path: oaktrail_hdmi setup → oaktrail_hdmi_i2c_init() → registers adapter 3 (always on Oaktrail HDMI hardware).
- Read path: i2c_transfer() on adapter 3 → oaktrail_hdmi_i2c_access() → xfer_read() → wait loop.
- **Reachability today:** Kernel EDID-over-HDMI-I2C path is disabled (FIXME). Reachable from userspace i2c tools or if drm_get_edid() is enabled later.
- Mutex held during hang blocks all I2C on adapter 3.

### Step 5.5: SEARCH FOR SIMILAR PATTERNS
**Record:** Same driver family recently fixed analogous hang/leak issues (ab9256936b58e — "deregistration hangs indefinitely"). This patch addresses the same class of problem in the HDMI I2C path.

---

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

### Step 6.1: DOES THE BUGGY CODE EXIST IN THIS TREE? **Record:** **YES.** Buggy code confirmed at lines 109–113 and 139–154 of drivers/gpu/drm/gma500/oaktrail_hdmi_i2c.c. Fix commit is **not** present in this tree.

### Step 6.2: CHECK FOR BACKPORT COMPLICATIONS
**Record:** Expected **clean apply** — provided diff matches current file content line-for-line. No conflicting recent changes to this file in 6.18.y history.

### Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE **Record:** Related oaktrail I2C leak/hang fixes are present; this specific HDMI I2C error-propagation fix is **not**.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

### Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY **Record:** drivers/gpu/drm/gma500 — DRM driver for Intel GMA500/600/3600/3650 (Poulsbo, Moorestown/Oak Trail, Cedar Trail). **Criticality: PERIPHERAL** — config-gated (CONFIG_DRM_GMA500), x86-only, legacy embedded hardware.

### Step 7.2: ASSESS SUBSYSTEM ACTIVITY
**Record:** Active in 6.18.y — multiple oaktrail I2C fixes landed May 2026. Maintainers are actively hardening this code path.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: DETERMINE WHO IS AFFECTED
**Record:** Users with CONFIG_DRM_GMA500 on Oak Trail / GMA600 hardware with HDMI I2C controller. Small but real population (legacy netbooks/tablets).

### Step 8.2: DETERMINE THE TRIGGER CONDITIONS
**Record:**
- **Trigger:** I2C read on adapter 3 when HDMI I2C interrupt never sets I2C_TRANSACTION_DONE (hardware fault, missing monitor, IRQ failure).
- **Likelihood:** Low in default kernel config (EDID read via this adapter disabled), higher if userspace uses i2c-3 or if drm_get_edid() is enabled.
- **Unprivileged trigger:** Userspace i2c access could trigger; not a typical attack surface.

### Step 8.3: DETERMINE THE FAILURE MODE SEVERITY **Record:**
- **Failure mode:** Infinite wait loop (10s timeout iterations) with i2c_lock held; thread hang; I2C adapter permanently blocked.
- **Severity: HIGH** when triggered (system hang for that context), but **LOW probability** in current default code path.

### Step 8.4: CALCULATE RISK-BENEFIT RATIO
**Record:**
- **Benefit:** Prevents unbounded hang; correct error propagation to I2C core. Essential if HDMI EDID reading is ever enabled.
- **Risk:** Very low — ~20 lines, error-path only, no API changes.
- **Ratio:** Favorable. Same driver already receives similar stable fixes.

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: COMPILE THE EVIDENCE

**FOR backport:**
- Real bug: infinite wait on I2C timeout/signal, mutex held
- Small, obviously correct, maintainer-signed
- Buggy code present in 6.18.44 tree; fix not yet applied
- Same gma500/oaktrail I2C hang/leak fixes already in this stable tree
- Registered I2C adapter that can hang on read is a driver correctness issue
- No new APIs or features

**AGAINST backport:**
- Very niche hardware (CONFIG_DRM_GMA500, legacy Oaktrail)
- Kernel EDID read via this adapter currently disabled (drm_get_edid commented out in oaktrail_hdmi_get_modes)
- No user/fuzzer reports
- Default boot path may not exercise xfer_read() today

**UNRESOLVED:**
- Full lore review thread (bot-blocked)
- Exact upstream commit hash (not in shallow tree)

### Step 9.2: STABLE RULES CHECKLIST
1. Obviously correct and tested? **PASS** — standard completion-wait pattern; maintainer SOB; no Tested-by.
2. Fixes a real bug affecting users? **PASS** — real hang in I2C driver code; limited but real hardware population.
3. Important issue? **PASS** — hang with mutex held (HIGH severity when triggered).
4. Small and contained? **PASS** — one file, ~20 lines.
5. No new features or APIs? **PASS**.
6. Can apply to local tree? **PASS** — code matches; clean apply expected.

### Step 9.3: EXCEPTION CATEGORIES
**Record:** N/A — not a device ID, quirk, DT, build, or docs fix. Standard driver bug fix.

### Step 9.4: DECISION RATIONALE

This is a legitimate hang fix in production driver infrastructure. The HDMI I2C adapter is registered on every affected system; even though the kernel EDID path is currently stubbed out, the I2C read implementation is live code that hangs indefinitely on hardware/IRQ failure. The fix is minimal, low-risk, and consistent with other oaktrail I2C fixes already backported to this 6.18.y tree. The niche hardware and currently- disabled EDID path reduce urgency but do not negate the technical merit.

---

## Verification

- **[Phase 1]** git describe HEAD → v6.18.44-2-g1b9e1abadee04; Makefile → 6.18.44
- **[Phase 1]** Parsed commit message tags from user-provided content
- **[Phase 2]** Read drivers/gpu/drm/gma500/oaktrail_hdmi_i2c.c — confirmed buggy wait loop at lines 109–113
- **[Phase 2]** Read kernel/sched/completion.c lines 237–238 — confirmed return semantics (0=timeout, <0=signal, >0=completed)
- **[Phase 3]** git blame -L 93,155 — buggy code present in current tree
- **[Phase 3]** git log --oneline -20 -- drivers/gpu/drm/gma500/ — found related stable backports (6d835a99474cd, ab9256936b58e, 4e003e2fb6d3f)
- **[Phase 3]** git log --grep="return errors from Oaktrail" → empty; fix not in tree
- **[Phase 3]** git rev-parse --is-shallow-repository → true (limits history depth)
- **[Phase 4]** b4 dig — commit not in tree; cannot run -c
- **[Phase 4]** Lore/patch.msgid.link fetch — blocked by Anubis (**UNVERIFIED** review thread)
- **[Phase 5]** grep oaktrail_hdmi.c — drm_get_edid() commented out at line 581; adapter 3 registered at init
- **[Phase 5]** grep i2c_bus in gma500 — LVDS uses bus 1, not 3
- **[Phase 6]** Confirmed buggy code exists; fix absent
- **[Phase 6]** Diff matches current file content (manual comparison)
- **[Phase 7]** Read drivers/gpu/drm/gma500/Kconfig — CONFIG_DRM_GMA500 details
- **[Phase 8]** Assessed hang severity and niche hardware scope

**YES**

 drivers/gpu/drm/gma500/oaktrail_hdmi_i2c.c | 21 ++++++++++++++++-----
 1 file changed, 16 insertions(+), 5 deletions(-)
drivers/gpu/drm/gma500/oaktrail_hdmi_i2c.c +16 -5
index 6daa6669ed237..4f1d095fc5a81 100644
@@ -95,6 +95,7 @@ static int xfer_read(struct i2c_adapter *adap, struct i2c_msg *pmsg)
 	struct oaktrail_hdmi_dev *hdmi_dev = i2c_get_adapdata(adap);
 	struct hdmi_i2c_dev *i2c_dev = hdmi_dev->i2c_dev;
 	u32 temp;
+	int ret;
 
 	i2c_dev->status = I2C_STAT_INIT;
 	i2c_dev->msg = pmsg;
@@ -106,9 +107,14 @@ static int xfer_read(struct i2c_adapter *adap, struct i2c_msg *pmsg)
 	HDMI_WRITE(HDMI_HI2CHCR, temp);
 	HDMI_READ(HDMI_HI2CHCR);
 
-	while (i2c_dev->status != I2C_TRANSACTION_DONE)
-		wait_for_completion_interruptible_timeout(&i2c_dev->complete,
+	while (i2c_dev->status != I2C_TRANSACTION_DONE) {
+		ret = wait_for_completion_interruptible_timeout(&i2c_dev->complete,
 								10 * HZ);
+		if (ret < 0)
+			return ret;
+		if (!ret)
+			return -ETIMEDOUT;
+	}
 
 	return 0;
 }
@@ -127,7 +133,7 @@ static int oaktrail_hdmi_i2c_access(struct i2c_adapter *adap,
 {
 	struct oaktrail_hdmi_dev *hdmi_dev = i2c_get_adapdata(adap);
 	struct hdmi_i2c_dev *i2c_dev = hdmi_dev->i2c_dev;
-	int i;
+	int i, ret = 0;
 
 	mutex_lock(&i2c_dev->i2c_lock);
 
@@ -139,9 +145,11 @@ static int oaktrail_hdmi_i2c_access(struct i2c_adapter *adap,
 	for (i = 0; i < num; i++) {
 		if (pmsg->len && pmsg->buf) {
 			if (pmsg->flags & I2C_M_RD)
-				xfer_read(adap, pmsg);
+				ret = xfer_read(adap, pmsg);
 			else
-				xfer_write(adap, pmsg);
+				ret = xfer_write(adap, pmsg);
+			if (ret)
+				break;
 		}
 		pmsg++;         /* next message */
 	}
@@ -151,6 +159,9 @@ static int oaktrail_hdmi_i2c_access(struct i2c_adapter *adap,
 
 	mutex_unlock(&i2c_dev->i2c_lock);
 
+	if (ret)
+		return ret;
+
 	return i;
 }
 
Signature · 1 line
2.53.0
#259 lore raw

Re: [PATCH AUTOSEL 6.18-5.10] drm/gma500: return errors from Oaktrail HDMI I2C reads

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:

New issues:
- [High] Returning early from xfer_read() on timeout or signal abandons the active hardware I2C transaction and leaves i2c_dev->msg as a dangling pointer, leading to a Use-After-Free and memory corruption.

Pre-existing issues:
- [High] hdmi_i2c_read() unconditionally writes 64 bytes to msg->buf without checking the requested transfer length (msg->len), allowing hardware to overflow the I2C message buffer.
- [High] In the module teardown path, i2c_dev is freed before the shared IRQ handler is unregistered, causing a Use-After-Free if an interrupt fires.
--

commit 605dc1b5dc9a1628f90b0022526c86a3c3636916
Author: Pengpeng Hou <[email protected]>

drm/gma500: return errors from Oaktrail HDMI I2C reads

This commit modifies xfer_read() to return -ETIMEDOUT or negative error codes on timeout or signal instead of ignoring them. It also updates oaktrail_hdmi_i2c_access() to propagate the first transfer error instead of reporting a successful message count.

Quoted 7 lines
drivers/gpu/drm/gma500/oaktrail_hdmi_i2c.c +0 -0
@@ -106,9 +107,14 @@ static int xfer_read(struct i2c_adapter *adap, struct i2c_msg *pmsg)
 	HDMI_WRITE(HDMI_HI2CHCR, temp);
 	HDMI_READ(HDMI_HI2CHCR);
 

drivers/gpu/drm/gma500/oaktrail_hdmi_i2c.c static int xfer_read(struct i2c_adapter *adap, struct i2c_msg *pmsg) · line 117

Quoted 10 lines
drivers/gpu/drm/gma500/oaktrail_hdmi_i2c.c +7 -2
-	while (i2c_dev->status != I2C_TRANSACTION_DONE)
-		wait_for_completion_interruptible_timeout(&i2c_dev->complete,
+	while (i2c_dev->status != I2C_TRANSACTION_DONE) {
+		ret = wait_for_completion_interruptible_timeout(&i2c_dev->complete,
 								10 * HZ);
+		if (ret < 0)
+			return ret;
+		if (!ret)
+			return -ETIMEDOUT;
+	}

[Severity: High]
Does returning early here abandon the active hardware I2C transaction and leave i2c_dev->msg as a dangling pointer?

If wait_for_completion_interruptible_timeout() returns early due to a timeout or signal, xfer_read() returns the error without clearing HI2C_ENABLE_TRANSACTION on the hardware or setting i2c_dev->msg to NULL.

oaktrail_hdmi_i2c_access() disables the device IRQ and returns the error, freeing the user buffer.

If the hardware finishes the transaction in the background, a subsequent I2C transfer calls hdmi_i2c_irq_enable(), unmasking the interrupt before xfer_read() updates i2c_dev->msg.

The pending interrupt fires immediately, and hdmi_i2c_read() dereferences the stale i2c_dev->msg pointer, overwriting freed memory.

[ ... ]

While reviewing this code, I noticed a couple of pre-existing issues in drivers/gpu/drm/gma500/oaktrail_hdmi_i2c.c:

[Severity: High]
This is a pre-existing issue, but does hdmi_i2c_read() unconditionally write 64 bytes to msg->buf without checking the requested transfer length?

drivers/gpu/drm/gma500/oaktrail_hdmi_i2c.c:hdmi_i2c_read() {
...

	for (i = 0; i < 0x10; i++) {
		temp = HDMI_READ(HDMI_HI2CRDB0 + (i * 4));
		memcpy(buf + (offset + i * 4), &temp, 4);
	}

...
}

If a user issues an I2C_RDWR ioctl with a read message where msg->len is less than 64 (e.g., 1 byte), the I2C core allocates a smaller buffer for msg->buf.

When the hardware fires the FULL interrupt, hdmi_i2c_read() reads 4 bytes per iteration and copies 64 bytes to msg->buf, which could overflow the allocated buffer bounds and corrupt adjacent heap memory.

[Severity: High]
This is a pre-existing issue, but is there a use-after-free race condition in the module teardown path?

drivers/gpu/drm/gma500/oaktrail_hdmi_i2c.c:oaktrail_hdmi_i2c_exit() {
...

	i2c_dev = hdmi_dev->i2c_dev;
	kfree(i2c_dev);
	free_irq(dev->irq, hdmi_dev);

...
}

The teardown logic frees i2c_dev before unregistering the shared interrupt handler.

Since the IRQ is registered with IRQF_SHARED, if another device sharing the IRQ line fires an interrupt before free_irq() runs, oaktrail_hdmi_i2c_handler() executes and dereferences i2c_dev->complete on the freed structure.

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

PATCH 1/1 pinctrl: meson: amlogic-a4: use nolock get range

In reply to Sasha Levin

From: Xianwei Zhao <[email protected]>

[ Upstream commit afa0c07131d8829ea0ebbcd8267c85aa178ce52c ]

Use pinctrl_find_gpio_range_from_pin_nolock() instead of pinctrl_find_gpio_range_from_pin() when configuring a pin or setting a GPIO value.

This avoids taking the lock and allows the code to be safely called from interrupt context.

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: pinctrl: meson: amlogic-a4: use nolock get range

**Local tree:** Linux **6.18.44** (v6.18.44-1-g2736c32da98b9, stable/linux-6.18.y)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Subject line
**Record:** [pinctrl/meson/amlogic-a4] [use] — switch remaining GPIO range lookups to the nolock variant when configuring pins / setting GPIO-related state.

### Step 1.2: Tags
**Record:**
- **Fixes:** — absent (expected for manual review)
- **Reported-by:** — none
- **Tested-by:** — none
- **Reviewed-by:** — none
- **Acked-by:** — none
- **Link:** — none
- **Cc: [email protected]:** — absent
- **Signed-off-by:** Xianwei Zhao, Linus Walleij (ignore pipeline SOB markers)

Notable: no syzbot/fuzzer report; no explicit stable nomination.

### Step 1.3: Body analysis
**Record:**
- **Bug described:** Using pinctrl_find_gpio_range_from_pin() takes pctldev->mutex. When callers already hold that mutex (or run in contexts where locking is unsafe), this causes deadlock or invalid locking.
- **Symptom:** Kernel hang / lockdep issues when configuring pins through paths that already hold the pinctrl mutex.
- **Root cause:** Recursive mutex acquisition in pinconf SET helpers and aml_pmx_set_mux().
- **Version info:** None in message. Driver landed in this tree via 6e9be3abb78c2 (Feb 2025).

### Step 1.4: Hidden bug fix detection
**Record:** Yes — despite neutral wording ("use nolock"), this is a **deadlock fix**, completing the same class of fix already partially backported as e917713f01342 ("fix deadlock issue") which only converted the three pinconf **GET** helpers.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Inventory
**Record:**
- **File:** drivers/pinctrl/meson/pinctrl-amlogic-a4.c only
- **Scope:** 5 call-site replacements (no logic changes)
- **Functions modified:**
- aml_pmx_set_mux()
- aml_pinconf_disable_bias()
- aml_pinconf_enable_bias()
- aml_pinconf_set_drive_strength()
- aml_pinconf_set_gpio_bit()
- **Classification:** Single-file, surgical fix

Note: subject says "get range" but the diff touches **SET** paths (and set_mux), not GET paths — GET paths were already fixed in e917713f01342.

### Step 2.2: Code flow change
**Record (per hunk):**

| Location | Before | After |
|---|---|---|
| All 5 sites | `pinctrl_find_gpio_range_from_pin()` → locks
`pctldev->mutex`, walks `gpio_ranges` |
`pinctrl_find_gpio_range_from_pin_nolock()` → no lock, same list walk |

Affected paths:
- **Pinconf SET** (bias, drive strength, GPIO bit output) — reached from aml_pinconf_set() and its helpers.
- **Pinmux SET** — aml_pmx_set_mux() during function selection.

### Step 2.3: Bug mechanism
**Record:** **Category:** Deadlock / lock ordering (mutex recursion)

Verified chain for pinconf SET:
1. aml_gpio_template.set_config = gpiochip_generic_config (line 959)
2. gpiochip_generic_config() → pinctrl_gpio_set_config() (core.c:919-937)
3. pinctrl_gpio_set_config() **locks** pctldev->mutex (line 931)
4. Calls pinconf_set_config() → aml_pinconf_set() → e.g. aml_pinconf_set_gpio_bit()
5. Helper calls pinctrl_find_gpio_range_from_pin() which tries to **lock the same mutex again** → **DEADLOCK**

This mirrors the already-fixed GET path where pinconf_pins_show() holds the mutex and GET helpers deadlocked.

### Step 2.4: Fix quality
**Record:**
- **Obviously correct:** Yes — pinctrl_find_gpio_range_from_pin_nolock() is the established API for callers that already hold the lock or must not sleep; same pattern used in stm32, airoha, etc.
- **Minimal:** Yes — function name substitution only.
- **Regression risk:** Very low — read-only lookup of the static gpio_ranges list populated at probe time.
- **Red flags:** None.

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame
**Record:** All 5 remaining locking call sites introduced in 6e9be3abb78c2 ("pinctrl: Add driver support for Amlogic SoCs", Feb 2025). Bug present since driver introduction.

### Step 3.2: Fixes: tag
**Record:** N/A — no Fixes: tag. Related fix e917713f01342 (upstream e72ce02981039) addresses the same bug class for GET paths only; confirmed present in this tree.

### Step 3.3: Related file history
**Record:**
- e917713f01342 — partial deadlock fix (3 GET helpers → nolock) — **already in 6.18.44**
- 4a1afa32145b5 — mark GPIO controller can_sleep = true (lockdep fix for shared GPIO proxy)
- 80f8e2302e639 — gpio output glitch fix
- Commit under review ("use nolock get range") — **NOT in this tree**

This is a logical follow-up to e917713f01342, not part of a multi- patch dependency series.

### Step 3.4: Author context
**Record:** Xianwei Zhao authored the original Amlogic pinctrl driver (6e9be3abb78c2) and the prior deadlock fix. Linus Walleij (pinctrl maintainer) merged both.

### Step 3.5: Dependencies
**Record:**
- Requires pinctrl-amlogic-a4.c driver — **present**
- Requires pinctrl_find_gpio_range_from_pin_nolock() — **present** in drivers/pinctrl/core.c since long before this driver
- Requires prior GET-path fix — **optional**; this patch is standalone and applies independently
- **Can apply standalone:** Yes

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original discussion
**Record:**
- b4 dig -c e72ce02981039 found the related v1 thread:
https://patch.msgid.link/20260422-fix-
[email protected]
- That thread covers only the GET-path deadlock fix (same author, same mechanism).
- **No separate lore thread found** for "use nolock get range" in this repo or via b4.
- WebFetch of lore URL blocked by bot protection; mbox saved locally confirms GET-path discussion with Reviewed-by Neil Armstrong.

### Step 4.2: Reviewers
**Record:** Related GET fix reviewed by Neil Armstrong (Linaro/Meson maintainer). This follow-up commit has no explicit Reviewed-by in the provided message; Linus Walleij merged it.

### Step 4.3: Bug report
**Record:** No external bug report, syzbot link, or user Reported-by for this specific commit. Deadlock mechanism inferred from code analysis and prior accepted fix.

### Step 4.4: Series context
**Record:** Companion to e917713f01342 — completes the nolock conversion. Not a multi-part series requiring other patches.

### Step 4.5: Stable list history
**Record:** Prior GET-path fix was backported to this tree (has [ Upstream commit ...] and Sasha Levin SOB from stable pipeline — per instructions, ignored for decision). No stable-list discussion found for this specific follow-up.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key functions
**Record:** aml_pmx_set_mux, aml_pinconf_disable_bias, aml_pinconf_enable_bias, aml_pinconf_set_drive_strength, aml_pinconf_set_gpio_bit

### Step 5.2: Callers
**Record:**
- **Pinconf SET helpers** ← aml_pinconf_set() ← pinconf_apply_setting() (DT pinconf at probe) AND pinconf_set_config() ← pinctrl_gpio_set_config() (GPIO set_config path — **mutex already held**)
- **aml_pmx_set_mux** ← pinmux_enable_setting() (pinctrl state changes, probe)

GPIO chip hooks:
- .set_config = gpiochip_generic_config — triggers the verified deadlock path
- .set = aml_gpio_set — does **not** use pinctrl_find_gpio_range_from_pin() (uses direct register calc)

### Step 5.3: Callees
**Record:** pinctrl_find_gpio_range_from_pin[_nolock]() → walks pctldev->gpio_ranges; then regmap_update_bits() on GPIO/mux registers.

### Step 5.4: Reachability
**Record:**
- **Verified reachable:** gpiod_set_config() / gpiochip_generic_config() on Amlogic A4 GPIOs with CONFIG_PINCTRL — userspace or drivers configuring bias, drive strength, output enable, level.
- **Platform-specific:** Amlogic A4/A5/S6/S7 SoCs only (driver in tree since 6.18 merge window).

### Step 5.5: Similar patterns
**Record:** stm32, airoha, pinctrl-lpc18xx, pinctrl-stmfx all use _nolock in pinconf/pinmux paths. Meson GET paths already converted in e917713f01342.

---

## PHASE 6: CROSS-REFERENCE WITH LOCAL TREE (6.18.44)

### Step 6.1: Buggy code present?
**Record:** **Yes.** Five call sites still use locking variant:
- Line 253: aml_pmx_set_mux
- Lines 452, 465, 487, 522: pinconf SET helpers

Three GET helpers already use nolock (lines 295, 329, 368) from e917713f01342.

### Step 6.2: Backport complications
**Record:** **Clean apply expected** — simple function renames at the same lines the diff shows. No structural divergence since partial fix.

### Step 6.3: Related fixes already present?
**Record:** Partial fix e917713f01342 (GET paths) already in tree. This commit is needed to complete the fix. No duplicate fix for SET paths found.

---

## PHASE 7: SUBSYSTEM CONTEXT

### Step 7.1: Subsystem criticality
**Record:** **PERIPHERAL** — Amlogic SoC pinctrl/GPIO driver. Not core kernel, but pinctrl/GPIO is on critical paths for embedded boards.

### Step 7.2: Activity
**Record:** Actively maintained — 6+ amlogic-a4 commits in this stable tree including deadlock, lockdep, and glitch fixes.

---

## PHASE 8: IMPACT AND RISK

### Step 8.1: Who is affected
**Record:** Users of Amlogic A4/A5/S6/S7 platforms using the pinctrl- amlogic-a4 driver, especially when calling gpiod_set_config() or GPIO set_config on these pins.

### Step 8.2: Trigger conditions
**Record:**
- **Verified trigger:** GPIO pin configuration via gpiochip_generic_config → pinctrl_gpio_set_config (mutex held)
- **Likelihood:** Moderate — any driver or userspace tool setting pin bias/drive/output config on these GPIOs
- **Unprivileged trigger:** Possible if GPIO is accessible to userspace
- **"Interrupt context" claim in commit message:** UNVERIFIED as primary mechanism — pinctrl_gpio_set_config() itself uses mutex_lock(). The verified failure mode is **mutex recursion deadlock**, not hardirq misuse.

### Step 8.3: Failure mode severity
**Record:** **CRITICAL** — task hang / unkillable deadlock when triggered. Same severity class as the already-backported GET-path fix.

### Step 8.4: Risk-benefit
**Record:**
- **Benefit:** HIGH for affected platforms — prevents kernel hang; completes incomplete stable fix
- **Risk:** VERY LOW — 5-line function rename, established API pattern
- **Ratio:** Strongly favors backport

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence summary

**FOR backport:**
- Fixes real, verifiable mutex-recursion deadlock in pinconf SET path
- Completes partial fix (e917713f01342) already in 6.18.44
- Same bug class as already-accepted stable commit
- Small, obviously correct, no new APIs
- Driver and prerequisite API exist in this tree
- Failure mode is system hang (critical)

**AGAINST backport:**
- Platform-specific (Amlogic only) — limited user base
- No syzbot/user report for this specific commit
- Commit message "interrupt context" claim not fully verified
- aml_pmx_set_mux deadlock path not independently verified (change is still safe)

**Unresolved:**
- No lore thread found for this exact follow-up commit
- Whether aml_pmx_set_mux has a mutex-held caller (preventive fix at most)

### Step 9.2: Stable rules checklist
1. Obviously correct and tested? **PASS** — established nolock API; prior GET fix same pattern merged and backported
2. Fixes real bug affecting users? **PASS** — verified deadlock in pinctrl_gpio_set_config → pinconf SET chain
3. Important issue? **PASS** — deadlock / system hang (CRITICAL)
4. Small and contained? **PASS** — 5 call-site changes, 1 file
5. No new features/APIs? **PASS** — uses existing exported nolock helper
6. Can apply to local tree? **PASS** — driver present, clean apply expected

### Step 9.3: Exception categories
**Record:** None (not device ID, quirk, DT, build, or docs). Standard bug fix.

### Step 9.4: Decision rationale
This tree (6.18.44) already carries a **partial** deadlock fix for the Amlogic A4 pinctrl driver. The remaining five locking call sites in pinconf SET helpers create a verified mutex-recursion deadlock when GPIO set_config is used (gpiochip_generic_config → pinctrl_gpio_set_config). Without this commit, stable users on Amlogic platforms can still hit kernel hangs that the prior backport was meant to address. The fix is minimal, follows an established pattern, and completes work already started in this tree.

---

## Verification

- **[Phase 1]** Parsed commit message and tags from user-provided diff
- **[Phase 2]** Diff analysis: 5 pinctrl_find_gpio_range_from_pin → _nolock replacements in SET/mux paths
- **[Phase 3]** git describe HEAD: v6.18.44; git blame lines 252-254, 451-453: introduced in 6e9be3abb78c2
- **[Phase 3]** git log --oneline -10 -- drivers/pinctrl/meson/pinctrl- amlogic-a4.c: found e917713f01342 partial fix
- **[Phase 3]** git merge-base --is-ancestor 6e9be3abb78c2 HEAD:
driver in tree; e917713f01342: partial fix in tree
- **[Phase 3]** git show e917713f01342: confirmed GET-only fix (3 sites)
- **[Phase 3]** git grep pinctrl_find_gpio_range_from_pin( in file: 5 remaining locking calls
- **[Phase 4]** b4 dig -c e72ce02981039: found related GET-fix thread; mbox downloaded
- **[Phase 4]** WebFetch lore URL: blocked (bot protection) — used mbox grep instead
- **[Phase 4]** UNVERIFIED: no lore thread for "use nolock get range" commit specifically
- **[Phase 5]** Traced call chain: gpiochip_generic_config → pinctrl_gpio_set_config (mutex at core.c:931) → aml_pinconf_set_* → locking lookup = deadlock
- **[Phase 5]** Confirmed aml_gpio_set does NOT use pinctrl_find_gpio_range_from_pin
- **[Phase 5]** Confirmed pinctrl_find_gpio_range_from_pin_nolock exists in core.c:484-505
- **[Phase 6]** Read current file: GET paths nolock (295,329,368); SET paths still locking (253,452,465,487,522)
- **[Phase 6]** Commit under review NOT in tree (git log --grep="nolock get range": no match on current branch)
- **[Phase 8]** Deadlock severity: CRITICAL
- **[Phase 8]** UNVERIFIED: "interrupt context" as stated in commit message; verified mechanism is mutex recursion

**YES**The background searches are done. Here’s what they showed:

- **Commit not in this tree:** Searches on the current branch and all- next did not find pinctrl: meson: amlogic-a4: use nolock get range. That matches treating it as a backport candidate, not something already in 6.18.44.
- **Partial fix already present:** e917713f01342 is in the tree and only switched the three pinconf **GET** helpers to pinctrl_find_gpio_range_from_pin_nolock().
- **Buggy code still present:** Five call sites in SET/mux paths still use the locking variant (aml_pmx_set_mux plus four pinconf SET helpers), introduced in 6e9be3abb78c2.

That supports the earlier **YES** verdict: this patch completes an incomplete deadlock fix already started in 6.18.44, with a clean, low- risk apply expected.

 drivers/pinctrl/meson/pinctrl-amlogic-a4.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)
drivers/pinctrl/meson/pinctrl-amlogic-a4.c +5 -5
index 1bd58fbbd26ac..e598373f51663 100644
@@ -250,7 +250,7 @@ static int aml_pmx_set_mux(struct pinctrl_dev *pctldev, unsigned int fselector,
 	int i;
 
 	for (i = 0; i < group->npins; i++) {
-		range =  pinctrl_find_gpio_range_from_pin(pctldev, group->pins[i]);
+		range =  pinctrl_find_gpio_range_from_pin_nolock(pctldev, group->pins[i]);
 		aml_pctl_set_function(info, range, group->pins[i], group->func[i]);
 	}
 
@@ -449,7 +449,7 @@ static int aml_pinconf_disable_bias(struct aml_pinctrl *info,
 				    unsigned int pin)
 {
 	struct pinctrl_gpio_range *range =
-			 pinctrl_find_gpio_range_from_pin(info->pctl, pin);
+			 pinctrl_find_gpio_range_from_pin_nolock(info->pctl, pin);
 	struct aml_gpio_bank *bank = gpio_chip_to_bank(range->gc);
 	unsigned int reg, bit = 0;
 
@@ -462,7 +462,7 @@ static int aml_pinconf_enable_bias(struct aml_pinctrl *info, unsigned int pin,
 				   bool pull_up)
 {
 	struct pinctrl_gpio_range *range =
-			 pinctrl_find_gpio_range_from_pin(info->pctl, pin);
+			 pinctrl_find_gpio_range_from_pin_nolock(info->pctl, pin);
 	struct aml_gpio_bank *bank = gpio_chip_to_bank(range->gc);
 	unsigned int reg, bit, val = 0;
 	int ret;
@@ -484,7 +484,7 @@ static int aml_pinconf_set_drive_strength(struct aml_pinctrl *info,
 					  u16 drive_strength_ua)
 {
 	struct pinctrl_gpio_range *range =
-			 pinctrl_find_gpio_range_from_pin(info->pctl, pin);
+			 pinctrl_find_gpio_range_from_pin_nolock(info->pctl, pin);
 	struct aml_gpio_bank *bank = gpio_chip_to_bank(range->gc);
 	unsigned int reg, bit, ds_val;
 
@@ -519,7 +519,7 @@ static int aml_pinconf_set_gpio_bit(struct aml_pinctrl *info,
 				    bool arg)
 {
 	struct pinctrl_gpio_range *range =
-			 pinctrl_find_gpio_range_from_pin(info->pctl, pin);
+			 pinctrl_find_gpio_range_from_pin_nolock(info->pctl, pin);
 	struct aml_gpio_bank *bank = gpio_chip_to_bank(range->gc);
 	unsigned int reg, bit;
 
Signature · 1 line
2.53.0
author maintainer
#261 lore raw

PATCH 1/1 net/sched: sch_drr: make cl->quantum lockless

In reply to Sasha Levin

From: Eric Dumazet <[email protected]>

[ Upstream commit a4d880b85089e12a5f2e8e2fee386310cec5b99a ]

cl->quantum does not need to be protected by RTNL or qdisc spinlock.

---

LLM Generated explanations, may be completely bogus:

## Phase 1: Commit Message Forensics

### Step 1.1: Parse the Subject Line
**Record:** [net/sched] [make] sch_drr: make cl->quantum lockless — networking traffic-control subsystem; action is making cl->quantum access lockless (concurrency/synchronization change, not labeled "fix").

### Step 1.2: Parse All Commit Message Tags
**Record:**
- **Signed-off-by:** Eric Dumazet <[email protected]> (author)
- **Link:** https://patch.msgid.link/20260519094618.2632073-3- [email protected] (patch 2/2 of series)
- **Signed-off-by:** Jakub Kicinski <[email protected]> (net maintainer merge)
- **No** Fixes:, Reported-by:, Tested-by:, Reviewed-by:, Acked-by:, or
Cc: stable tags
- Notable: part of series titled **"net/sched: sch_drr: lockless cl->deficit and cl->quantum"** (patches 1/2 and 2/2)

### Step 1.3: Analyze Commit Body
**Record:**
- **Bug description:** cl->quantum does not need RTNL or qdisc spinlock protection; access should be lockless with proper annotations.
- **Symptom/failure mode:** Not described — no crash, corruption, or user report mentioned.
- **Version info:** None in message.
- **Root cause (author):** Quantum is read on fast paths without holding sch_tree_lock; locking on write is unnecessary and inconsistent.

### Step 1.4: Detect Hidden Bug Fixes
**Record:** **Yes, likely a hidden concurrency bug fix.** Removing sch_tree_lock() around the write while fast-path readers (drr_enqueue, drr_dequeue, drr_dump_class) access cl->quantum without that lock means the old code had a writer-lock/reader-no-lock pattern. The fix adds WRITE_ONCE/READ_ONCE to make lockless concurrent access formally safe — same pattern as the already-backported companion patch for cl->deficit.

---

## Phase 2: Diff Analysis

### Step 2.1: Inventory the Changes
**Record:**
- **File:** net/sched/sch_drr.c only
- **Scope:** ~4 insertions, ~6 deletions (net −2 lines)
- **Functions modified:** drr_change_class, drr_dump_class, drr_enqueue, drr_dequeue
- **Classification:** Single-file, surgical synchronization fix

### Step 2.2: Code Flow Change (per hunk)
**Record:**
1. **drr_change_class:** Before: update cl->quantum under sch_tree_lock/sch_tree_unlock. After: WRITE_ONCE(cl->quantum, quantum) with no tree lock.
2. **drr_dump_class:** Before: plain cl->quantum read. After:
READ_ONCE(cl->quantum).
3. **drr_enqueue:** Before: WRITE_ONCE(cl->deficit, cl->quantum).
After: WRITE_ONCE(cl->deficit, READ_ONCE(cl->quantum)).
4. **drr_dequeue:** Before: WRITE_ONCE(cl->deficit, cl->deficit + cl->quantum). After: WRITE_ONCE(cl->deficit, cl->deficit + READ_ONCE(cl->quantum)).

### Step 2.3: Bug Mechanism
**Record:** **Category: synchronization / data-race fix.** Fast-path enqueue/dequeue and drr_dump_class read cl->quantum without sch_tree_lock, while drr_change_class wrote it under that lock — ineffective protection against the actual concurrent readers. Fix uses READ_ONCE/WRITE_ONCE for defined lockless u32 access.

### Step 2.4: Fix Quality
**Record:** Fix is minimal, obviously correct, and mirrors the already- applied cl->deficit annotations. Regression risk is very low. Removing sch_tree_lock from the quantum-update path also reduces lock contention during tc class changes under load.

---

## Phase 3: Git History Investigation

### Step 3.1: Blame Changed Lines
**Record:**
- Quantum lock/unlock in drr_change_class: Patrick McHardy, 2008-11-20 (original DRR code).
- WRITE_ONCE for deficit: Eric Dumazet, 2026-05-19 (a88f6da618e8b, already in this tree).
- Buggy pattern (lock on write, lockless reads on fast path) present since DRR introduction (~2.6 era).

### Step 3.2: Follow Fixes: Tag
**Record:** No Fixes: tag in this commit. N/A for direct lookup. Companion patch 1/2 fixes edb09eb17ed89 ("net: sched: do not acquire qdisc spinlock in qdisc/class stats dump"), which **is** in this tree.

### Step 3.3: File History / Related Changes
**Record:**
- a88f6da618e8b — "annotate data-races around cl->deficit" (patch 1/2, **already in 6.18.y**)
- edb09eb17ed89 — lockless stats dump infrastructure (prerequisite context, in tree since 2016)
- f99a3fbf023e2 — double-list-add fix in DRR (unrelated)
- This is patch **2/2** of a 2-patch series; patch 1/2 is already backported here.

### Step 3.4: Author's Other Commits
**Record:** Eric Dumazet is a core networking maintainer. Related sch_drr work in this tree includes the deficit annotation backport and the 2016 lockless stats-dump series.

### Step 3.5: Dependencies / Prerequisites
**Record:** Patch 1/2 (a88f6da618e8b) is **already in this tree**. This patch applies standalone on top of that state. No other dependencies required. The tree currently has an **incomplete** 2-patch
series: deficit annotated, quantum not.

---

## Phase 4: Mailing List and External Research

### Step 4.1: Original Patch Discussion
**Record:** Series found via web search (lore fetch blocked by bot protection):
- Cover: [PATCH net-next 0/2] net/sched: sch_drr: lockless cl->deficit and cl->quantum
- Patch 1/2: annotate data-races around cl->deficit
- Patch 2/2: make cl->quantum lockless (this commit)
- URL: https://www.spinics.net/lists/netdev/msg1188405.html
- b4 dig -c could not be run (commit not in local repo). No NAKs found in search results.

### Step 4.2: Reviewers
**Record:** CC list from syzbot CI series page includes davem@, kuba@, netdev@, pabeni@, jhs@, victor@. Patchwork-bot reported on cover letter (2026-05-21). Full reviewer thread not retrieved.

### Step 4.3: Bug Reports
**Record:** No Reported-by, no syzbot crash report, no bugzilla link. Syzbot CI
(https://ci.syzbot.org/series/3c50e02b-b07f-4d23-a7d3-45d5a6e23096) ran build/boot/fuzz — all **passed**; no bug was filed against this series.

### Step 4.4: Related Patches / Series
**Record:** 2-patch series. Patch 1/2 already backported to this 6.18.y tree (July 2026). This commit completes the series.

### Step 4.5: Stable Mailing List
**Record:** Not searched (no stable-specific discussion found in available sources). Absence of Cc: stable is expected per instructions.

---

## Phase 5: Code Semantic Analysis

### Step 5.1: Key Functions
**Record:** drr_change_class, drr_dump_class, drr_enqueue, drr_dequeue

### Step 5.2: Callers / Context
**Record:**
- drr_enqueue/drr_dequeue: packet scheduling fast path (softirq/NAPI), high frequency.
- drr_change_class: netlink tc class configuration (administrative).
- drr_dump_class: tc class show dump via cl_ops->walk in tc_dump_tclass_qdisc — **without** qdisc spinlock (same pattern as stats dump after edb09eb17ed89).

### Step 5.3: Callees
**Record:** WRITE_ONCE, READ_ONCE, sch_tree_lock/sch_tree_unlock (removed from quantum path), nla_put_u32, list_add_tail, qdisc_pkt_len.

### Step 5.4: Reachability
**Record:** All paths reachable — packet forwarding (every enqueued packet) and tc administration. Users with CAP_NET_ADMIN can trigger quantum changes; any traffic through a DRR qdisc reads quantum on enqueue/dequeue.

### Step 5.5: Similar Patterns
**Record:** Patch 1/2 applied the identical READ_ONCE/WRITE_ONCE pattern to cl->deficit in the same functions. sch_htb.c and sch_ets.c still use plain cl->quantum access (not part of this commit).

---

## Phase 6: Cross-Referencing Against the Local Tree

### Step 6.1: Does the Buggy Code Exist?
**Record:** **Yes.** Local tree is **v6.18.44** (linux-6.18.y stable). Current code at lines 100–103 still uses sch_tree_lock + plain cl->quantum = quantum; lines 365/406 read cl->quantum without READ_ONCE inside WRITE_ONCE deficit updates. READ_ONCE/WRITE_ONCE for quantum: **not present** (verified via grep).

### Step 6.2: Backport Complications
**Record:** **Clean apply expected.** Patch 1/2 already present; diff applies directly on current sch_drr.c. Minor context differences possible (e.g., kzalloc vs kzalloc_obj, qstats_backlog_add vs direct sch->qstats — user's diff shows mainline variants; stable tree may need trivial context adjustment only).

### Step 6.3: Related Fixes Already Present?
**Record:** Patch 1/2 (a88f6da618e8b, deficit annotations) **already backported** (2026-07-24). This quantum patch is the **missing half** of that series. No duplicate quantum fix found.

---

## Phase 7: Subsystem and Maintainer Context

### Step 7.1: Subsystem Criticality
**Record:** net/sched — **IMPORTANT** subsystem. DRR itself is a less- common qdisc, but the code path is standard packet scheduling infrastructure.

### Step 7.2: Subsystem Activity
**Record:** Moderately active; recent sch_drr changes include deficit annotations (2026), qlen_notify idempotency (2025), extack support.

---

## Phase 8: Impact and Risk Assessment

### Step 8.1: Who Is Affected
**Record:** Users of DRR qdisc (sch_drr) with concurrent tc class modification and traffic — config-specific, not universal. Google BwE- scale tc dumps were the original motivation for the broader lockless- stats work.

### Step 8.2: Trigger Conditions
**Record:** Concurrent tc class change (quantum update) while packets are enqueued/dequeued, or while tc class show dumps quantum. Requires DRR in use and concurrent admin + traffic. Not unprivileged-triggerable for the write side; reads happen on every packet.

### Step 8.3: Failure Mode Severity
**Record:** Without fix: C11/KCSAN data race; in practice, reading a slightly stale or mid-update u32 quantum value. **Severity: LOW to MEDIUM** — may cause transient scheduling inaccuracy, not kernel crash, panic, memory corruption, or security escalation. No crash reports exist.

### Step 8.4: Risk-Benefit
**Record:**
- **Benefit:** Completes data-race fix series already partially in tree; consistent lockless access; slightly less lock contention on tc changes; KCSAN-correct.
- **Risk:** Very low — 10-line change, established READ_ONCE/WRITE_ONCE idiom.
- **Ratio:** Moderate benefit for DRR users; very low risk. Strongest argument is **series completeness** after patch 1/2 was already accepted for this tree.

---

## Phase 9: Final Synthesis

### Step 9.1: Evidence Summary

**FOR backport:**
- Completes 2-patch series; patch 1/2 already in 6.18.y
- Fixes real data race on cl->quantum in fast path and dump path
- Same author, same rationale as already-backported deficit fix
- Small, surgical, obviously correct
- Syzbot CI passed on full series
- Prerequisites (edb09eb17ed89, patch 1/2) present in tree

**AGAINST backport:**
- No user crash reports, no syzbot bug, no CVE
- Failure mode is benign (stale quantum value), not crash/corruption
- Race existed since 2008; newly highlighted, not newly introduced catastrophic bug
- DRR is niche compared to HTB/fq_codel
- Partially a performance improvement (removing unnecessary sch_tree_lock)

**Unresolved:** Full lore reviewer thread not retrieved; no explicit stable nomination found.

### Step 9.2: Stable Rules Checklist
1. Obviously correct and tested? **PASS** — idiomatic READ_ONCE/WRITE_ONCE; syzbot CI green.
2. Fixes a real bug? **PASS** — data race with concurrent lockless readers; same class as already-backported patch 1/2.
3. Important issue? **BORDERLINE PASS** — not crash/security level, but correctness under concurrent tc + traffic; series completion after partial backport.
4. Small and contained? **PASS** — single file, ~10 lines.
5. No new features/APIs? **PASS** — synchronization annotations only.
6. Can apply to local tree? **PASS** — code present; patch 1/2 prerequisite satisfied.

### Step 9.3: Exception Categories
**Record:** None (not device ID, quirk, DT, build fix, or docs).

### Step 9.4: Decision Rationale

For **linux-6.18.y** specifically: patch 1/2 of this series is already backported, leaving cl->deficit properly annotated but cl->quantum still racy in the exact same functions (drr_enqueue, drr_dequeue, dump paths). Backporting this commit completes a maintainer-intended, already-half-applied concurrency fix with negligible risk. While the user-visible severity is low (no crashes reported), the technical merit and series consistency strongly favor inclusion in this tree.

---

## Verification

- [Phase 1] Parsed subject, tags, body from user-provided commit message
- [Phase 2] Analyzed full diff (4 hunks, 1 file); classified as data- race fix
- [Phase 3] git describe HEAD → v6.18.44; git blame on lines 100–103, 365, 406
- [Phase 3] git log --oneline -20 -- net/sched/sch_drr.c — found a88f6da618e8b (patch 1/2)
- [Phase 3] git show a88f6da618e8b — deficit annotations, Fixes edb09eb17ed89, already in tree
- [Phase 3] git log --grep='quantum lockless' / 'make cl->quantum' — **no results** (patch 2/2 absent)
- [Phase 3] git merge-base --is-ancestor edb09eb17ed89 HEAD → prerequisite present
- [Phase 4] Web search found spinics.net series page and syzbot CI page; lore fetch blocked
- [Phase 4] Syzbot CI: build/boot/fuzz passed, no bug filed
- [Phase 5] Read net/sched/sch_drr.c — confirmed current buggy state (plain cl->quantum reads)
- [Phase 5] grep READ_ONCE(cl->quantum) in net/sched/ → **no matches**
- [Phase 5] Read tc_dump_tclass_qdisc in sch_api.c — dump walks classes without spinlock
- [Phase 6] Confirmed tree is 6.18.y stable; buggy code present; patch 1/2 backported July 2026
- [Phase 8] Assessed severity as LOW-MEDIUM (scheduling inaccuracy, not crash)

**YES**The background check finished: **patch 1/2** (a88f6da618e8b — deficit READ_ONCE/WRITE_ONCE annotations) is already in this **6.18.44** tree, and **patch 2/2** (make cl->quantum lockless) is not — git log --grep='quantum lockless' and --grep='make cl->quantum' both came up empty.

That matches the earlier analysis: the series is only half-applied here, and backporting this commit would complete it. Verdict remains **YES**.

 net/sched/sch_drr.c | 10 ++++------
 1 file changed, 4 insertions(+), 6 deletions(-)
net/sched/sch_drr.c +4 -6
index 44686fd1c2749..faafb29056259 100644
@@ -97,10 +97,8 @@ static int drr_change_class(struct Qdisc *sch, u32 classid, u32 parentid,
 			}
 		}
 
-		sch_tree_lock(sch);
 		if (tb[TCA_DRR_QUANTUM])
-			cl->quantum = quantum;
-		sch_tree_unlock(sch);
+			WRITE_ONCE(cl->quantum, quantum);
 
 		return 0;
 	}
@@ -251,7 +249,7 @@ static int drr_dump_class(struct Qdisc *sch, unsigned long arg,
 	nest = nla_nest_start_noflag(skb, TCA_OPTIONS);
 	if (nest == NULL)
 		goto nla_put_failure;
-	if (nla_put_u32(skb, TCA_DRR_QUANTUM, cl->quantum))
+	if (nla_put_u32(skb, TCA_DRR_QUANTUM, READ_ONCE(cl->quantum)))
 		goto nla_put_failure;
 	return nla_nest_end(skb, nest);
 
@@ -362,7 +360,7 @@ static int drr_enqueue(struct sk_buff *skb, struct Qdisc *sch,
 
 	if (!cl_is_active(cl)) {
 		list_add_tail(&cl->alist, &q->active);
-		WRITE_ONCE(cl->deficit, cl->quantum);
+		WRITE_ONCE(cl->deficit, READ_ONCE(cl->quantum));
 	}
 
 	sch->qstats.backlog += len;
@@ -403,7 +401,7 @@ static struct sk_buff *drr_dequeue(struct Qdisc *sch)
 			return skb;
 		}
 
-		WRITE_ONCE(cl->deficit, cl->deficit + cl->quantum);
+		WRITE_ONCE(cl->deficit, cl->deficit + READ_ONCE(cl->quantum));
 		list_move_tail(&cl->alist, &q->active);
 	}
 out:
Signature · 1 line
2.53.0
author maintainer
#262 lore raw

PATCH 1/1 HID: bpf: Add Huion Inspiroy Frego M button quirk

In reply to Sasha Levin

From: Nikhil Chatterjee <[email protected]>

[ Upstream commit 857e71cb0a538b1660743a4267a1e789575f7966 ]

The Huion Inspiroy Frego M pen report descriptor exposes the second side button as Secondary Tip Switch instead of Secondary Barrel Switch. This makes userspace see the control as the wrong pen button.

Add a HID-BPF report descriptor fixup for the Bluetooth 256c:8251 device and USB 256c:2012 L610 variant. The fixup matches the expected pen descriptor and rewrites the offending usage from Secondary Tip Switch to Secondary Barrel Switch.

Tested by building the HID-BPF object with:

make -C drivers/hid/bpf/progs Huion__Inspiroy-Frego-M.bpf.o

---

LLM Generated explanations, may be completely bogus:

The background git searches finished and match the earlier analysis:

- **git log --grep="Frego" / --grep="Inspiroy Frego"** — no matches in this tree; the quirk is not present in 6.18.44.
- **git log --grep="8251" under drivers/hid/** — only an unrelated HID debugging commit, not this device.

That confirms the patch would be a new addition here, consistent with the **YES** backport recommendation.

 .../bpf/progs/Huion__Inspiroy-Frego-M.bpf.c   | 87 +++++++++++++++++++
 1 file changed, 87 insertions(+)
 create mode 100644 drivers/hid/bpf/progs/Huion__Inspiroy-Frego-M.bpf.c
drivers/hid/bpf/progs/Huion__Inspiroy-Frego-M.bpf.c new file +87 -0
new file mode 100644
index 0000000000000..e6ba2295dc775
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: GPL-2.0-only
+#include "vmlinux.h"
+#include "hid_bpf.h"
+#include "hid_bpf_helpers.h"
+#include <bpf/bpf_tracing.h>
+
+/*
+ * Huion Inspiroy Frego M Pen Tablet
+ * Model L610
+ * 256c:8251 (Bluetooth)
+ * 256c:2012 (USB)
+ */
+#define VID_HUION			0x256C
+#define PID_INSPIROY_FREGO_M		0x8251
+#define PID_L610			0x2012
+
+#define PEN_RDESC_SIZE			125
+#define SECONDARY_SWITCH_OFFSET		17
+
+HID_BPF_CONFIG(
+	HID_DEVICE(BUS_BLUETOOTH, HID_GROUP_GENERIC, VID_HUION, PID_INSPIROY_FREGO_M),
+	HID_DEVICE(BUS_USB, HID_GROUP_GENERIC, VID_HUION, PID_L610)
+);
+
+/*
+ * The pen descriptor reports the second side button as Secondary Tip Switch
+ * instead of Secondary Barrel Switch.
+ *
+ * Relevant part of the original pen report descriptor:
+ *
+ * 0x09, 0x42,       // Usage (Tip Switch)                  12
+ * 0x09, 0x44,       // Usage (Barrel Switch)               14
+ * 0x09, 0x43,       // Usage (Secondary Tip Switch)        16 <- change to 0x5a
+ * 0x09, 0x3c,       // Usage (Invert)                      18
+ * 0x09, 0x45,       // Usage (Eraser)                      20
+ * 0x15, 0x00,       // Logical Minimum (0)                 22
+ * 0x25, 0x01,       // Logical Maximum (1)                 24
+ */
+SEC(HID_BPF_RDESC_FIXUP)
+int BPF_PROG(fix_secondary_barrel_rdesc, struct hid_bpf_ctx *hctx)
+{
+	__u8 *data = hid_bpf_get_data(hctx, 0 /* offset */, HID_MAX_DESCRIPTOR_SIZE /* size */);
+
+	if (!data)
+		return 0; /* EPERM check */
+
+	if (hctx->size != PEN_RDESC_SIZE)
+		return 0;
+
+	if (data[0] != 0x05 || data[1] != 0x0d || /* Usage Page (Digitizers) */
+	    data[2] != 0x09 || data[3] != 0x02 || /* Usage (Pen) */
+	    data[16] != 0x09 ||
+	    data[SECONDARY_SWITCH_OFFSET] != 0x43) /* Secondary Tip Switch */
+		return 0;
+
+	data[SECONDARY_SWITCH_OFFSET] = 0x5a;
+
+	return 0;
+}
+
+HID_BPF_OPS(fix_secondary_barrel) = {
+	.hid_rdesc_fixup = (void *)fix_secondary_barrel_rdesc,
+};
+
+SEC("syscall")
+int probe(struct hid_bpf_probe_args *ctx)
+{
+	ctx->retval = ctx->rdesc_size != PEN_RDESC_SIZE;
+	if (ctx->retval) {
+		ctx->retval = -EINVAL;
+		return 0;
+	}
+
+	if (ctx->rdesc[0] != 0x05 || ctx->rdesc[1] != 0x0d || /* Usage Page (Digitizers) */
+	    ctx->rdesc[2] != 0x09 || ctx->rdesc[3] != 0x02 || /* Usage (Pen) */
+	    ctx->rdesc[16] != 0x09 ||
+	    ctx->rdesc[SECONDARY_SWITCH_OFFSET] != 0x43) { /* Secondary Tip Switch */
+		ctx->retval = -EINVAL;
+		return 0;
+	}
+
+	ctx->retval = 0;
+
+	return 0;
+}
+
+char _license[] SEC("license") = "GPL";
Signature · 1 line
2.53.0
author maintainer
#263 lore raw

PATCH 1/1 btrfs: use lockless read in nr_cached_objects shrinker callback

In reply to Sasha Levin

From: Ben Maurer <[email protected]>

[ Upstream commit 1ba72d847c7aa3c0887f749115af5232fd61b598 ]

Under heavy memcg-driven slab reclaim with many memcgs and CPUs, shrink_slab_memcg() invokes the per-superblock count callback once per (memcg, NUMA node) tuple. For btrfs that callback reaches percpu_counter_sum_positive() on fs_info->evictable_extent_maps, which takes the percpu_counter's raw spinlock with IRQs disabled and walks every online CPU. With hundreds of memcgs driving reclaim on a host with dozens of CPUs, this counter lock becomes a global serialization point:
profiles show CPU pinned in the spin_lock_irqsave acquire under __percpu_counter_sum, with cross-CPU IPIs hitting csd_lock_wait_toolong while waiting for spinning vCPUs.

The shrinker count is advisory -- super_cache_count() already notes "counts can change between super_cache_count and super_cache_scan, so we really don't need locks here." Use percpu_counter_read_positive(), which is lockless. Worst-case skew is bounded by batch * num_online_cpus (a few thousand), negligible compared to the millions of extent maps a busy filesystem accumulates and well within the noise that the shrinker already tolerates.

---

LLM Generated explanations, may be completely bogus:

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: PARSE THE SUBJECT LINE
**Record:** [btrfs] [use] — Replace the locked percpu_counter_sum_positive() call in the extent-map shrinker count callback with the lockless percpu_counter_read_positive().

### Step 1.2: PARSE ALL COMMIT MESSAGE TAGS
**Record:**
- **Tested-by:** Boris Burkov <[email protected]> — fix verified on real workload
- **Reviewed-by:** Qu Wenruo <[email protected]> — btrfs maintainer
- **Reviewed-by:** Shakeel Butt <[email protected]> — memcg/mm maintainer
- **Signed-off-by:** Ben Maurer <[email protected]> — author
- **Signed-off-by:** David Sterba <[email protected]> — btrfs maintainer
- No Fixes:, Reported-by:, Link:, or Cc: [email protected] tags (expected for manual review)
- Notable: dual maintainer review (btrfs + memcg), production-scale author (Meta)

### Step 1.3: ANALYZE THE COMMIT BODY TEXT
**Record:**
- **Bug:** Under heavy memcg-driven slab reclaim with many memcgs and CPUs, shrink_slab_memcg() invokes the per-superblock count callback once per (memcg, NUMA node) tuple. For btrfs this reaches percpu_counter_sum_positive() on fs_info->evictable_extent_maps, which takes a raw spinlock with IRQs disabled and walks every online CPU.
- **Symptom:** Global serialization — CPUs pinned in spin_lock_irqsave under __percpu_counter_sum, cross-CPU IPIs hitting csd_lock_wait_toolong while waiting for spinning vCPUs.
- **Root cause:** Using the expensive accurate-sum API in an advisory shrinker count path that explicitly does not require locks or precision.
- **Fix rationale:** super_cache_count() already documents that counts are advisory and locks are unnecessary; use lockless percpu_counter_read_positive() instead.
- **Accuracy bound:** Worst-case skew ≤ batch * num_online_cpus (a few thousand), negligible vs. millions of extent maps.

### Step 1.4: DETECT HIDDEN BUG FIXES
**Record:** Yes — described as a performance optimization, but it fixes a scalability defect in the memory-reclaim hot path. The VFS shrinker framework deliberately avoids locking in super_cache_count(); btrfs's locked sum undermines that design and can stall reclaim under memory pressure. This is a correctness-of-API-usage fix with stability impact, not mere throughput tuning.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: INVENTORY THE CHANGES
**Record:**
- **Files:** fs/btrfs/super.c only (+0/-0 net, 1 line changed)
- **Functions:** btrfs_nr_cached_objects()
- **Scope:** Single-file, single-line surgical fix

### Step 2.2: UNDERSTAND THE CODE FLOW CHANGE
**Record:**
- **Hunk (line 2413):** Before:
percpu_counter_sum_positive(&fs_info->evictable_extent_maps) — acquires fbc->lock, iterates all online/dying CPUs, sums per-CPU values. After:
percpu_counter_read_positive(&fs_info->evictable_extent_maps) — single READ_ONCE(fbc->count), no lock, no cross-CPU walk.
- **Execution path:** Called from super_cache_count() → sb->s_op->nr_cached_objects() during shrink_slab_memcg() reclaim, potentially once per (memcg, node) per shrinker invocation.

### Step 2.3: IDENTIFY THE BUG MECHANISM
**Record:**
- **Category:** Scalability / lock-contention bug in hot reclaim path (synchronization misuse)
- **Mechanism:** __percpu_counter_sum() in lib/percpu_counter.c takes a global raw spinlock and walks every CPU. Invoked repeatedly from memcg-aware superblock shrinker counting. Creates a global serialization point exactly when the system is under memory pressure and needs fast reclaim.

### Step 2.4: ASSESS THE FIX QUALITY
**Record:**
- **Quality:** Obviously correct — direct API substitution; matches VFS shrinker contract and btrfs precedent in space-info.c (commit 2cdb3909c9e95).
- **Regression risk:** Very low. Under-counting bounded by percpu_counter_batch (32) × num_cpus; shrinker counts are advisory per fs/super.c:247-249. xfs uses the same estimate-vs-sum pattern (xfs_estimate_freecounter()).
- **No new APIs, no behavior change beyond count approximation in an already-tolerant path.**

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: BLAME THE CHANGED LINES
**Record:**
- btrfs_nr_cached_objects() introduced in 956a17d9d0507 ("btrfs: add a shrinker for extent maps", 2024-05-07) by Filipe Manana
- percpu_counter_sum_positive() line from 0d89a15e1a0dcc (tracepoints commit, 2024-04-09)
- Bug present since extent-map shrinker landed (~kernel 6.9); confirmed ancestor of current HEAD (6.18.44)

### Step 3.2: FOLLOW THE FIXES: TAG
**Record:** N/A — no Fixes: tag present.

### Step 3.3: CHECK FILE HISTORY FOR RELATED CHANGES **Record:**
- 956a17d9d0507 — added extent map shrinker and btrfs_nr_cached_objects
- f1d97e7691528 — added evictable_extent_maps percpu counter
- 2cdb3909c9e95 — btrfs already switched need_preemptive_reclaim() from sum_positive to read_positive for same reason (perf/lock avoidance)
- 15b3b3254d145 — extent map shrinker iput fix
- Standalone 1-line fix, not part of a series

### Step 3.4: CHECK THE AUTHOR'S OTHER COMMITS **Record:** No prior commits from Ben Maurer in this tree's btrfs history. David Sterba (committer) is btrfs maintainer.

### Step 3.5: CHECK FOR DEPENDENT/PREREQUISITE COMMITS **Record:** No dependencies. Requires only evictable_extent_maps counter and btrfs_nr_cached_objects() — both present in 6.18.44. Applies cleanly as a single-line change.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: FIND THE ORIGINAL PATCH DISCUSSION
**Record:** UNVERIFIED — commit not yet in this tree (no SHA for b4 dig -c). b4 dig subject search not supported. lore.kernel.org returned 403 (bot protection). Review tags in commit message are the available review evidence.

### Step 4.2: CHECK WHO REVIEWED THE PATCH
**Record:** From commit message: Qu Wenruo (btrfs), Shakeel Butt (memcg/mm), David Sterba (btrfs maintainer/committer). Appropriate reviewers for this change.

### Step 4.3: SEARCH FOR THE BUG REPORT
**Record:** N/A — no Reported-by: or Link: tags. Issue identified via production profiling at Meta (per commit body).

### Step 4.4: CHECK FOR RELATED PATCHES AND SERIES **Record:** Standalone fix. Direct precedent: 2cdb3909c9e95 (same sum→read change in btrfs space-info.c).

### Step 4.5: CHECK STABLE MAILING LIST HISTORY **Record:** UNVERIFIED — lore.kernel.org inaccessible.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: IDENTIFY KEY FUNCTIONS IN THE DIFF **Record:** btrfs_nr_cached_objects() (modified); callers:
super_cache_count() in fs/super.c

### Step 5.2: TRACE CALLERS
**Record:**
- super_cache_count() → shrinker->count_objects for superblock shrinker (s->s_shrink, SHRINKER_MEMCG_AWARE | SHRINKER_NUMA_AWARE)
- Invoked from do_shrink_slab() → shrink_slab_memcg() → shrink_slab() during memory reclaim
- Hot path under memory pressure; frequency scales with num_memcgs × num_nodes × num_shrinkers

### Step 5.3: TRACE CALLEES
**Record:**
- Before: percpu_counter_sum_positive() → __percpu_counter_sum() → raw_spin_lock_irqsave + per-CPU iteration
- After: percpu_counter_read_positive() → READ_ONCE(fbc->count) (from include/linux/percpu_counter.h:118-126)

### Step 5.4: FOLLOW THE CALL CHAIN
**Record:** Memory reclaim (kernel-initiated under pressure, triggered by allocation failures or memcg limits) → shrink_slab → superblock shrinker count → btrfs extent map count. Reachable whenever btrfs is mounted and memory reclaim runs. Container hosts with many memcgs are the high-impact scenario.

### Step 5.5: SEARCH FOR SIMILAR PATTERNS
**Record:**
- btrfs space-info.c:1031-1032 — already uses read_positive for heuristic decisions
- xfs xfs_mount.h:733-736 — xfs_estimate_freecounter() uses read_positive with comment "just provides an estimate"
- backing-dev.h, mm.h — same read-vs-sum pattern for hot paths vs. accurate counts

---

## 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.44** (git describe HEAD = v6.18.44). fs/btrfs/super.c:2413 still uses percpu_counter_sum_positive(). Extent map shrinker present since 956a17d9d0507 (May 2024, in 6.18.y ancestry).

### Step 6.2: CHECK FOR BACKPORT COMPLICATIONS **Record:** Clean apply expected — single-line substitution, no structural changes needed. No recent churn around btrfs_nr_cached_objects().

### Step 6.3: CHECK IF RELATED FIXES ARE ALREADY HERE **Record:** The space-info.c precedent fix (2cdb3909c9e95) is already in tree. This specific shrinker callback fix is NOT yet applied.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

### Step 7.1: IDENTIFY THE SUBSYSTEM AND ITS CRITICALITY **Record:** **btrfs filesystem** / memory reclaim interaction. **Criticality: IMPORTANT** — affects memory reclaim behavior for all btrfs mounts under memory pressure; severity scales with memcg count.

### Step 7.2: ASSESS SUBSYSTEM ACTIVITY
**Record:** btrfs actively maintained in 6.18.y with regular merges from for-6.17/6.18 tags. Extent map shrinker is relatively new (2024) but stable in tree.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: DETERMINE WHO IS AFFECTED
**Record:** btrfs users under memory pressure, especially:
- Systems with CONFIG_MEMCG and many cgroups (containers/K8s)
- Multi-socket / many-CPU hosts
- btrfs root or btrfs data volumes on memory-constrained systems

### Step 8.2: DETERMINE THE TRIGGER CONDITIONS **Record:** Heavy memcg-driven slab reclaim + btrfs mounted + many (memcg, node) tuples. Common on container hosts; not every boot, but realistic in production. Unprivileged users can trigger via memory allocation within their cgroup.

### Step 8.3: DETERMINE THE FAILURE MODE SEVERITY **Record:** Global spinlock contention during reclaim → CPU spinning, cross-CPU IPI stalls (csd_lock_wait_toolong), severely degraded reclaim throughput, potential soft-lockup warnings and system unresponsiveness under memory pressure. **Severity: HIGH** (stability under memory pressure, not data corruption or security).

### Step 8.4: CALCULATE RISK-BENEFIT RATIO
**Record:**
- **Benefit:** HIGH for affected deployments — removes global lock from hot reclaim path; aligns btrfs with VFS shrinker design
- **Risk:** VERY LOW — 1-line change, bounded count imprecision already tolerated by shrinker framework
- **Ratio:** Strong benefit, minimal risk

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: COMPILE THE EVIDENCE

**FOR backporting:**
- Real production issue (Meta, profiled lock contention)
- Reviewed by btrfs and memcg maintainers; Tested-by present
- 1-line, obviously correct fix
- VFS explicitly documents shrinker counts need no locks (fs/super.c:247-249)
- Direct btrfs precedent (2cdb3909c9e95) and xfs pattern (xfs_estimate_freecounter)
- Bug present in 6.18.44 since extent map shrinker (6.9+)
- Can cause severe reclaim stalls under memory pressure — stability- relevant per stable rules for perf fixes that prevent lockups

**AGAINST backporting:**
- Primarily a scalability/performance issue, not crash/corruption/security
- Only affects btrfs + memcg + high-scale configurations
- Approximate count could theoretically under-report objects (bounded, maintainer-accepted)

**UNRESOLVED:**
- Mailing list thread and stable-list discussion (lore inaccessible, commit not in tree for b4 dig)

### Step 9.2: STABLE RULES CHECKLIST
1. Obviously correct and tested? **PASS** — maintainer-reviewed, Tested- by, matches established API-usage pattern
2. Fixes a real bug affecting users? **PASS** — lock contention in reclaim path on production workloads
3. Important issue? **PASS** — HIGH severity stability under memory pressure (reclaim stalls, potential lockup warnings)
4. Small and contained? **PASS** — 1 line, 1 file
5. No new features or APIs? **PASS**
6. Can apply to local tree? **PASS** — buggy code confirmed present, clean apply

### Step 9.3: EXCEPTION CATEGORIES
**Record:** N/A — not a device ID, quirk, DT, build, or docs fix. Standard bug fix.

### Step 9.4: DECISION RATIONALE

This commit fixes btrfs using the wrong percpu_counter API in a shrinker count callback. The VFS shrinker framework deliberately avoids locking because counts are advisory; btrfs's use of percpu_counter_sum_positive() introduces a global spinlock into a path invoked repeatedly per (memcg, node) during reclaim. On large container hosts this creates a serialization bottleneck during exactly the operation (memory reclaim) that must remain fast.

The fix is minimal, maintainer-reviewed, has direct precedent in the same btrfs codebase, and carries negligible regression risk. While not a traditional crash or corruption bug, it causes serious stability degradation under memory pressure — a scenario stable trees must handle well.

---

## Verification

- [Phase 1] Parsed commit message tags: Tested-by, 2× Reviewed-by, 2× Signed-off-by; no Fixes/Reported-by/Link
- [Phase 2] Diff analysis: 1-line change in btrfs_nr_cached_objects(), sum_positive → read_positive
- [Phase 2] Read include/linux/percpu_counter.h:97-126: confirmed sum_positive locks and iterates CPUs; read_positive is lockless READ_ONCE
- [Phase 2] Read lib/percpu_counter.c:159-185: __percpu_counter_sum documented as "more accurate but much slower"
- [Phase 3] git describe HEAD: v6.18.44 / 6.18.44
- [Phase 3] git blame fs/btrfs/super.c:2410-2418: function from 956a17d9d0507 (2024-05-07)
- [Phase 3] git merge-base --is-ancestor 956a17d9d0507 HEAD: shrinker commit in 6.18.y
- [Phase 3] git show 2cdb3909c9e95: btrfs precedent for same API change
- [Phase 4] UNVERIFIED: b4 dig failed (no commit SHA in tree); lore.kernel.org returned 403
- [Phase 5] Read fs/super.c:235-262: super_cache_count() explicitly avoids locks, notes counts are advisory
- [Phase 5] Read fs/super.c:377-385: superblock shrinker is SHRINKER_MEMCG_AWARE | SHRINKER_NUMA_AWARE
- [Phase 5] Read mm/shrinker.c:478-594: shrink_slab_memcg() iterates shrinkers per memcg/node
- [Phase 5] Read fs/xfs/xfs_mount.h:729-736: xfs uses read_positive for estimates
- [Phase 6] grep fs/btrfs/super.c: buggy percpu_counter_sum_positive confirmed at line 2413
- [Phase 6] git log -S evictable_extent_maps: counter and shrinker both in tree since 2024
- [Phase 8] percpu_counter_batch default = 32 (lib/percpu_counter.c:255)

**YES**

 fs/btrfs/super.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/btrfs/super.c +1 -1
index 9dc399e5dc091..d3661be700810 100644
@@ -2435,7 +2435,7 @@ static int btrfs_show_devname(struct seq_file *m, struct dentry *root)
 static long btrfs_nr_cached_objects(struct super_block *sb, struct shrink_control *sc)
 {
 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
-	const s64 nr = percpu_counter_sum_positive(&fs_info->evictable_extent_maps);
+	const s64 nr = percpu_counter_read_positive(&fs_info->evictable_extent_maps);
 
 	trace_btrfs_extent_map_shrinker_count(fs_info, nr);
 
Signature · 1 line
2.53.0
author maintainer
#264 lore raw

PATCH 1/1 clk: clk-axi-clkgen: Add support versal timings

In reply to Sasha Levin

From: Nuno Sá <[email protected]>

[ Upstream commit 0aef2f0db6db22c2a441e067d8e8458106fb0483 ]

Add proper VCO and PFD limits for versal based platforms. For that we need to add new Technology and Speed grade defines.

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: clk: clk-axi-clkgen: Add support versal timings

**Local tree:** v6.18.43 (linux-6.18.y stable, HEAD 7b923c78b50d)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Subject Line
**Record:** [clk: clk-axi-clkgen] [Add] — Add support for Versal FPGA VCO/PFD timing limits in the existing AXI clkgen driver.

### Step 1.2: Commit Message Tags
**Record:**
- **Signed-off-by:** Nuno Sá <[email protected]> (author)
- **Reviewed-by:** Brian Masney <[email protected]>
- **Signed-off-by:** Stephen Boyd <[email protected]> (clk maintainer merge)
- **No** Fixes:, Reported-by:, Tested-by:, Link:, Cc:
[email protected]

Notable: Reviewed by a Red Hat contributor; merged by clk subsystem maintainer. No user/fuzzer bug reports in the message.

### Step 1.3: Commit Body Analysis
**Record:**
- **Bug described:** Versal-based platforms need correct VCO and PFD limits; current driver lacks the technology/speed-grade definitions and limit overrides.
- **Symptom/failure mode:** Without proper limits, the driver either rejects unknown speed grades at probe time or programs the MMCM/PLL with out-of-spec VCO frequency bounds for Versal silicon.
- **Version info:** None stated.
- **Root cause:** axi_clkgen_setup_limits() handles Series7/Ultrascale/Ultrascale+ but not Versal (ADI_AXI_FPGA_TECH_VERSAL) or the Versal-specific ADI_AXI_FPGA_SPEED_2MP speed grade.

### Step 1.4: Hidden Bug Fix Detection
**Record:** **Yes — disguised as "Add support".** The subject says "add support," but the change corrects two concrete failures in existing code:
1. Speed grade 2MP (value 23) falls through the switch to default → probe returns -ENODEV.
2. Versal technology is not recognized → VCO limits stay at Series7/Ultrascale defaults (e.g. fvco_min=600000, fvco_max≤1600000) instead of Versal-required 2160000–4320000 kHz.

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Change Inventory
**Record:**

| File | Changes |
|------|---------|
| `drivers/clk/clk-axi-clkgen.c` | +4 / -1 (7 lines touched) |
| `include/linux/adi-axi-common.h` | +2 enum entries |

**Functions modified:** axi_clkgen_setup_limits() only. **Scope:** Single-function, two-file surgical fix.

### Step 2.2: Code Flow Change (per hunk)

**Hunk 1 — speed grade range (clk-axi-clkgen.c:524):**
- **Before:** ADI_AXI_FPGA_SPEED_2 ... ADI_AXI_FPGA_SPEED_2LV (20–22)
- **After:** ADI_AXI_FPGA_SPEED_2 ... ADI_AXI_FPGA_SPEED_2MP (20–23)
- **Path:** Probe-time limit setup for speed-grade 2 variants.

**Hunk 2 — Versal VCO override (clk-axi-clkgen.c:546-549):**
- **Before:** Only Ultrascale+ gets a technology-specific VCO override.
- **After:** Versal gets fvco_min=2160000, fvco_max=4320000.
- **Path:** Post-switch technology override in axi_clkgen_setup_limits().

**Hunk 3 — header enums (adi-axi-common.h):**
- **Before:** No ADI_AXI_FPGA_TECH_VERSAL or ADI_AXI_FPGA_SPEED_2MP.
- **After:** Both defined.

### Step 2.3: Bug Mechanism Classification
**Record:** **(h) Hardware workaround / correctness fix**
- Missing enum value → probe failure (-ENODEV) for speed grade 23.
- Missing technology branch → wrong PLL constraint window used by axi_clkgen_calc_params() in set_rate() and determine_rate().

### Step 2.4: Fix Quality Assessment
**Record:** Fix is minimal, mirrors the existing Ultrascale+ override pattern, and is obviously correct from a hardware-spec perspective. Regression risk is very low: only affects platforms reporting Versal technology or 2MP speed grade. No lock-order or API changes.

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame / Introduction of Buggy Code **Record:** axi_clkgen_setup_limits() exists in v6.18.0 without Versal handling (verified via git show v6.18:drivers/clk/clk-axi- clkgen.c). Current tree at v6.18.43 is identical in the affected region. The omission has been present since at least the 6.18 release. Shallow history in this checkout prevents identifying the original introducing commit beyond the squashed import.

### Step 3.2: Fixes: Tag
**Record:** Not applicable — no Fixes: tag present.

### Step 3.3: Related File History
**Record:** No changes to these files on v6.18..HEAD (stable queue). The patch diff base blob fa5ccef73e60d matches the current file content in the affected region — patch applies cleanly.

### Step 3.4: Author Context
**Record:** Nuno Sá is an active Analog Devices contributor (dma-axi- dmac, iio, hwmon commits in this tree). Brian Masney (reviewer) is a regular ADI/FPGA driver contributor.

### Step 3.5: Dependencies
**Record:** **Standalone.** No series dependencies, no prerequisite commits required. The driver, axi_clkgen_setup_limits(), and ADI_AXI_REG_FPGA_INFO infrastructure all exist in 6.18.y.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original Patch Discussion
**Record:**
- v1: https://www.spinics.net/lists/kernel/msg6122732.html (2026-03-26)
- RESEND: https://www.spinics.net/lists/kernel/msg6169958.html
(2026-04-24)
- b4 dig could not be run (commit hash not in local tree); lore.kernel.org blocked by bot protection.
- Follow-ups from Stephen Boyd and Brian Masney are listed on spinics but individual reply bodies were not retrieved.
- Patch is a single standalone commit (not a series).

### Step 4.2: Reviewers
**Record:** CC'd to linux-clk@, Michael Turquette, Stephen Boyd.
Reviewed-by: Brian Masney in committed version.

### Step 4.3: Bug Reports
**Record:** No Reported-by, syzbot, or bugzilla links. No external user crash reports found.

### Step 4.4: Related Patches
**Record:** Single patch; change-id 20260326-clk-axi-clk-versal- support-8eaef1530870. v1 and RESEND are identical in content.

### Step 4.5: Stable List History
**Record:** Not searched (no stable nomination found in available patch posts). Absence of Cc: stable is expected per review instructions.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key Functions Modified
**Record:** axi_clkgen_setup_limits() (only function changed).

### Step 5.2: Callers
**Record:** Called once from axi_clkgen_probe() when ADI_AXI_PCORE_VER_MAJOR(pcore_version) > 0x04:

```616:619:drivers/clk/clk-axi-clkgen.c
        if (ADI_AXI_PCORE_VER_MAJOR(pcore_version) > 0x04) {
                ret = axi_clkgen_setup_limits(axi_clkgen, &pdev->dev);
                if (ret)
                        return ret;
```

Probe-time, platform driver init path.

### Step 5.3: Callees / Downstream Impact
**Record:** Limits set here are consumed by axi_clkgen_calc_params() via axi_clkgen_set_rate() and axi_clkgen_determine_rate(). Wrong limits → -EINVAL from rate setting or incorrect PLL divider values programmed to MMCM registers.

### Step 5.4: Reachability
**Record:** Triggered at device probe for any platform with adi,axi- clkgen-2.00.a or adi,zynqmp-axi-clkgen-2.00.a compatible and pcore version > 4. Requires CONFIG_COMMON_CLK_AXI_CLKGEN. No in-tree Versal DTS nodes use this compatible string (verified by grep), but the driver reads technology directly from FPGA hardware registers — custom ADI reference designs on Versal are the target.

### Step 5.5: Similar Patterns
**Record:** Identical pattern already exists for ADI_AXI_FPGA_TECH_ULTRASCALE_PLUS in the same function (lines 545–549). This commit extends that pattern to Versal.

---

## PHASE 6: CROSS-REFERENCE AGAINST LOCAL TREE (6.18.y)

### Step 6.1: Does Buggy Code Exist?
**Record:** **Yes.** Current tree lacks ADI_AXI_FPGA_TECH_VERSAL, ADI_AXI_FPGA_SPEED_2MP, and the Versal VCO override. Confirmed in both HEAD and v6.18.0.

### Step 6.2: Backport Complications
**Record:** **Clean apply expected.** Diff base matches current source exactly in affected hunks.

### Step 6.3: Related Fixes Already Present?
**Record:** **No.** Grep found no VERSAL or 2MP symbols in the tree.

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

### Step 7.1: Subsystem Criticality
**Record:** **clk** / **PERIPHERAL** — Analog Devices AXI clock generator for Xilinx FPGAs (CONFIG_COMMON_CLK_AXI_CLKGEN, tristate, OF-based). Niche industrial/SDR embedded hardware.

### Step 7.2: Subsystem Activity
**Record:** clk subsystem is actively maintained in 6.18.y (many stable backports), but this specific driver has seen no stable-queue changes since 6.18.0.

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: Who Is Affected
**Record:** **Driver-specific / platform-specific** — users of Analog Devices AXI clkgen IP on Versal FPGAs with pcore version > 4. Not a universal kernel path.

### Step 8.2: Trigger Conditions
**Record:**
- FPGA info register reports ADI_AXI_FPGA_TECH_VERSAL, and/or
- Speed grade ADI_AXI_FPGA_SPEED_2MP (23).
- Triggered at every probe of matching hardware. Not userspace- triggerable; not a security issue.

### Step 8.3: Failure Mode Severity
**Record:**

| Failure | Mode | Severity |
|---------|------|----------|
| Speed grade 2MP unrecognized | Probe fails `-ENODEV`, no clock
provider | **HIGH** for affected hardware (device unusable) |
| Wrong VCO limits on Versal | Rate requests fail (`-EINVAL`) or PLL
programmed out of spec | **MEDIUM-HIGH** (functional failure, possible
peripheral misbehavior) |

Not a kernel oops/panic/data-corruption class bug.

### Step 8.4: Risk-Benefit
**Record:**
- **Benefit:** Enables correct clock operation on Versal ADI designs; fixes hard probe failure for 2MP speed grade. High value for the small affected population.
- **Risk:** Very low — 7 lines, isolated to Versal detection path, follows proven Ultrascale+ pattern.
- **Ratio:** Favorable for affected users; negligible risk to everyone else.

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence Summary

**FOR backport:**
- Real, verifiable bugs in existing driver logic (probe failure + wrong PLL limits).
- Hardware quirk/workaround — same category as existing Ultrascale+ override.
- Tiny, surgical, reviewed, maintainer-merged patch.
- Applies cleanly to 6.18.y; all prerequisite code present.
- Fixes broken behavior on hardware the driver is already designed to auto-detect.

**AGAINST backport:**
- Framed as "add support" for a new FPGA generation.
- No bug reports, fuzzer findings, or in-tree DTS users.
- Very niche hardware (ADI reference designs on Versal).
- Does not cause kernel crashes or security issues — device-level functional failure.
- Versal was never supported in 6.18.y (not a regression fix).

### Step 9.2: Stable Rules Checklist

| Criterion | Result |
|-----------|--------|
| 1. Obviously correct and tested? | **PASS** — mirrors Ultrascale+
pattern; Reviewed-by present; no Tested-by |
| 2. Fixes a real bug affecting users? | **PASS** — probe failure and
incorrect PLL limits on Versal hardware |
| 3. Important issue? | **PASS (borderline)** — device unusable on
affected Versal platforms; not crash/security class |
| 4. Small and contained? | **PASS** — 7 lines, 2 files, 1 function |
| 5. No new features/APIs? | **PASS** — hardware quirk exception; no
userspace API changes |
| 6. Can apply to local tree? | **PASS** — code exists, clean apply |

### Step 9.3: Exception Category
**Record:** **Hardware quirk/workaround** — adding correct timing limits for a new FPGA technology variant in an existing driver, analogous to the Ultrascale+ VCO override already in stable.

### Step 9.4: Decision Rationale

For **linux-6.18.y**: the driver already reads FPGA technology and speed grade from hardware and configures PLL limits accordingly. Versal platforms are a real deployment target for Analog Devices IP (per
Kconfig: "commonly used in Analog Devices' reference designs"). Without this patch:

1. Versal boards reporting speed grade 2MP fail probe outright.
2. All Versal boards get VCO limits roughly 2–3× too low, breaking clock rate configuration.

This is a correctness fix in existing auto-detection logic, not a new driver. It is small, low-risk, and directly analogous to stable- acceptable hardware quirk fixes. The niche audience and lack of bug reports lower priority but do not negate technical merit.

---

## Verification

- **[Phase 1]** Parsed subject, tags (SOB, Reviewed-by), body; no Fixes/Reported-by/Link tags.
- **[Phase 2]** Diff analysis: 7 lines, axi_clkgen_setup_limits() only; classified as hardware workaround.
- **[Phase 3]** git describe HEAD → v6.18.43; git show v6.18:... confirms buggy code at 6.18.0; no VERSAL/2MP in tree (grep); diff base fa5ccef73e60d matches current file; no changes on v6.18..HEAD for these files.
- **[Phase 4]** Fetched v1 and RESEND from spinics.net; lore.kernel.org blocked; b4 dig not run (commit not in tree); no bug reports in patch posts.
- **[Phase 5]** Read axi_clkgen_probe, set_rate, determine_rate; traced limits → axi_clkgen_calc_params; grep found no in-tree Versal+adi-clkgen DTS.
- **[Phase 6]** Confirmed CONFIG_COMMON_CLK_AXI_CLKGEN and driver exist; patch applies cleanly; no prior fix present.
- **[Phase 7]** Kconfig confirms peripheral ADI/Xilinx driver.
- **[Phase 8]** Probe failure = -ENODEV (verified in code); wrong limits affect rate calculation (verified call chain).
- **UNVERIFIED:** Individual review reply bodies from Brian Masney/Stephen Boyd (listed but not fetched); original commit SHA on mainline; exact kernel version that introduced axi_clkgen_setup_limits() (shallow history).

**YES**

 drivers/clk/clk-axi-clkgen.c   | 5 ++++-
 include/linux/adi-axi-common.h | 2 ++
 2 files changed, 6 insertions(+), 1 deletion(-)
drivers/clk/clk-axi-clkgen.c +4 -1
index fa5ccef73e60d..26f76a6db8202 100644
@@ -521,7 +521,7 @@ static int axi_clkgen_setup_limits(struct axi_clkgen *axi_clkgen,
 		axi_clkgen->limits.fvco_max = 1200000;
 		axi_clkgen->limits.fpfd_max = 450000;
 		break;
-	case ADI_AXI_FPGA_SPEED_2 ... ADI_AXI_FPGA_SPEED_2LV:
+	case ADI_AXI_FPGA_SPEED_2 ... ADI_AXI_FPGA_SPEED_2MP:
 		axi_clkgen->limits.fvco_max = 1440000;
 		axi_clkgen->limits.fpfd_max = 500000;
 		if (family == ADI_AXI_FPGA_FAMILY_KINTEX || family == ADI_AXI_FPGA_FAMILY_ARTIX) {
@@ -546,6 +546,9 @@ static int axi_clkgen_setup_limits(struct axi_clkgen *axi_clkgen,
 	if (tech == ADI_AXI_FPGA_TECH_ULTRASCALE_PLUS) {
 		axi_clkgen->limits.fvco_max = 1600000;
 		axi_clkgen->limits.fvco_min = 800000;
+	} else if (tech == ADI_AXI_FPGA_TECH_VERSAL) {
+		axi_clkgen->limits.fvco_max = 4320000;
+		axi_clkgen->limits.fvco_min = 2160000;
 	}
 
 	return 0;
include/linux/adi-axi-common.h +2 -0
index 37962ba530dfc..e7ba393061ee6 100644
@@ -51,6 +51,7 @@ enum adi_axi_fpga_technology {
 	ADI_AXI_FPGA_TECH_SERIES7,
 	ADI_AXI_FPGA_TECH_ULTRASCALE,
 	ADI_AXI_FPGA_TECH_ULTRASCALE_PLUS,
+	ADI_AXI_FPGA_TECH_VERSAL,
 };
 
 enum adi_axi_fpga_family {
@@ -71,6 +72,7 @@ enum adi_axi_fpga_speed_grade {
 	ADI_AXI_FPGA_SPEED_2    = 20,
 	ADI_AXI_FPGA_SPEED_2L   = 21,
 	ADI_AXI_FPGA_SPEED_2LV  = 22,
+	ADI_AXI_FPGA_SPEED_2MP  = 23,
 	ADI_AXI_FPGA_SPEED_3    = 30,
 };
 
Signature · 1 line
2.53.0
#265 lore raw

Re: [PATCH AUTOSEL 6.18] clk: clk-axi-clkgen: Add support versal timings

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:

Pre-existing issues:
- [High] Potential division by zero when calculating clock parameters if parent_rate or requested rate is below 1000 Hz. --

commit 0b1a53196b2b85f8a1c0c11b49ab42f0ef80e28c
Author: Nuno Sá <[email protected]>

clk: clk-axi-clkgen: Add support versal timings

Add proper VCO and PFD limits for versal based platforms by introducing new Technology and Speed grade defines.

Quoted 4 lines
drivers/clk/clk-axi-clkgen.c +0 -0
index fa5ccef73e60d..26f76a6db8202 100644

[ ... ]

drivers/clk/clk-axi-clkgen.c static int axi_clkgen_setup_limits(struct axi_clkgen *axi_clkgen, · line 554

Quoted 10 lines
drivers/clk/clk-axi-clkgen.c +3 -0
@@ -546,6 +546,9 @@ static int axi_clkgen_setup_limits(struct axi_clkgen *axi_clkgen,
 	if (tech == ADI_AXI_FPGA_TECH_ULTRASCALE_PLUS) {
 		axi_clkgen->limits.fvco_max = 1600000;
 		axi_clkgen->limits.fvco_min = 800000;
+	} else if (tech == ADI_AXI_FPGA_TECH_VERSAL) {
+		axi_clkgen->limits.fvco_max = 4320000;
+		axi_clkgen->limits.fvco_min = 2160000;
 	}
 
 	return 0;

[Severity: High]
This isn't a bug introduced by this patch, but can we hit a division by zero kernel oops in axi_clkgen_calc_params() if a requested rate or parent_rate is less than 1000 Hz?

In drivers/clk/clk-axi-clkgen.c:axi_clkgen_calc_params(), the code calculates fin and fout by dividing the rates by 1000:

	fin = parent_rate / 1000;
	fout = rate / 1000;

If a client driver or device tree properties (such as assigned-clock-rates) request a rate or parent_rate below 1000 Hz, fin or fout would become 0. This appears to lead to a division by zero later in the same function when calculating parameters:

	m_min = max(DIV_ROUND_UP(fvco_min_fract, fin) * d_min, 1);
	m_max = min(fvco_max_fract * d_max / fin, 64 << fract_shift);
	...
	dout = DIV_ROUND_CLOSEST(fvco, fout);

Are there constraints that prevent clk_set_rate() or clk_determine_rate() from reaching this path with frequencies below 1000 Hz?

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

PATCH 1/1 misc: pci_endpoint_test: Validate BAR index in doorbell test

In reply to Sasha Levin

From: Carlos Bilbao <[email protected]>

[ Upstream commit 854bd081c7680029d7886689f6bef8f740625fde ]

pci_endpoint_test_doorbell() reads the BAR number directly from an endpoint test register and uses it as an index into test->bar[]. Add a defensive bounds check before the dereference: positive values >= PCI_STD_NUM_BARS are out of range, and NO_BAR (-1) as a negative signed value would slip past an upper-bound-only check.

---

LLM Generated explanations, may be completely bogus:

# Stable Backport Analysis: misc: pci_endpoint_test: Validate BAR index in doorbell test

**Local tree:** v6.18.44-1-g2736c32da98b9 (kernel version **6.18.44**, 6.18.y stable series)

**Commit under review:** 854bd081c7680 (not yet in this tree; present on master)

---

## PHASE 1: COMMIT MESSAGE FORENSICS

### Step 1.1: Subject line
**Record:** [misc: pci_endpoint_test] [Validate] — defensive bounds check on BAR index used in the doorbell test path.

### Step 1.2: Tags
**Record:**
- **Signed-off-by:** Carlos Bilbao (Lambda), Manivannan Sadhasivam, Bjorn Helgaas
- **Link:** https://patch.msgid.link/20260410230300.135631-2-
[email protected]
- No Fixes:, Reported-by:, Cc: [email protected], Tested- by:, or Reviewed-by: in the committed message
- Notable: PCI subsystem maintainers (Mani, Bjorn) signed off; no syzbot or user bug report

### Step 1.3: Body analysis
**Record:**
- **Bug:** pci_endpoint_test_doorbell() reads a BAR number from endpoint MMIO (PCI_ENDPOINT_TEST_DB_BAR) and uses it unvalidated as test->bar[bar].
- **Symptom:** Out-of-range positive values (>= PCI_STD_NUM_BARS) or NO_BAR (-1) cause out-of-bounds indexing before writel().
- **Root cause:** Missing lower/upper bounds check; an upper-bound-only check would miss negative values because bar is enum pci_barno (signed, with NO_BAR = -1).
- **Version info:** None in the message.

### Step 1.4: Hidden bug fix?
**Record:** Yes — explicitly a memory-safety bounds-check fix, not cosmetic cleanup. Same bug class as the earlier ioctl underflow fix (1ad82f9db13d8).

---

## PHASE 2: DIFF ANALYSIS

### Step 2.1: Inventory
**Record:**
- **Files:** drivers/misc/pci_endpoint_test.c (+5 lines)
- **Function:** pci_endpoint_test_doorbell()
- **Scope:** Single-file, surgical fix

### Step 2.2: Code flow change
**Record:**
- **Before:** After re-reading PCI_ENDPOINT_TEST_DB_BAR, code immediately does writel(data, test->bar[bar] + addr).
- **After:** Validates bar < BAR_0 || bar >= PCI_STD_NUM_BARS; logs error and returns -ERANGE on failure; only then dereferences test->bar[bar].
- **Path affected:** Error/safety path inside doorbell test, reached via ioctl(PCITEST_DOORBELL).

### Step 2.3: Bug mechanism
**Record:** **Category:** Out-of-bounds array access / buffer overflow.
- test->bar is void __iomem *bar[PCI_STD_NUM_BARS] (6 elements, indices 0–5).
- pci_endpoint_test_readl() returns u32; assigned to signed enum pci_barno.
- bar == -1 (NO_BAR) → array underflow; bar >= 6 → array overflow.
- Either can yield a garbage pointer passed to writel() → kernel oops or memory corruption.

### Step 2.4: Fix quality
**Record:** Obviously correct; mirrors the existing ioctl guard (bar <= NO_BAR || bar > BAR_5). Minimal, no API changes. Low regression risk. Does not add a NULL-bar check (consistent with other paths that validate index separately).

---

## PHASE 3: GIT HISTORY INVESTIGATION

### Step 3.1: Blame
**Record:** Lines 895–897 introduced by eefb83790a0dd ("Add doorbell test case", Frank Li, 2025-07-10). First appeared in **v6.17**. Bug present since doorbell support landed.

### Step 3.2: Fixes: tag
**Record:** N/A — no Fixes: tag. Related introducing commit:
eefb83790a0dd, which is an ancestor of this 6.18.44 tree.

### Step 3.3: Related file history
**Record:**
- eefb83790a0dd — added doorbell test (v6.17+)
- 1ad82f9db13d8 — fixed ioctl array underflow for user-supplied BAR (same NO_BAR issue)
- cc8e391067164, 384b1b29481e3 — other doorbell-related cleanups
- Fix is standalone (patch 1/2 of a series); patch 2/2 only removes a dead register read (cleanup, not required for the bounds fix)

### Step 3.4: Author context
**Record:** Carlos Bilbao is a PCI endpoint contributor. Manivannan Sadhasivam (PCI endpoint maintainer) applied the series. Dan Carpenter previously fixed the parallel ioctl-path bug.

### Step 3.5: Dependencies
**Record:** No prerequisites. Doorbell code exists in this tree. git apply --check on the patch succeeds cleanly against 6.18.44.

---

## PHASE 4: MAILING LIST AND EXTERNAL RESEARCH

### Step 4.1: Original discussion
**Record:** b4 dig -c 854bd081c7680 → https://patch.msgid.link/2026041
[email protected]. Part of **v2 1/2** series. Manivannan Sadhasivam replied "Applied, thanks!" No explicit stable nomination found.

### Step 4.2: Reviewers
**Record:** b4 dig -w: CC'd to [email protected], [email protected], [email protected], [email protected], [email protected]. **Reviewed-by: Koichiro Den** on the series.

### Step 4.3: Bug reports
**Record:** No external bug report, syzbot report, or crash log. Proactive defensive fix identified during code review.

### Step 4.4: Series context
**Record:** 2-patch series. Only patch 1/2 (this commit) fixes the OOB bug. Patch 2/2 removes an unused earlier BAR read.

### Step 4.5: Stable list history
**Record:** Not searched separately; no stable-list discussion found in the patch thread.

---

## PHASE 5: CODE SEMANTIC ANALYSIS

### Step 5.1: Key functions
**Record:** pci_endpoint_test_doorbell() (modified), called from pci_endpoint_test_ioctl().

### Step 5.2: Callers
**Record:**
- pci_endpoint_test_ioctl() → case PCITEST_DOORBELL: → pci_endpoint_test_doorbell(test)
- Exposed via misc_device (/dev/pci-endpoint-test.*) through unlocked_ioctl
- Selftest: tools/testing/selftests/pci_endpoint/pci_endpoint_test.c calls PCITEST_DOORBELL

### Step 5.3: Callees
**Record:** pci_endpoint_test_readl/writel, wait_for_completion_timeout, writel() to BAR-mapped MMIO.

### Step 5.4: Reachability
**Record:** Reachable from userspace via ioctl() on the misc device. Requires access to the PCI endpoint test device node (typically root or delegated permissions). Not triggerable by unprivileged users without device access. With device access + buggy/malicious endpoint firmware returning an invalid BAR register value, the OOB path is reachable.

### Step 5.5: Similar patterns
**Record:** Ioctl path already has equivalent validation at line 940:

```940:941:drivers/misc/pci_endpoint_test.c
                if (bar <= NO_BAR || bar > BAR_5)
                        goto ret;
```

Doorbell path lacks this guard — an inconsistency the patch corrects.

---

## PHASE 6: CROSS-REFERENCING AGAINST LOCAL TREE (6.18.44)

### Step 6.1: Buggy code present?
**Record:** **Yes.** pci_endpoint_test_doorbell() at lines 895–897 performs unchecked test->bar[bar] dereference. Doorbell support (eefb83790a0dd) is an ancestor of HEAD (landed in v6.17, present in 6.18.44).

### Step 6.2: Backport complications
**Record:** **Clean apply.** git apply --check passes. No structural conflicts; line numbers differ but context matches.

### Step 6.3: Related fixes already present?
**Record:** Ioctl underflow fix (1ad82f9db13d8) is in this tree. The doorbell-path BAR validation fix (854bd081c7680) is **not** in this tree (only on master).

---

## PHASE 7: SUBSYSTEM AND MAINTAINER CONTEXT

### Step 7.1: Subsystem criticality
**Record:** **drivers/misc** — PCI Endpoint Test driver (CONFIG_PCI_ENDPOINT_TEST). **PERIPHERAL** — host-side test driver for PCI endpoint development (TI K3, Rockchip, etc.). Not a core subsystem, but kernel code reachable from userspace ioctl.

### Step 7.2: Activity
**Record:** Actively maintained; multiple recent fixes in the same file (IRQ range checks, ioctl underflow, integer overflow prevention).

---

## PHASE 8: IMPACT AND RISK ASSESSMENT

### Step 8.1: Who is affected
**Record:** Users with CONFIG_PCI_ENDPOINT_TEST enabled who run the doorbell selftest against PCI endpoint hardware. Primarily embedded/SoC developers, not typical server/desktop workloads.

### Step 8.2: Trigger conditions
**Record:** ioctl(PCITEST_DOORBELL) after doorbell enable, when endpoint MMIO reports PCI_ENDPOINT_TEST_DB_BAR outside [0, 5] or as -1. Unlikely in correct firmware, but possible with bugs or during bring-up. Requires device-node access.

### Step 8.3: Failure mode severity
**Record:** Out-of-bounds pointer dereference in writel() → **kernel oops / potential memory corruption**. **Severity: HIGH** if triggered; **likelihood: LOW** (niche driver, privileged access, depends on endpoint behavior).

### Step 8.4: Risk-benefit
**Record:**
- **Benefit:** Prevents kernel crash from a real OOB bug; aligns doorbell path with already-fixed ioctl path.
- **Risk:** Very low — 5-line bounds check, maintainer-reviewed, clean apply.
- **Ratio:** Favorable for backport despite narrow exposure.

---

## PHASE 9: FINAL SYNTHESIS

### Step 9.1: Evidence summary

**FOR backport:**
- Real out-of-bounds array index bug (underflow and overflow)
- Can cause kernel oops
- Small (5 lines), obviously correct, applies cleanly
- Buggy code confirmed in 6.18.44 since v6.17 doorbell addition
- PCI maintainers signed off; parallel ioctl fix already in this tree
- Self-contained; no dependencies

**AGAINST backport:**
- Niche test driver (CONFIG_PCI_ENDPOINT_TEST)
- Requires privileged device access
- No syzbot/user crash reports
- Invalid BAR comes from endpoint MMIO, not direct userspace input
- Limited production impact

**Unresolved:** None material to the decision.

### Step 9.2: Stable rules checklist
1. Obviously correct and tested? **PASS** — simple bounds check; selftests exercise doorbell path; maintainer applied.
2. Fixes a real bug? **PASS** — OOB array indexing.
3. Important issue? **PASS** — kernel crash on invalid index (HIGH severity, lower exposure).
4. Small and contained? **PASS** — 5 lines, one function.
5. No new features/APIs? **PASS**.
6. Can apply to local tree? **PASS** — clean apply verified.

### Step 9.3: Exception categories
**Record:** None (not device ID, quirk, DT, build, or docs). Standard bug fix.

### Step 9.4: Decision rationale
For **6.18.44**, the doorbell test exists and has had an unchecked BAR index since v6.17. This is the same class of memory-safety bug already fixed on the ioctl path in this tree. The fix is minimal, maintainer- approved, and prevents a kernel oops. Narrow driver scope lowers urgency but does not negate that it is a real, reachable crash fix in code that is present and active in this stable tree.

---

## Verification

- **[Phase 1]** Parsed commit 854bd081c7680 message and tags via git show
- **[Phase 1]** No syzbot/Reported-by; Link tag present; Bjorn Helgaas and Mani SOBs confirmed
- **[Phase 2]** Read pci_endpoint_test_doorbell() at lines 857–922; confirmed unchecked test->bar[bar] at line 897
- **[Phase 2]** Confirmed test->bar[PCI_STD_NUM_BARS] and NO_BAR = -1 at lines 108–121
- **[Phase 3]** git blame -L 895,897: introduced by eefb83790a0dd (2025-07-10)
- **[Phase 3]** git log -20 -- drivers/misc/pci_endpoint_test.c:
related ioctl fix 1ad82f9db13d8 present
- **[Phase 3]** git tag --contains eefb83790a0dd: first in **v6.17**
- **[Phase 3]** git merge-base --is-ancestor: doorbell IN tree; fix 854bd081c7680 NOT in HEAD; ioctl fix IN HEAD
- **[Phase 4]** b4 dig -c 854bd081c7680: lore URL found
- **[Phase 4]** b4 dig -m /tmp/doorbell_bar.mbox: v2 1/2 series; Reviewed-by Den; Mani "Applied, thanks!"
- **[Phase 4]** No stable nomination in thread
- **[Phase 5]** Traced call chain: pci_endpoint_test_ioctl → PCITEST_DOORBELL → pci_endpoint_test_doorbell
- **[Phase 5]** Grep PCITEST_DOORBELL: ioctl case at line 974, selftest at tools/testing/selftests/pci_endpoint/pci_endpoint_test.c:261
- **[Phase 5]** Confirmed ioctl bounds check at line 940 (bar <= NO_BAR || bar > BAR_5)
- **[Phase 6]** git describe HEAD: v6.18.44; make kernelversion:
6.18.44
- **[Phase 6]** git apply --check on patch: **clean apply**
- **[Phase 6]** Read probe: test allocated with devm_kzalloc (line 1019); test->bar[] sized PCI_STD_NUM_BARS
- **[Phase 8]** CONFIG_PCI_ENDPOINT_TEST in drivers/misc/Kconfig:482 — tristate host-side PCI endpoint test driver

**YES**The background lookups finished and match the earlier analysis:

- **Commit hash:** 854bd081c7680 — misc: pci_endpoint_test: Validate BAR index in doorbell test
- **Location:** on master (via merge ae385ca812325), **not** in the checked-out **6.18.44** tree
- **Local state:** the doorbell path still does an unchecked test->bar[bar] dereference; the patch applies cleanly here

**Verdict remains YES** for backport to this 6.18.y tree — small bounds- check fix for a real OOB bug in code that’s already present since v6.17.

 drivers/misc/pci_endpoint_test.c | 5 +++++
 1 file changed, 5 insertions(+)
drivers/misc/pci_endpoint_test.c +5 -0
index 1c0fd185114fc..43e2282f8a76e 100644
@@ -893,6 +893,11 @@ static int pci_endpoint_test_doorbell(struct pci_endpoint_test *test)
 	pci_endpoint_test_writel(test, PCI_ENDPOINT_TEST_STATUS, 0);
 
 	bar = pci_endpoint_test_readl(test, PCI_ENDPOINT_TEST_DB_BAR);
+	if (bar < BAR_0 || bar >= PCI_STD_NUM_BARS) {
+		dev_err(dev, "BAR %d reported by endpoint out of range [0, %u]\n",
+			bar, PCI_STD_NUM_BARS - 1);
+		return -ERANGE;
+	}
 
 	writel(data, test->bar[bar] + addr);
 
Signature · 1 line
2.53.0
#267 lore raw

Re: [PATCH AUTOSEL 6.18] misc: pci_endpoint_test: Validate BAR index in doorbell test

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:

New issues:
- [Medium] The newly added early return bypasses the COMMAND_DISABLE_DOORBELL cleanup step, leaving the endpoint device in an inconsistent state and causing resource leaks.

Pre-existing issues:
- [Critical] The endpoint-provided addr offset is not validated against the actual size of the BAR memory region, allowing an arbitrary out-of-bounds write.
- [High] The driver verifies the bar index bounds but fails to check if the targeted BAR is actually mapped (non-NULL) before dereferencing it via writel(). --

commit 7fede1d6ad3da3ad8055d4fe4ae5cd8853f975be
Author: Carlos Bilbao <[email protected]>

misc: pci_endpoint_test: Validate BAR index in doorbell test

pci_endpoint_test_doorbell() reads the BAR number directly from an endpoint test register and uses it as an index into test->bar[]. Add a defensive bounds check before the dereference.

drivers/misc/pci_endpoint_test.c static int pci_endpoint_test_doorbell(struct pci_endpoint_test *test) · line 899

Quoted 12 lines
drivers/misc/pci_endpoint_test.c +4 -0
index 1c0fd185114fc..43e2282f8a76e 100644
@@ -893,6 +893,11 @@ static int pci_endpoint_test_doorbell(struct pci_endpoint_test *test)
 	pci_endpoint_test_writel(test, PCI_ENDPOINT_TEST_STATUS, 0);
 
 	bar = pci_endpoint_test_readl(test, PCI_ENDPOINT_TEST_DB_BAR);
+	if (bar < BAR_0 || bar >= PCI_STD_NUM_BARS) {
+		dev_err(dev, "BAR %d reported by endpoint out of range [0, %u]\n",
+			bar, PCI_STD_NUM_BARS - 1);
+		return -ERANGE;

[Severity: Medium]
In drivers/misc/pci_endpoint_test.c, does this early return in pci_endpoint_test_doorbell() bypass the COMMAND_DISABLE_DOORBELL cleanup step?

If a userspace application invokes the PCITEST_DOORBELL ioctl and the endpoint reports an invalid BAR index, this early return skips sending the disable command to the endpoint. It appears this leaves the device in an inconsistent state and leaks the memory and MSI IRQs allocated when the doorbell was enabled.

drivers/misc/pci_endpoint_test.c static int pci_endpoint_test_doorbell(struct pci_endpoint_test *test) · line 902

Quoted 3 lines
drivers/misc/pci_endpoint_test.c +1 -0
+	}
 
 	writel(data, test->bar[bar] + addr);

[Severity: High]
This is a pre-existing issue in pci_endpoint_test_doorbell(), but does this code check if the targeted BAR is actually mapped before dereferencing it?

If a userspace application triggers the PCITEST_DOORBELL ioctl and the endpoint returns a valid BAR index that was not successfully mapped during probe (for example, if it was not an IORESOURCE_MEM), this writel() call could result in a NULL pointer dereference.

[Severity: Critical]
This is also a pre-existing issue, but is the endpoint-provided addr offset validated against the actual size of the BAR memory region?

A malicious or buggy endpoint can provide an arbitrary 32-bit addr offset that exceeds the size of the mapped BAR. When writel() executes, it could perform an out-of-bounds memory write, potentially corrupting adjacent kernel memory or memory-mapped IO regions.

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