Skip to contentSkip to conversation

ALSA: hda/realtek: Fix headset mic for TongFang X6AR55xU

PATCH New Sasha Levin 2 participants 19 messages Jan 28 – Jan 29

Subsystems (6)
lore
Share & tools
lore

Sasha Levin

author maintainer
#0 lore raw

PATCH 1/1 ALSA: hda/realtek: Fix headset mic for TongFang X6AR55xU

From: Tim Guttzeit <[email protected]>

[ Upstream commit b48fe9af1e60360baf09ca6b7a3cd6541f16e611 ]

Add a PCI quirk to enable microphone detection on the headphone jack of TongFang X6AR55xU devices.

---

LLM Generated explanations, may be completely bogus:

The ALC274_FIXUP_HP_HEADSET_MIC fixup was added in October 2020, so it exists in all currently maintained stable trees (6.1.y, 6.6.y, 6.12.y, etc.). The new quirk entry will apply cleanly.

### 8. SIMILAR COMMITS PATTERN

This follows the exact same pattern as countless other HDA pin quirk additions that are routinely backported to stable. The HDA realtek driver has hundreds of similar entries in this table, all following the same format.

---

## Summary

**What problem it solves:** Fixes non-functional headset microphone on TongFang X6AR55xU laptops by adding a pin quirk entry that applies an existing, proven fixup.

**Meets stable kernel rules:**
- ✅ Obviously correct - simple table entry addition following established pattern
- ✅ Fixes a real bug - hardware doesn't work without it
- ✅ Small and contained - 4 lines, 1 file, no logic changes
- ✅ No new features - uses existing ALC274_FIXUP_HP_HEADSET_MIC fixup
- ✅ Falls under "hardware quirks/workarounds" exception

**Risk vs Benefit:**
- **Risk:** Essentially zero - only affects specific hardware, cannot impact other devices
- **Benefit:** High for affected users - enables basic audio functionality

**Concerns:** None. The fixup already exists in stable trees since 2020. The change applies cleanly with no dependencies.

This is a textbook example of a backport-worthy commit: a minimal hardware quirk that fixes a real user-facing issue with zero risk to other systems.

**YES**

 sound/hda/codecs/realtek/alc269.c | 4 ++++
 1 file changed, 4 insertions(+)
sound/hda/codecs/realtek/alc269.c +4 -0
index b5aa8da1e50a8..c6dc44f5d3ab7 100644
@@ -7675,6 +7675,10 @@ static const struct snd_hda_pin_quirk alc269_pin_fixup_tbl[] = {
 		{0x12, 0x90a60140},
 		{0x19, 0x04a11030},
 		{0x21, 0x04211020}),
+	SND_HDA_PIN_QUIRK(0x10ec0274, 0x1d05, "TongFang", ALC274_FIXUP_HP_HEADSET_MIC,
+		{0x17, 0x90170110},
+		{0x19, 0x03a11030},
+		{0x21, 0x03211020}),
 	SND_HDA_PIN_QUIRK(0x10ec0282, 0x1025, "Acer", ALC282_FIXUP_ACER_DISABLE_LINEOUT,
 		ALC282_STANDARD_PINS,
 		{0x12, 0x90a609c0},
Signature · 1 line
2.51.0
author maintainer
#1 lore raw

PATCH 1/1 io_uring/rw: free potentially allocated iovec on cache put failure

From: Jens Axboe <[email protected]>

[ Upstream commit 4b9748055457ac3a0710bf210c229d01ea1b01b9 ]

If a read/write request goes through io_req_rw_cleanup() and has an allocated iovec attached and fails to put to the rw_cache, then it may end up with an unaccounted iovec pointer. Have io_rw_recycle() return whether it recycled the request or not, and use that to gauge whether to free a potential iovec or not.

---

LLM Generated explanations, may be completely bogus:

Now let's understand the scope. This commit fix is for a memory leak bug in the io_uring rw (read/write) path. Let me summarize my analysis:

## Analysis Summary

### 1. COMMIT MESSAGE ANALYSIS
- **Subject**: "io_uring/rw: free potentially allocated iovec on cache put failure"
- **Keywords**: "free", "allocated", "failure" - this is clearly a bug fix for a resource leak
- **Description**: When a read/write request goes through io_req_rw_cleanup() with an allocated iovec and fails to put to the rw_cache, the iovec pointer becomes unaccounted (leaked).
- **Reviewed-by**: Nitesh Shetty (Samsung) - indicates review
- **Author**: Jens Axboe (io_uring maintainer)

### 2. CODE CHANGE ANALYSIS

The bug is in io_rw_recycle() and io_req_rw_cleanup():

**Before the fix:**

```c
static void io_rw_recycle(struct io_kiocb *req, unsigned int
issue_flags)
{
    struct io_async_rw *rw = req->async_data;

    if (unlikely(issue_flags & IO_URING_F_UNLOCKED))
        return;  // Early return - iovec potentially leaked

    io_alloc_cache_vec_kasan(&rw->vec);
    if (rw->vec.nr > IO_VEC_CACHE_SOFT_CAP)
        io_vec_free(&rw->vec);

    if (io_alloc_cache_put(&req->ctx->rw_cache, rw))
        io_req_async_data_clear(req, 0);
    // PROBLEM: If io_alloc_cache_put fails (returns false when cache is
full),
    // the rw structure is NOT freed and NOT put back into the cache,
    // but the iovec inside rw->vec is also not freed!
}
```

**After the fix:**

```c
static bool io_rw_recycle(struct io_kiocb *req, unsigned int
issue_flags)
{
    // Returns bool to indicate if recycling succeeded

    if (unlikely(issue_flags & IO_URING_F_UNLOCKED))
        return false;  // Caller knows recycling failed

    // ... same cleanup ...

    if (io_alloc_cache_put(&req->ctx->rw_cache, rw)) {
        io_req_async_data_clear(req, 0);
        return true;  // Successfully recycled
    }
    return false;  // Failed to recycle - caller will free
}

static void io_req_rw_cleanup(struct io_kiocb *req, unsigned int
issue_flags)
{
    if (!(req->flags & (REQ_F_REISSUE | REQ_F_REFCOUNT))) {
        req->flags &= ~REQ_F_NEED_CLEANUP;
        if (!io_rw_recycle(req, issue_flags)) {
            struct io_async_rw *rw = req->async_data;
            io_vec_free(&rw->vec);  // FIX: Free the iovec if recycle
failed
        }
    }
}
```

### 3. CLASSIFICATION
- **Type**: Bug fix - memory leak
- **Category**: Resource leak in io_uring read/write path
- **Severity**: Medium - leads to memory leak over time with repeated I/O operations when cache is full

### 4. SCOPE AND RISK ASSESSMENT
- **Lines changed**: 11 insertions, 4 deletions (small)
- **Files touched**: 1 (io_uring/rw.c)
- **Complexity**: Low - simple return value change and conditional free
- **Risk**: Very low - the fix is straightforward and localized

### 5. USER IMPACT
- **Who is affected**: All io_uring users doing read/write operations
- **How severe**: Memory leak - can cause gradual memory exhaustion on systems with heavy io_uring usage
- **Trigger conditions**: When the rw_cache is full (reaches IO_ALLOC_CACHE_MAX=128 entries) and a request cleanup occurs

### 6. STABILITY INDICATORS
- **Reviewed-by**: Yes (Nitesh Shetty)
- **Maintainer authored**: Yes (Jens Axboe is the io_uring maintainer)
- **Testing**: The fix is straightforward and has a Reviewed-by tag

### 7. DEPENDENCY CHECK
- The code being fixed was introduced in v6.14-rc1 (commit 9ac273ae3dc29)
- The io_vec_free function exists in v6.15+
- This fix applies cleanly to 6.14+ and 6.15+ stable branches

### Conclusion

This commit should be backported because:

1. **Fixes a real bug**: Memory leak when io_alloc_cache_put fails
2. **Small and surgical**: Only 15 lines changed in one file
3. **Obviously correct**: The fix simply ensures proper cleanup when cache insertion fails
4. **No new features**: Just fixes the existing resource management
5. **Low risk**: The change is well-contained and logical
6. **Affects production code**: io_uring is widely used, and memory leaks in this path affect real users

The fix is simple: change io_rw_recycle() to return a boolean indicating success/failure, and have io_req_rw_cleanup() call io_vec_free() when recycling fails. This ensures the iovec is always properly freed.

**YES**

 io_uring/rw.c | 15 +++++++++++----
 1 file changed, 11 insertions(+), 4 deletions(-)
io_uring/rw.c +11 -4
index abe68ba9c9dc8..d7388a4a3ea5e 100644
@@ -144,19 +144,22 @@ static inline int io_import_rw_buffer(int rw, struct io_kiocb *req,
 	return 0;
 }
 
-static void io_rw_recycle(struct io_kiocb *req, unsigned int issue_flags)
+static bool io_rw_recycle(struct io_kiocb *req, unsigned int issue_flags)
 {
 	struct io_async_rw *rw = req->async_data;
 
 	if (unlikely(issue_flags & IO_URING_F_UNLOCKED))
-		return;
+		return false;
 
 	io_alloc_cache_vec_kasan(&rw->vec);
 	if (rw->vec.nr > IO_VEC_CACHE_SOFT_CAP)
 		io_vec_free(&rw->vec);
 
-	if (io_alloc_cache_put(&req->ctx->rw_cache, rw))
+	if (io_alloc_cache_put(&req->ctx->rw_cache, rw)) {
 		io_req_async_data_clear(req, 0);
+		return true;
+	}
+	return false;
 }
 
 static void io_req_rw_cleanup(struct io_kiocb *req, unsigned int issue_flags)
@@ -190,7 +193,11 @@ static void io_req_rw_cleanup(struct io_kiocb *req, unsigned int issue_flags)
 	 */
 	if (!(req->flags & (REQ_F_REISSUE | REQ_F_REFCOUNT))) {
 		req->flags &= ~REQ_F_NEED_CLEANUP;
-		io_rw_recycle(req, issue_flags);
+		if (!io_rw_recycle(req, issue_flags)) {
+			struct io_async_rw *rw = req->async_data;
+
+			io_vec_free(&rw->vec);
+		}
 	}
 }
 
Signature · 1 line
2.51.0
author maintainer
#2 lore raw

PATCH 1/1 ALSA: hda/realtek: ALC269 fixup for Lenovo Yoga Book 9i 13IRU8 audio

In reply to Sasha Levin

From: Martin Hamilton <[email protected]>

[ Upstream commit 64e0924ed3b446fdd758dfab582e0e961863a116 ]

The amp/speakers on the Lenovo Yoga Book 9i 13IRU8 laptop aren't fully powered up, resulting in horrible tinny sound by default.

The kernel has an existing quirk for PCI SSID 0x17aa3843 which matches this machine and several others. The quirk applies the ALC287_FIXUP_IDEAPAD_BASS_SPK_AMP fixup, however the fixup does not work on this machine.

This patch modifies the existing quirk by adding a check for the subsystem ID 0x17aa3881. If present, ALC287_FIXUP_TAS2781_I2C will be applied instead of ALC287_FIXUP_IDEAPAD_BASS_SPK_AMP. With this change the TAS2781 amp is powered up, firmware is downloaded and recognised by HDA/SOF - i.e. all is good, and we can boogie.

Code is re-used from alc298_fixup_lenovo_c940_duet7(), which fixes a similar problem with two other Lenovo laptops.

Cross checked against ALSA cardinfo database for potential clashes. Tested against 6.18.5 kernel built with Arch Linux default options. Tested in HDA mode and SOF mode.

Note: Possible further work required to address quality of life issues caused by the firmware's agressive power saving, and to improve ALSA control mappings.

---

LLM Generated explanations, may be completely bogus:

The alc298_fixup_lenovo_c940_duet7 pattern was introduced in June 2022, making it well-established and available in all active stable trees.

## Summary

### What the commit fixes:
The Lenovo Yoga Book 9i 13IRU8 laptop has broken audio - "horrible tinny sound" - because the TAS2781 amplifier isn't being properly initialized. The machine shares a PCI SSID (0x17aa3843) with other Yoga 9i models, but needs a different fixup to work correctly.

### Why it matters to stable users:
This is a real-world hardware issue affecting laptop users who have completely broken speaker audio. The "tinny sound" described means the speakers are essentially unusable.

### Does it meet stable kernel rules?

1. **Obviously correct**: Yes - follows an identical, proven pattern from alc298_fixup_lenovo_c940_duet7() that has been in the kernel since June 2022
2. **Fixes a real bug**: Yes - "horrible tinny sound" is a significant audio bug on production hardware
3. **Fixes an important issue**: Yes - broken speakers on a premium laptop significantly impact usability
4. **Small and contained**: Yes - ~25 lines, single file, minimal scope
5. **No new features**: Correct - it routes an existing machine to an existing fixup (ALC287_FIXUP_TAS2781_I2C)
6. **Applies cleanly**: Should apply cleanly as it only touches quirk infrastructure

### Risk vs Benefit:
- **Benefit**: High - fixes broken audio for Yoga Book 9i users
- **Risk**: Very low - the check for subsystem ID 0x17aa3881 ensures only the specific machine is affected. Other Yoga 9i models with SSID 0x17aa3843 will continue to get the existing ALC287_FIXUP_IDEAPAD_BASS_SPK_AMP fixup

### Dependencies:
- ALC287_FIXUP_TAS2781_I2C must exist (added Aug 2023)
- __snd_hda_apply_fixup() must exist (established infrastructure)
- The pattern is well-tested from alc298_fixup_lenovo_c940_duet7()

### Concerns:
- For older stable trees (6.1.y, 5.15.y), the ALC287_FIXUP_TAS2781_I2C fixup may not exist, so this patch would only be applicable to 6.6+ stable trees
- Tested by the author on 6.18.5 in both HDA and SOF modes

This is a textbook example of a hardware quirk/workaround that falls under the "quirks and workarounds" exception for stable. It fixes broken hardware using a proven pattern with minimal risk to other systems.

**YES**

 sound/hda/codecs/realtek/alc269.c | 24 +++++++++++++++++++++++-
 1 file changed, 23 insertions(+), 1 deletion(-)
sound/hda/codecs/realtek/alc269.c +23 -1
index c6dc44f5d3ab7..cbfcf7ad37591 100644
@@ -3674,6 +3674,7 @@ enum {
 	ALC287_FIXUP_LEGION_15IMHG05_AUTOMUTE,
 	ALC287_FIXUP_YOGA7_14ITL_SPEAKERS,
 	ALC298_FIXUP_LENOVO_C940_DUET7,
+	ALC287_FIXUP_LENOVO_YOGA_BOOK_9I,
 	ALC287_FIXUP_13S_GEN2_SPEAKERS,
 	ALC256_FIXUP_SET_COEF_DEFAULTS,
 	ALC256_FIXUP_SYSTEM76_MIC_NO_PRESENCE,
@@ -3757,6 +3758,23 @@ static void alc298_fixup_lenovo_c940_duet7(struct hda_codec *codec,
 	__snd_hda_apply_fixup(codec, id, action, 0);
 }
 
+/* A special fixup for Lenovo Yoga 9i and Yoga Book 9i 13IRU8
+ * both have the very same PCI SSID and vendor ID, so we need
+ * to apply different fixups depending on the subsystem ID
+ */
+static void alc287_fixup_lenovo_yoga_book_9i(struct hda_codec *codec,
+					   const struct hda_fixup *fix,
+					   int action)
+{
+	int id;
+
+	if (codec->core.subsystem_id == 0x17aa3881)
+		id = ALC287_FIXUP_TAS2781_I2C; /* Yoga Book 9i 13IRU8 */
+	else
+		id = ALC287_FIXUP_IDEAPAD_BASS_SPK_AMP; /* Yoga 9i */
+	__snd_hda_apply_fixup(codec, id, action, 0);
+}
+
 static const struct hda_fixup alc269_fixups[] = {
 	[ALC269_FIXUP_GPIO2] = {
 		.type = HDA_FIXUP_FUNC,
@@ -5764,6 +5782,10 @@ static const struct hda_fixup alc269_fixups[] = {
 		.type = HDA_FIXUP_FUNC,
 		.v.func = alc298_fixup_lenovo_c940_duet7,
 	},
+	[ALC287_FIXUP_LENOVO_YOGA_BOOK_9I] = {
+		.type = HDA_FIXUP_FUNC,
+		.v.func = alc287_fixup_lenovo_yoga_book_9i,
+	},
 	[ALC287_FIXUP_13S_GEN2_SPEAKERS] = {
 		.type = HDA_FIXUP_VERBS,
 		.v.verbs = (const struct hda_verb[]) {
@@ -7084,7 +7106,7 @@ static const struct hda_quirk alc269_fixup_tbl[] = {
 	SND_PCI_QUIRK(0x17aa, 0x3827, "Ideapad S740", ALC285_FIXUP_IDEAPAD_S740_COEF),
 	SND_PCI_QUIRK(0x17aa, 0x3834, "Lenovo IdeaPad Slim 9i 14ITL5", ALC287_FIXUP_YOGA7_14ITL_SPEAKERS),
 	SND_PCI_QUIRK(0x17aa, 0x383d, "Legion Y9000X 2019", ALC285_FIXUP_LEGION_Y9000X_SPEAKERS),
-	SND_PCI_QUIRK(0x17aa, 0x3843, "Yoga 9i", ALC287_FIXUP_IDEAPAD_BASS_SPK_AMP),
+	SND_PCI_QUIRK(0x17aa, 0x3843, "Lenovo Yoga 9i / Yoga Book 9i", ALC287_FIXUP_LENOVO_YOGA_BOOK_9I),
 	SND_PCI_QUIRK(0x17aa, 0x3847, "Legion 7 16ACHG6", ALC287_FIXUP_LEGION_16ACHG6),
 	SND_PCI_QUIRK(0x17aa, 0x384a, "Lenovo Yoga 7 15ITL5", ALC287_FIXUP_YOGA7_14ITL_SPEAKERS),
 	SND_PCI_QUIRK(0x17aa, 0x3852, "Lenovo Yoga 7 14ITL5", ALC287_FIXUP_YOGA7_14ITL_SPEAKERS),
Signature · 1 line
2.51.0
author maintainer
#3 lore raw

PATCH 1/1 ALSA: usb-audio: Add delay quirk for MOONDROP Moonriver2 Ti

In reply to Sasha Levin

From: Lianqin Hu <[email protected]>

[ Upstream commit 49985bc466b51af88d534485631c8cd8c9c65f43 ]

Audio control requests that sets sampling frequency sometimes fail on this card. Adding delay between control messages eliminates that problem.

usb 1-1: New USB device found, idVendor=2fc6, idProduct=f06b usb 1-1: New USB device strings: Mfr=1, Product=2, SerialNumber=3 usb 1-1: Product: MOONDROP Moonriver2 Ti
usb 1-1: Manufacturer: MOONDROP
usb 1-1: SerialNumber: MOONDROP Moonriver2 Ti

---

LLM Generated explanations, may be completely bogus:

## Comprehensive Analysis

### 1. COMMIT MESSAGE ANALYSIS

**Subject:** "ALSA: usb-audio: Add delay quirk for MOONDROP Moonriver2 Ti"

**Key indicators:**
- The commit describes a real hardware issue: "Audio control requests that sets sampling frequency sometimes fail on this card"
- The fix is adding a workaround: "Adding delay between control messages eliminates that problem"
- The commit has proper sign-offs and review tags (Reviewed-by, Signed- off-by from maintainer Takashi Iwai)
- Device identification is clearly provided (idVendor=2fc6, idProduct=f06b)

**Missing tags:** As expected for commits needing manual review, there's no Cc: [email protected] or Fixes: tag. This is NOT a negative signal - it's why this commit needs review.

### 2. CODE CHANGE ANALYSIS

The diff shows a simple two-line addition to sound/usb/quirks.c:

```c
DEVICE_FLG(0x2fc6, 0xf06b, /* MOONDROP Moonriver2 Ti */
           QUIRK_FLAG_CTL_MSG_DELAY),
```

This adds a USB device ID (vendor 0x2fc6, product 0xf06b) to a quirk flags table with the QUIRK_FLAG_CTL_MSG_DELAY flag.

**Technical mechanism:**
- The USB audio device (MOONDROP Moonriver2 Ti DAC/amp) has buggy firmware that cannot handle rapid control messages
- Without the delay, sampling frequency setting fails intermittently
- The QUIRK_FLAG_CTL_MSG_DELAY flag tells the USB audio driver to add delays between control messages for this specific device
- This is a well-established workaround pattern - other devices in the same file use the same quirk (e.g., Luxman D-10X, iBasso DC07 Pro)

### 3. CLASSIFICATION

**This is a HARDWARE QUIRK addition** - one of the explicitly allowed exception categories for stable backports.

- **NOT a new feature:** The quirk mechanism already exists; this just adds a device to the list
- **Fixes a real bug:** Audio device fails to work properly without the quirk
- **Zero code logic changes:** Just a table entry addition

### 4. SCOPE AND RISK ASSESSMENT

**Scope:**
- 2 lines added
- 1 file changed (quirks.c)
- No logic changes, no new code paths

**Risk:** **EXTREMELY LOW**
- The change only affects the specific USB device (0x2fc6:0xf06b)
- Users without this device are completely unaffected
- The quirk mechanism is mature and well-tested
- Similar quirk entries exist for many other devices (visible in the context)
- If the quirk were somehow wrong, it would only affect this one device model

### 5. USER IMPACT

**Who is affected:**
- Users of the MOONDROP Moonriver2 Ti USB DAC/amp
- This is a commercially available audio device that users connect to Linux systems

**Severity without fix:**
- Audio control requests fail intermittently
- Device may not work properly at certain sample rates
- This is a functional bug preventing normal use of hardware

**Impact of fix:**
- Device works correctly
- No negative impact on any other hardware

### 6. STABILITY INDICATORS

- **Reviewed-by:** Cryolitia PukNgae from Uniontech (likely a testing/QA role)
- **Signed-off-by:** Takashi Iwai (ALSA maintainer at SUSE) - trusted maintainer acceptance
- The pattern follows identical entries in the same file
- The quirk flag used (QUIRK_FLAG_CTL_MSG_DELAY) is well-established

### 7. DEPENDENCY CHECK

**Dependencies:** None
- The QUIRK_FLAG_CTL_MSG_DELAY flag already exists in stable kernels
- The DEVICE_FLG macro already exists
- The quirk handling code already exists
- This is a pure data addition to an existing table

**Applies cleanly:** The change is a simple table entry insertion that should apply cleanly to any stable tree that has the USB audio quirks infrastructure.

### Summary

This commit is a **textbook example** of what SHOULD be backported to stable:

1. **Obviously correct:** Simple device ID + existing quirk flag
2. **Fixes a real bug:** Hardware doesn't work properly without it
3. **Small and contained:** 2 lines, no logic changes
4. **No new features:** Uses existing infrastructure
5. **No new APIs:** Just a table entry
6. **Falls under explicit exception:** Hardware quirk addition

The fix enables a commercial USB audio device to work correctly on Linux. The risk is essentially zero since the change only affects this specific device model, and the benefit is direct hardware enablement for users who own this device.

**YES**

 sound/usb/quirks.c | 2 ++
 1 file changed, 2 insertions(+)
sound/usb/quirks.c +2 -0
index 94a8fdc9c6d3c..8a646891ebb44 100644
@@ -2390,6 +2390,8 @@ static const struct usb_audio_quirk_flags_table quirk_flags_table[] = {
 		   QUIRK_FLAG_CTL_MSG_DELAY_1M),
 	DEVICE_FLG(0x2d99, 0x0026, /* HECATE G2 GAMING HEADSET */
 		   QUIRK_FLAG_MIXER_PLAYBACK_MIN_MUTE),
+	DEVICE_FLG(0x2fc6, 0xf06b, /* MOONDROP Moonriver2 Ti */
+		   QUIRK_FLAG_CTL_MSG_DELAY),
 	DEVICE_FLG(0x2fc6, 0xf0b7, /* iBasso DC07 Pro */
 		   QUIRK_FLAG_CTL_MSG_DELAY_1M),
 	DEVICE_FLG(0x30be, 0x0101, /* Schiit Hel */
Signature · 1 line
2.51.0
author maintainer
#4 lore raw

PATCH 1/1 spi: hisi-kunpeng: Fixed the wrong debugfs node name in hisi_spi debugfs initialization

In reply to Sasha Levin

From: Devyn Liu <[email protected]>

[ Upstream commit b062a899c997df7b9ce29c62164888baa7a85833 ]

In hisi_spi_debugfs_init, spi controller pointer is calculated by container_of macro, and the member is hs->dev. But the host cannot be calculated offset directly by this. (hs->dev) points to (pdev->dev), and it is the (host->dev.parent) rather than (host->dev) points to the (pdev->dev), which is set in __spi_alloc_controller.

In this patch, this issues is fixed by getting the spi_controller data from pdev->dev by dev_get_drvdata() directly. (dev->driver_data) points to the spi controller data in the probe stage.

---

LLM Generated explanations, may be completely bogus:

In struct spi_controller, dev is at offset 0. So when container_of is used with an incorrect pointer, it will calculate the "base" of the spi_controller by subtracting 0 from the address - meaning it will use hs->dev (pdev->dev) directly as if it were an spi_controller!

This would cause the access to host->bus_num (used in the snprintf for creating debugfs directory name) to read from the wrong memory location. Looking at struct spi_controller, bus_num is at around offset 72-80 bytes (after dev and list), so it would be reading random data from the platform_device structure.

Let me analyze the severity:

1. **Best case**: Random garbage bus_num value → debugfs directory created with garbage name like "hisi_spi-1234567" or some nonsense
2. **Worst case**: Could potentially read out of bounds if pdev->dev is at the end of an allocation

The fix is simple, correct, and uses the proper method to retrieve the spi_controller pointer.

## Summary Analysis

### 1. COMMIT MESSAGE ANALYSIS
The commit message clearly explains:
- The bug: container_of is incorrectly used - hs->dev points to pdev->dev, not host->dev
- The fix: Use dev_get_drvdata() to correctly get the spi_controller pointer

### 2. CODE CHANGE ANALYSIS
**The Bug:**
- hs->dev = dev where dev = &pdev->dev (platform device's device)
- host = container_of(hs->dev, struct spi_controller, dev) computes wrong offset
- Since dev is at offset 0 in spi_controller, this treats pdev->dev as if it were the spi_controller
- Accessing host->bus_num reads garbage from wrong memory location

**The Fix:**
- Uses dev_get_drvdata(hs->dev) to correctly retrieve the spi_controller pointer
- This works because platform_set_drvdata(pdev, host) was called in probe

**The fix is obviously correct:** It mirrors how other parts of the driver (e.g., interrupt handler) retrieve the spi_controller.

### 3. CLASSIFICATION
- **Bug fix**: Yes, this fixes a real bug where incorrect memory is accessed
- **Category**: Bug fix for incorrect pointer calculation

### 4. SCOPE AND RISK ASSESSMENT
- **Lines changed**: Net -4 lines, very small change
- **Files touched**: 1 driver file
- **Risk**: Very low - changes a local variable initialization in a debugfs init function
- **Could break something else?**: No, this is a purely local fix

### 5. USER IMPACT
- **Who is affected**: Users of HiSilicon Kunpeng SoC SPI controllers with debugfs enabled
- **Severity**: The bug causes incorrect debugfs directory naming and potentially reads garbage memory
- **Hardware support**: This driver is for specific Kunpeng server SoCs

### 6. STABILITY INDICATORS
- Has "Reviewed-by:" tag from another Huawei engineer
- The fix is straightforward and mirrors existing patterns in the driver

### 7. DEPENDENCY CHECK
- The driver exists since v5.13, so this is relevant for 5.15.y, 6.1.y, 6.6.y, etc.
- No dependencies on other commits - standalone fix

## Conclusion

This commit fixes a real bug in pointer calculation that causes incorrect memory access. The fix is:
- Small and surgical (changes one variable initialization)
- Obviously correct (uses the same pattern as other code in the driver)
- Fixes a real bug (incorrect container_of usage)
- Low risk (only affects debugfs, but still fixes incorrect memory access)

The bug could cause reading garbage values or potentially undefined behavior. While debugfs is primarily a debugging interface, the incorrect memory access is still a real bug that should be fixed in stable trees.

**YES**

 drivers/spi/spi-hisi-kunpeng.c | 4 +---
 1 file changed, 1 insertion(+), 3 deletions(-)
drivers/spi/spi-hisi-kunpeng.c +1 -3
index dadf558dd9c0c..80a1a15de0bc3 100644
@@ -161,10 +161,8 @@ static const struct debugfs_reg32 hisi_spi_regs[] = {
 static int hisi_spi_debugfs_init(struct hisi_spi *hs)
 {
 	char name[32];
+	struct spi_controller *host = dev_get_drvdata(hs->dev);
 
-	struct spi_controller *host;
-
-	host = container_of(hs->dev, struct spi_controller, dev);
 	snprintf(name, 32, "hisi_spi%d", host->bus_num);
 	hs->debugfs = debugfs_create_dir(name, NULL);
 	if (IS_ERR(hs->debugfs))
Signature · 1 line
2.51.0
author maintainer
#5 lore raw

PATCH 1/1 scsi: target: iscsi: Fix use-after-free in iscsit_dec_conn_usage_count()

In reply to Sasha Levin

From: Maurizio Lombardi <[email protected]>

[ Upstream commit 9411a89e9e7135cc459178fa77a3f1d6191ae903 ]

In iscsit_dec_conn_usage_count(), the function calls complete() while holding the conn->conn_usage_lock. As soon as complete() is invoked, the waiter (such as iscsit_close_connection()) may wake up and proceed to free the iscsit_conn structure.

If the waiter frees the memory before the current thread reaches spin_unlock_bh(), it results in a KASAN slab-use-after-free as the function attempts to release a lock within the already-freed connection structure.

Fix this by releasing the spinlock before calling complete().

---

LLM Generated explanations, may be completely bogus:

This confirms the race condition analysis perfectly:
1. iscsit_check_conn_usage_count(conn) waits for usage count to become 0
2. Once it returns (after complete() is called), it immediately calls iscsit_free_conn(conn) at line 4363
3. If the decrementer thread hasn't released the spinlock yet, it will try to spin_unlock_bh() on freed memory

### FINAL ASSESSMENT

**Why this should be backported:**

1. **Fixes a real, reproducible bug:** The commit explicitly mentions KASAN detection and has a "Reported-by" tag, confirming this is a real issue that was hit in practice.

2. **Serious bug type:** Use-after-free is a critical memory safety bug that can cause:
- Kernel panics/crashes
- Data corruption
- Potential security exploits (UAF is a common attack vector)

3. **Obvious correctness:** The fix follows the well-known pattern of "unlock before complete" which is the standard way to avoid this class of race conditions. The code change is straightforward and the logic is preserved.

4. **Small and contained:**
- Only 6 lines changed
- Single function modified
- No new APIs or features
- Self-contained fix

5. **Low regression risk:** The change only reorders operations (unlock before complete instead of after). The same checks are made, same operations performed.

6. **Affects production systems:** iSCSI target code is used in enterprise storage environments where kernel crashes are unacceptable.

7. **Long-standing code:** The affected function has been in the kernel since 2011, meaning all stable trees contain this vulnerable code.

8. **Expert review:** Reviewed by Mike Christie (iSCSI maintainer) and signed off by Martin K. Petersen (SCSI maintainer).

9. **Clean backport expected:** No dependencies on other commits, the fix is self-contained and should apply cleanly to all stable trees.

**Risk assessment:** MINIMAL. The fix is a classic pattern, well- reviewed, and doesn't change functionality.

**YES**

 drivers/target/iscsi/iscsi_target_util.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/target/iscsi/iscsi_target_util.c +4 -1
index 262a3e76b4b1c..c1888c42afdd5 100644
@@ -813,8 +813,11 @@ void iscsit_dec_conn_usage_count(struct iscsit_conn *conn)
 	spin_lock_bh(&conn->conn_usage_lock);
 	conn->conn_usage_count--;
 
-	if (!conn->conn_usage_count && conn->conn_waiting_on_uc)
+	if (!conn->conn_usage_count && conn->conn_waiting_on_uc) {
+		spin_unlock_bh(&conn->conn_usage_lock);
 		complete(&conn->conn_waiting_on_uc_comp);
+		return;
+	}
 
 	spin_unlock_bh(&conn->conn_usage_lock);
 }
Signature · 1 line
2.51.0
author maintainer
#6 lore raw

PATCH 1/1 btrfs: fix Wmaybe-uninitialized warning in replay_one_buffer()

In reply to Sasha Levin

From: Qiang Ma <[email protected]>

[ Upstream commit 9c7e71c97c8cd086b148d0d3d1cd84a1deab023c ]

Warning was found when compiling using loongarch64-gcc 12.3.1:

  $ make CFLAGS_tree-log.o=-Wmaybe-uninitialized

In file included from fs/btrfs/ctree.h:21,

		   from fs/btrfs/tree-log.c:12:
  fs/btrfs/accessors.h: In function 'replay_one_buffer':
  fs/btrfs/accessors.h:66:16: warning: 'inode_item' may be used uninitialized [-Wmaybe-uninitialized]
     66 |         return btrfs_get_##bits(eb, s, offsetof(type, member));         \
	|                ^~~~~~~~~~

fs/btrfs/tree-log.c:2803:42: note: 'inode_item' declared here
2803 | struct btrfs_inode_item *inode_item;
| ^~~~~~~~~~

Initialize the inode_item to NULL, the compiler does not seem to see the relation between the first 'wc->log_key.type == BTRFS_INODE_ITEM_KEY' check and the other one that also checks the replay phase.

---

LLM Generated explanations, may be completely bogus:

Now I have a clear understanding of the code flow. Let me verify what the commit changes and analyze it:

## Analysis Summary

### 1. COMMIT MESSAGE ANALYSIS

The commit addresses a compiler warning (-Wmaybe-uninitialized) for the inode_item pointer in replay_one_buffer(). The warning is triggered by certain compilers (loongarch64-gcc 12.3.1 in this case) that don't recognize the relationship between:
- The first check: wc->log_key.type == BTRFS_INODE_ITEM_KEY (which assigns inode_item)
- The later use: wc->log_key.type == BTRFS_INODE_ITEM_KEY && wc->stage == LOG_WALK_REPLAY_INODES (which uses inode_item)

The compiler can't prove that inode_item is always initialized before use due to the complex conditional logic.

### 2. CODE CHANGE ANALYSIS

The change is trivial:

```c
- struct btrfs_inode_item *inode_item;
+ struct btrfs_inode_item *inode_item = NULL;
```

Looking at the control flow:
- Line 2807: if (wc->log_key.type == BTRFS_INODE_ITEM_KEY) - inode_item is assigned via btrfs_item_ptr()
- Line 2838-2845: if (wc->log_key.type == BTRFS_INODE_ITEM_KEY && wc->stage == LOG_WALK_REPLAY_INODES) - inode_item is used via btrfs_inode_mode(eb, inode_item)

Logically, whenever the second condition is true, the first condition must also have been true (both check wc->log_key.type == BTRFS_INODE_ITEM_KEY), so inode_item will have been assigned. But some compilers cannot deduce this relationship due to the second condition also checking wc->stage.

### 3. CLASSIFICATION

This is a **build fix** - it silences a compiler warning. It falls under the "BUILD FIXES" exception category:
- Fixes for compilation warnings
- Zero risk of runtime regression (initializing a pointer to NULL that will always be properly assigned before use)

### 4. SCOPE AND RISK ASSESSMENT

- **Lines changed**: 1 line
- **Files touched**: 1 file (fs/btrfs/tree-log.c)
- **Complexity**: Trivial - just adding = NULL initialization
- **Risk**: Extremely low - this is a defensive initialization that doesn't change runtime behavior

The only possible risk would be if the compiler warning was actually detecting a real bug. However, analyzing the code:
- Line 2838 checks wc->log_key.type == BTRFS_INODE_ITEM_KEY AND wc->stage == LOG_WALK_REPLAY_INODES
- Line 2807 checks wc->log_key.type == BTRFS_INODE_ITEM_KEY
- If we reach line 2845 (where inode_item is used), we must have passed the check at 2838, which implies wc->log_key.type == BTRFS_INODE_ITEM_KEY is true, which means we also entered the block at 2807 and assigned inode_item.

The warning is a false positive.

### 5. USER IMPACT

- This fixes a compiler warning that can be annoying for developers/users who enable -Wmaybe-uninitialized
- Some build configurations with stricter warning settings (e.g., -Werror) could fail to compile without this fix
- The btrfs subsystem is widely used, so build issues affect many users

### 6. STABILITY INDICATORS

- **Reviewed-by: David Sterba <[email protected]>** - David Sterba is the btrfs maintainer
- **Signed-off-by: David Sterba <[email protected]>** - Merged by the maintainer
- This is a simple, obviously correct fix

### 7. DEPENDENCY CHECK

- No dependencies on other commits
- This is a self-contained one-line change
- The code exists in stable trees (tree-log.c is present in all kernel versions)

## Conclusion

This commit is an ideal candidate for stable backporting:

1. **Meets stable criteria**:
- Obviously correct - trivial initialization
- Fixes a real issue - compiler warning that could break builds with strict settings
- Small and contained - single line change
- No new features

2. **Falls under BUILD FIXES exception**: Compiler warning fixes are explicitly allowed in stable

3. **Zero risk**: Initializing a pointer to NULL that is guaranteed to be assigned before use cannot cause any runtime regression

4. **Maintainer approved**: Reviewed and merged by David Sterba, the btrfs maintainer

**YES**

 fs/btrfs/tree-log.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/btrfs/tree-log.c +1 -1
index 1444857de9fe8..ae2e035d013e2 100644
@@ -2800,7 +2800,7 @@ static int replay_one_buffer(struct extent_buffer *eb,
 
 	nritems = btrfs_header_nritems(eb);
 	for (wc->log_slot = 0; wc->log_slot < nritems; wc->log_slot++) {
-		struct btrfs_inode_item *inode_item;
+		struct btrfs_inode_item *inode_item = NULL;
 
 		btrfs_item_key_to_cpu(eb, &wc->log_key, wc->log_slot);
 
Signature · 1 line
2.51.0
author maintainer
#7 lore raw

PATCH 1/1 scsi: target: iscsi: Fix use-after-free in iscsit_dec_session_usage_count()

In reply to Sasha Levin

From: Maurizio Lombardi <[email protected]>

[ Upstream commit 84dc6037390b8607c5551047d3970336cb51ba9a ]

In iscsit_dec_session_usage_count(), the function calls complete() while holding the sess->session_usage_lock. Similar to the connection usage count logic, the waiter signaled by complete() (e.g., in the session release path) may wake up and free the iscsit_session structure immediately.

This creates a race condition where the current thread may attempt to execute spin_unlock_bh() on a session structure that has already been deallocated, resulting in a KASAN slab-use-after-free.

To resolve this, release the session_usage_lock before calling complete() to ensure all dereferences of the sess pointer are finished before the waiter is allowed to proceed with deallocation.

---

LLM Generated explanations, may be completely bogus:

Excellent! Now I have a complete understanding. Let me summarize my analysis:

## ANALYSIS

### 1. COMMIT MESSAGE ANALYSIS

The commit message clearly describes:
- **Bug type:** Use-after-free (UAF)
- **Root cause:** complete() is called while holding sess->session_usage_lock, but the waiter (in session release path) may wake up and call kfree(sess) before the lock is released
- **Detection:** KASAN slab-use-after-free
- **Fix:** Release the lock before calling complete()
- **Tags:**
- Reported-by: - indicates a real bug report
- Reviewed-by: Mike Christie - credible reviewer for SCSI/iSCSI target code

### 2. CODE CHANGE ANALYSIS

**The bug mechanism:**
1. Thread A calls iscsit_dec_session_usage_count(), decrements count to 0
2. Thread A calls complete() while still holding sess->session_usage_lock
3. Thread B (waiting in iscsit_check_session_usage_count()) wakes up from wait_for_completion()
4. Thread B continues to iscsit_close_session() → kfree(sess) at line 4519
5. Thread A tries to call spin_unlock_bh(&sess->session_usage_lock) on freed memory → **UAF**

**The fix:**
- Releases the spinlock *before* calling complete()
- Uses early return to avoid double-unlock
- This is a standard pattern for avoiding UAF when completion wakes up a free-er

**Size:** +4 lines changed, -1 line changed = 3 net lines. Very small and surgical.

### 3. CLASSIFICATION

- **Bug fix:** Yes, fixes a clear use-after-free
- **Security:** Use-after-free bugs can potentially be exploited for privilege escalation or code execution, though this one is in iSCSI target code which requires privileged access to configure
- **Severity:** HIGH - UAF can cause kernel crashes (KASAN detected) and potential security issues

### 4. SCOPE AND RISK ASSESSMENT

- **Lines changed:** ~5 lines (minimal)
- **Files touched:** 1 file (drivers/target/iscsi/iscsi_target_util.c)
- **Complexity:** Very low - simply reorders lock release and complete() call
- **Subsystem:** iSCSI target - mature, widely used for storage
- **Risk:** Very LOW - the fix is semantically identical (unlock happens either way), just changes order

### 5. USER IMPACT

- **Affected users:** Anyone using Linux iSCSI target (LIO) with active session teardown
- **Severity if hit:** Kernel crash/panic, or potentially worse (security issue)
- **Likelihood:** Race condition, so timing-dependent, but clearly can be triggered (reported by Red Hat engineer with KASAN)

### 6. STABILITY INDICATORS

- Reviewed-by: Mike Christie <[email protected]> - Mike Christie is a well-known SCSI subsystem maintainer/contributor
- Reported-by: tag indicates this is a real-world bug
- Accepted by Martin K. Petersen (SCSI maintainer)

### 7. DEPENDENCY CHECK

- No dependencies on other commits
- The session_usage_lock, session_waiting_on_uc, and completion structure exist in all stable trees (they're fundamental to iSCSI target operation)
- Clean, standalone fix

### CONCLUSION

This commit is an **ideal candidate for stable backport**:

1. **Fixes a real, serious bug:** Use-after-free detected by KASAN, reported by Red Hat
2. **Obviously correct:** Standard pattern of "unlock before complete when waiter frees the object"
3. **Small and contained:** Only 5 lines changed in one function
4. **No new features:** Pure bug fix
5. **Low risk:** The change is semantically equivalent (lock must be released anyway), just changes order
6. **Wide impact:** iSCSI target is widely deployed in enterprise storage environments
7. **Reviewed by expert:** Mike Christie is a recognized SCSI expert

The fix follows the well-established pattern seen in many similar fixes throughout the kernel where a completion must not be signaled while holding a lock that protects the structure being freed by the waiter.

**YES**

 drivers/target/iscsi/iscsi_target_util.c | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)
drivers/target/iscsi/iscsi_target_util.c +4 -1
index 5e6cf34929b55..262a3e76b4b1c 100644
@@ -741,8 +741,11 @@ void iscsit_dec_session_usage_count(struct iscsit_session *sess)
 	spin_lock_bh(&sess->session_usage_lock);
 	sess->session_usage_count--;
 
-	if (!sess->session_usage_count && sess->session_waiting_on_uc)
+	if (!sess->session_usage_count && sess->session_waiting_on_uc) {
+		spin_unlock_bh(&sess->session_usage_lock);
 		complete(&sess->session_waiting_on_uc_comp);
+		return;
+	}
 
 	spin_unlock_bh(&sess->session_usage_lock);
 }
Signature · 1 line
2.51.0
author maintainer
#8 lore raw

PATCH 1/1 Revert "drm/amd/display: pause the workload setting in dm"

In reply to Sasha Levin

From: Alex Deucher <[email protected]>

[ Upstream commit f377ea0561c9576cdb7e3890bcf6b8168d455464 ]

This reverts commit bc6d54ac7e7436721a19443265f971f890c13cc5.

The workload profile needs to be in the default state when the dc idle optimizaion state is entered. However, when jobs come in for video or GFX or compute, the profile may be set to a non-default profile resulting in the dc idle optimizations not taking affect and resulting in higher power usage. As such we need to pause the workload profile changes during this transition. When this patch was originally committed, it caused a regression with a Dell U3224KB display, but no other problems were reported at the time. When it was reapplied (this patch) to address increased power usage, it seems to have caused additional regressions. This change seems to have a number of side affects (audio issues, stuttering, etc.). I suspect the pause should only happen when all displays are off or in static screen mode, but I think this call site gets called more often than that which results in idle state entry more often than intended. For now revert.

---

LLM Generated explanations, may be completely bogus:

Now I have a complete picture. Let me analyze this commit for backporting.

## Analysis Summary

### 1. COMMIT MESSAGE ANALYSIS
- This is a **revert commit** that undoes a problematic patch
- The commit message is detailed and explains the technical reasoning
- **Five bug reports** are closed by this revert (issues #4894, #4717, #4725, #4517, #4806)
- The message acknowledges the original intent was good (power savings during idle) but the implementation causes regressions
- Symptoms include: audio issues, stuttering, display corruption (Dell U3224KB)
- Cherry-picked from mainline commit 1412482b714358ffa30d38fd3dd0b05795163648
- **Has Reviewed-by tag**: Yang Wang reviewed this

### 2. CODE CHANGE ANALYSIS
The revert removes 11 lines of code that:
- Added calls to amdgpu_dpm_pause_power_profile(adev, true/false) around dc_allow_idle_optimizations()
- These calls were meant to pause power profile changes during idle optimization entry
- The problem: The call site amdgpu_dm_crtc_vblank_control_worker gets called more frequently than intended (not just when displays are off/static screen)
- This causes idle state entry to happen too often, leading to various side effects

The diff is simple and surgical:
- **Only removes code**: No new code added
- **Removes 2 variable declarations** (adev, r)
- **Removes 9 lines of power profile pause/resume logic**
- Single file changed, clean and contained

### 3. CLASSIFICATION
- **This is a regression fix** - it reverts code that was introduced and caused user-visible bugs
- The original commit bc6d54ac7e7436721a19443265f971f890c13cc5 was added in March 2025
- It was reverted once in May 2025 (988b1d2164a1c) for Dell display corruption
- Then it was **re-applied** (5d7b36d1bffce) - and now the new regressions appeared
- This is a follow-up revert to fix the additional regressions

### 4. SCOPE AND RISK ASSESSMENT
- **Very small scope**: 11 lines removed in a single file
- **Low risk**: Removing problematic code reverts to previously working state
- **AMD GPU display driver** - affects many users with AMD graphics cards
- The code being removed was relatively new (March 2025) so reverting returns to well-tested state

### 5. USER IMPACT
- **HIGH impact** for affected users - audio issues, stuttering, and display corruption are severe
- The bug reports indicate real users are hitting these issues
- AMD GPU users are a significant portion of Linux desktop users
- The regressions affect usability (audio skipping, video stuttering, display problems)

### 6. STABILITY INDICATORS
- **Reviewed-by: Yang Wang**
- **Tested in mainline first**: Cherry-picked from mainline commit
- The revert was done by AMD's primary maintainer (Alex Deucher)
- AMD developers clearly understand the root cause and explicitly chose to revert

### 7. DEPENDENCY CHECK
- **No dependencies**: This is a pure revert of code that was previously added
- The affected code **definitely exists in 6.18.y stable** - I confirmed the problematic commit 5d7b36d1bffce is in 6.18.y
- The code should also exist in 6.17.y stable based on the grep results

### 8. SPECIAL CONSIDERATIONS FOR THIS COMMIT
This is the classic case for stable backporting:
- A commit was added that seemed good but caused regressions
- The revert is small, simple, and returns the code to its previously working state
- Multiple bug reports confirm real users are affected
- The fix (revert) is obviously correct - it removes code that shouldn't have been added in its current form

The commit message even indicates the maintainer understands what a proper fix would be ("pause should only happen when all displays are off or in static screen mode") but correctly chose to revert first for stability.

### CONCLUSION

This is an **excellent candidate for stable backporting**:

1. **Fixes real user-visible bugs**: Audio issues, stuttering, display corruption
2. **Small and surgical**: Just removes 11 lines of problematic code
3. **No risk of new regressions**: Returns to previously working state
4. **Already tested**: Cherry-picked from mainline, reviewed by AMD developers
5. **Multiple bug reports closed**: Shows widespread impact
6. **Code exists in stable**: The problematic code is confirmed in 6.18.y (and likely 6.17.y)
7. **Classic revert pattern**: The safest type of stable fix

The only potential issue is ensuring the code being reverted actually exists in the target stable tree. For 6.18.y, I confirmed it does (commit 5d7b36d1bffce).

**YES**

 .../gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_crtc.c    | 11 -----------
 1 file changed, 11 deletions(-)
drivers/gpu/drm/amd/display/amdgpu_dm/amdgpu_dm_crtc.c +0 -11
index 38f9ea313dcbb..2e7ee77c010e1 100644
@@ -248,8 +248,6 @@ static void amdgpu_dm_crtc_vblank_control_worker(struct work_struct *work)
 	struct vblank_control_work *vblank_work =
 		container_of(work, struct vblank_control_work, work);
 	struct amdgpu_display_manager *dm = vblank_work->dm;
-	struct amdgpu_device *adev = drm_to_adev(dm->ddev);
-	int r;
 
 	mutex_lock(&dm->dc_lock);
 
@@ -279,16 +277,7 @@ static void amdgpu_dm_crtc_vblank_control_worker(struct work_struct *work)
 
 	if (dm->active_vblank_irq_count == 0) {
 		dc_post_update_surfaces_to_stream(dm->dc);
-
-		r = amdgpu_dpm_pause_power_profile(adev, true);
-		if (r)
-			dev_warn(adev->dev, "failed to set default power profile mode\n");
-
 		dc_allow_idle_optimizations(dm->dc, true);
-
-		r = amdgpu_dpm_pause_power_profile(adev, false);
-		if (r)
-			dev_warn(adev->dev, "failed to restore the power profile mode\n");
 	}
 
 	mutex_unlock(&dm->dc_lock);
Signature · 1 line
2.51.0
author maintainer
#9 lore raw

PATCH 1/1 btrfs: sync read disk super and set block size

In reply to Sasha Levin

From: Edward Adam Davis <[email protected]>

[ Upstream commit 3f29d661e5686f3aa14e6f11537ff5c49846f2e2 ]

When the user performs a btrfs mount, the block device is not set correctly. The user sets the block size of the block device to 0x4000 by executing the BLKBSZSET command.
Since the block size change also changes the mapping->flags value, this further affects the result of the mapping_min_folio_order() calculation.

Let's analyze the following two scenarios:

Scenario 1: Without executing the BLKBSZSET command, the block size is 0x1000, and mapping_min_folio_order() returns 0;

Scenario 2: After executing the BLKBSZSET command, the block size is 0x4000, and mapping_min_folio_order() returns 2.

do_read_cache_folio() allocates a folio before the BLKBSZSET command is executed. This results in the allocated folio having an order value of 0. Later, after BLKBSZSET is executed, the block size increases to 0x4000, and the mapping_min_folio_order() calculation result becomes 2.

This leads to two undesirable consequences:

1. filemap_add_folio() triggers a VM_BUG_ON_FOLIO(folio_order(folio) < mapping_min_folio_order(mapping)) assertion.

2. The syzbot report [1] shows a null pointer dereference in create_empty_buffers() due to a buffer head allocation failure.

Synchronization should be established based on the inode between the BLKBSZSET command and read cache page to prevent inconsistencies in block size or mapping flags before and after folio allocation.

[1]

KASAN: null-ptr-deref in range [0x0000000000000000-0x0000000000000007]
RIP: 0010:create_empty_buffers+0x4d/0x480 fs/buffer.c:1694
Call Trace:
 folio_create_buffers+0x109/0x150 fs/buffer.c:1802
 block_read_full_folio+0x14c/0x850 fs/buffer.c:2403
 filemap_read_folio+0xc8/0x2a0 mm/filemap.c:2496
 do_read_cache_folio+0x266/0x5c0 mm/filemap.c:4096
 do_read_cache_page mm/filemap.c:4162 [inline]
 read_cache_page_gfp+0x29/0x120 mm/filemap.c:4195
 btrfs_read_disk_super+0x192/0x500 fs/btrfs/volumes.c:1367

---

LLM Generated explanations, may be completely bogus:

So this commit is going into v6.19. Let me now analyze the complete picture.

## Analysis Summary

### 1. COMMIT MESSAGE ANALYSIS

**Subject:** "btrfs: sync read disk super and set block size"

**Key indicators:**
- **Reported-by: syzbot**: Indicates a real bug found by fuzzing
- **Closes: syzkaller bug link**: Confirms this is fixing a reported issue
- **Reviewed-by: Filipe Manana**: Core btrfs maintainer reviewed and approved
- **Signed-off-by: David Sterba**: Btrfs maintainer signed off

The commit message describes a race condition that leads to:
1. VM_BUG_ON_FOLIO assertion failure
2. Null pointer dereference in create_empty_buffers()

### 2. CODE CHANGE ANALYSIS

The fix is **extremely simple** - just 2 lines added:

```c
+       filemap_invalidate_lock(mapping);
        page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT,
GFP_NOFS);
+       filemap_invalidate_unlock(mapping);
```

**Root cause:** A race between:
1. btrfs_read_disk_super() allocating a folio via read_cache_page_gfp()
2. User space calling BLKBSZSET ioctl to change block size

When the block size changes mid-operation, the folio order requirements change, causing either a BUG_ON or null pointer dereference.

**Why the fix works:** The filemap_invalidate_lock() provides synchronization between the page cache reader and the block size setter (in set_blocksize()), preventing the race.

### 3. CLASSIFICATION

- **Bug type:** Race condition leading to kernel crash (null pointer deref) or BUG_ON
- **Severity:** High - causes kernel panic/crash
- **Category:** Synchronization fix

### 4. SCOPE AND RISK ASSESSMENT

- **Lines changed:** 2 additions only
- **Files touched:** 1 (fs/btrfs/volumes.c)
- **Complexity:** Very low - just lock/unlock pair around existing call
- **Risk:** LOW - the lock is well-understood and used elsewhere for exactly this purpose

### 5. USER IMPACT

- **Who is affected:** Any btrfs user where concurrent block device operations occur
- **Triggering scenario:** User space modifying block device size while btrfs is mounting/reading superblock
- **Severity of impact:** Kernel crash (HIGH)

### 6. STABILITY INDICATORS

- **Reviewed-by:** Filipe Manana (senior btrfs developer at SUSE)
- **Multiple sign-offs:** Through the btrfs maintainer chain
- **Syzbot reported:** Reproducible issue

### 7. CRITICAL DEPENDENCY CHECK

**THIS IS THE KEY ISSUE:** The fix relies on set_blocksize() also taking filemap_invalidate_lock(). This was added by commit c0e473a0d2264 ("block: fix race between set_blocksize and read paths") which is **only in kernel 6.15+**.

Without that block layer fix:
- On kernels < 6.15: set_blocksize() does NOT take filemap_invalidate_lock, so this btrfs fix would NOT provide proper synchronization
- The btrfs fix by itself would be ineffective in preventing the race

### Risk vs Benefit Analysis

**Benefits:**
- Fixes real crash reported by syzbot
- Very small, surgical fix (2 lines)
- Well-reviewed by btrfs maintainers
- Follows established synchronization pattern

**Risks/Concerns:**
- **CRITICAL DEPENDENCY**: Requires c0e473a0d2264 to be present for the synchronization to work
- Without the block layer fix, this btrfs fix is essentially a no-op (won't actually synchronize)
- The block layer fix is only in 6.15+, so backporting this btrfs fix to 6.14 or earlier would be pointless without also backporting the block layer changes

### Conclusion

This commit fixes a real kernel crash (null pointer dereference) in btrfs that was reported by syzbot. The fix itself is minimal and correct
- it adds proper locking around the read_cache_page_gfp() call to synchronize with block size changes.

However, there is a **critical dependency issue**: This fix only provides effective synchronization when paired with commit c0e473a0d2264 ("block: fix race between set_blocksize and read paths") which adds the corresponding lock acquisition in set_blocksize(). That commit is only in kernel 6.15+.

For stable trees **6.15.y and later**: This is a clear YES - fixes a real crash with minimal risk.

For stable trees **6.14 and earlier**: The fix would be ineffective without also backporting the block layer changes, which are more invasive.

Given that the question is about backporting in general and this commit would only be effective in 6.15+ (where the block layer infrastructure exists), and the fix is correct, small, and addresses a real crash, the answer depends on the target kernel. For the current stable (6.15+), this should be backported.

**YES**

 fs/btrfs/volumes.c | 2 ++
 1 file changed, 2 insertions(+)
fs/btrfs/volumes.c +2 -0
index 48e717c105c35..8e7dcb12af4c4 100644
@@ -1365,7 +1365,9 @@ struct btrfs_super_block *btrfs_read_disk_super(struct block_device *bdev,
 				      (bytenr + BTRFS_SUPER_INFO_SIZE) >> PAGE_SHIFT);
 	}
 
+	filemap_invalidate_lock(mapping);
 	page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT, GFP_NOFS);
+	filemap_invalidate_unlock(mapping);
 	if (IS_ERR(page))
 		return ERR_CAST(page);
 
Signature · 1 line
2.51.0
author maintainer
#10 lore raw

PATCH 1/1 wifi: mac80211: don't increment crypto_tx_tailroom_needed_cnt twice

In reply to Sasha Levin

From: Miri Korenblit <[email protected]>

[ Upstream commit 3f3d8ff31496874a69b131866f62474eb24ed20a ]

In reconfig, in case the driver asks to disconnect during the reconfig, all the keys of the interface are marked as tainted.
Then ieee80211_reenable_keys will loop over all the interface keys, and for each one it will
a) increment crypto_tx_tailroom_needed_cnt
b) call ieee80211_key_enable_hw_accel, which in turn will detect that this key is tainted, so it will mark it as "not in hardware", which is paired with crypto_tx_tailroom_needed_cnt incrementation, so we get two incrementations for each tainted key.
Then we get a warning in ieee80211_free_keys.

To fix it, don't increment the count in ieee80211_reenable_keys for tainted keys

---

LLM Generated explanations, may be completely bogus:

So KEY_FLAG_TAINTED was introduced in v4.20. The bug being fixed is likely in all kernels from 4.20 onward. Let me verify the current state after the patch would be applied.

The patch being analyzed changes:

```c
list_for_each_entry(key, &sdata->key_list, list) {
    increment_tailroom_need_count(sdata);  // OLD: unconditional
    ieee80211_key_enable_hw_accel(key);
}
```

to:

```c
list_for_each_entry(key, &sdata->key_list, list) {
    if (!(key->flags & KEY_FLAG_TAINTED))  // NEW: skip for tainted
        increment_tailroom_need_count(sdata);
    ieee80211_key_enable_hw_accel(key);
}
```

This is correct because:
- For non-tainted keys: increment once here, and if HW accel succeeds, it will be decremented in ieee80211_key_enable_hw_accel() (line 187). Net result: proper accounting.
- For tainted keys: skip here, let ieee80211_key_enable_hw_accel() handle the increment (line 141) when clearing KEY_FLAG_UPLOADED_TO_HARDWARE. Net result: proper accounting.

## Analysis Summary

**1. COMMIT MESSAGE ANALYSIS:**
- Clear explanation of the problem: double increment of crypto_tx_tailroom_needed_cnt for tainted keys during reconfig
- The symptom is a warning in ieee80211_free_keys
- Reviewed-by from Johannes Berg (mac80211 maintainer) adds confidence

**2. CODE CHANGE ANALYSIS:**
- The bug: In ieee80211_reenable_keys(), for each key:
1. increment_tailroom_need_count(sdata) is called unconditionally
2. ieee80211_key_enable_hw_accel(key) is called

- For tainted keys (marked when driver requests disconnect during reconfig), ieee80211_key_enable_hw_accel() will:
- Also call increment_tailroom_need_count(sdata) at line 141 if the key was uploaded to hardware
- Clear the KEY_FLAG_UPLOADED_TO_HARDWARE flag

- Result: Two increments per tainted key instead of one

- The fix: Skip the first increment for tainted keys since they'll get their increment inside ieee80211_key_enable_hw_accel()

**3. CLASSIFICATION:**
- This is a clear BUG FIX for a reference counting error
- Not a feature addition
- Fixes a real warning that users would see in kernel logs

**4. SCOPE AND RISK ASSESSMENT:**
- Very small change: adds a simple conditional check (1 line changed)
- Localized to mac80211 key handling
- Low risk: the logic is straightforward and has been reviewed by the subsystem maintainer
- The worst-case if the fix is wrong would be the opposite accounting error

**5. USER IMPACT:**
- WiFi users doing rekeys or going through suspend/resume/HW restart with certain driver/firmware combinations could hit this
- The symptom is a kernel warning (WARN_ON_ONCE in ieee80211_free_keys)
- It causes incorrect tailroom accounting which could potentially lead to issues with software encryption

**6. STABILITY INDICATORS:**
- Reviewed-by: Johannes Berg (mac80211 maintainer)
- The code path and fix are straightforward

**7. DEPENDENCY CHECK:**
- KEY_FLAG_TAINTED exists since v4.20
- The function ieee80211_reenable_keys() exists in stable trees
- The code affected exists in all supported stable kernels
- No dependency on other commits - this is a standalone fix

The fix is small, surgical, reviewed by the subsystem maintainer, fixes a real bug (warning + incorrect reference counting), and meets all stable kernel criteria.

**YES**

 net/mac80211/key.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
net/mac80211/key.c +2 -1
index d5da7ccea66e0..04c8809173d7f 100644
@@ -987,7 +987,8 @@ void ieee80211_reenable_keys(struct ieee80211_sub_if_data *sdata)
 
 	if (ieee80211_sdata_running(sdata)) {
 		list_for_each_entry(key, &sdata->key_list, list) {
-			increment_tailroom_need_count(sdata);
+			if (!(key->flags & KEY_FLAG_TAINTED))
+				increment_tailroom_need_count(sdata);
 			ieee80211_key_enable_hw_accel(key);
 		}
 	}
Signature · 1 line
2.51.0
author maintainer
#11 lore raw

PATCH 1/1 spi: intel-pci: Add support for Nova Lake SPI serial flash

In reply to Sasha Levin

From: Alan Borzeszkowski <[email protected]>

[ Upstream commit caa329649259d0f90c0056c9860ca659d4ba3211 ]

Add Intel Nova Lake PCH-S SPI serial flash PCI ID to the list of supported devices. This is the same controller found in previous generations.

---

LLM Generated explanations, may be completely bogus:

## Comprehensive Backport Analysis

### 1. COMMIT MESSAGE ANALYSIS

**Subject:** "spi: intel-pci: Add support for Nova Lake SPI serial flash"

**Key information from message:**
- Adds a new PCI ID for Intel Nova Lake PCH-S SPI serial flash controller
- Explicitly states: "This is the same controller found in previous generations"
- Has proper sign-offs from Intel developer and maintainer acknowledgment
- Link to patch message provided for traceability

**Notable:** No Fixes: tag or Cc: stable tag, but as noted in the analysis guidelines, this is expected for commits requiring manual review.

### 2. CODE CHANGE ANALYSIS

The diff shows a **single-line addition**:

```c
{ PCI_VDEVICE(INTEL, 0x6e24), (unsigned long)&cnl_info },
```

This adds PCI device ID 0x6e24 to the intel_spi_pci_ids[] table, using the existing cnl_info configuration structure (Cannon Lake info).

**Technical details:**
- The change adds one entry to the PCI device ID table
- Uses the well-established PCI_VDEVICE() macro
- References cnl_info, which already exists and is used by many other device IDs in this driver
- The insertion is alphabetically ordered (0x6e24 is placed between 0x5825 and 0x7723)
- No new code paths, functions, or logic introduced

### 3. CLASSIFICATION

**This is a NEW DEVICE ID addition** - one of the explicitly listed exceptions in the stable kernel rules.

From the guidelines:

Quoted 4 lines

**NEW DEVICE IDs (Very Common):**
- Adding PCI IDs, USB IDs, ACPI IDs, etc. to existing drivers
- These are trivial one-line additions that enable hardware support
- Rule: The driver must already exist in stable; only the ID is new

This commit fits this exception perfectly:
- The spi-intel-pci driver already exists in stable kernels
- Only the PCI ID is being added
- Uses existing configuration (cnl_info)

### 4. SCOPE AND RISK ASSESSMENT

**Scope:**
- **Lines changed:** 1 line added
- **Files touched:** 1 file (drivers/spi/spi-intel-pci.c)
- **Complexity:** Minimal - just a table entry

**Risk assessment:**
- **Extremely LOW risk** - This is one of the safest possible changes
- The new ID only matches Nova Lake hardware
- Existing hardware continues to work exactly as before
- If the ID is somehow wrong, only Nova Lake devices would be affected
- The cnl_info structure is already well-tested with many other Intel platforms

### 5. USER IMPACT

**Who benefits:**
- Users with Intel Nova Lake PCH-S systems
- Enterprise customers deploying on newer Intel hardware
- Without this patch, SPI flash on Nova Lake systems won't be recognized

**Impact assessment:**
- **Positive impact:** Enables SPI flash access on new hardware
- **Negative impact potential:** None for existing users
- **Hardware scope:** This is a platform-level chipset, so all Nova Lake systems are affected

### 6. STABILITY INDICATORS

- **Acked-by:** Mika Westerberg (Intel kernel maintainer) - positive signal
- **Signed-off-by:** Mark Brown (SPI subsystem maintainer) - indicates proper review
- The commit message explicitly states this uses the "same controller found in previous generations" - this suggests the hardware is compatible and doesn't need new code

### 7. DEPENDENCY CHECK

**Dependencies:** None
- This commit is completely self-contained
- It only adds an entry to an existing table
- No prerequisites needed - the driver infrastructure is already in place

**Stable tree compatibility:**
- The spi-intel-pci.c driver has been in the kernel for years
- The cnl_info structure exists in all relevant stable trees
- This patch will apply cleanly to any stable kernel that has this driver

### 8. VERDICT REASONING

**Why this SHOULD be backported:**

1. **Explicitly allowed by stable rules:** New device IDs are a documented exception that IS appropriate for stable trees

2. **Zero regression risk:** Adding a new PCI ID to a table cannot possibly break existing functionality

3. **Minimal change:** Single line addition is as small and contained as possible

4. **Real user benefit:** Users with Nova Lake hardware need this to have functional SPI flash support

5. **Mature driver:** The intel-spi-pci driver is well-established and the cnl_info configuration is used by many other platforms

6. **Proper review:** Has maintainer acks from both Intel and SPI subsystem maintainers

**No concerns:**
- No dependencies
- No backport adjustments needed
- Will apply cleanly
- No new code paths or features

This is a textbook example of a commit that should be backported to stable - it's a trivial device ID addition that enables hardware support using existing, well-tested driver code.

**YES**

 drivers/spi/spi-intel-pci.c | 1 +
 1 file changed, 1 insertion(+)
drivers/spi/spi-intel-pci.c +1 -0
index b8c572394aac2..bce3d149bea18 100644
@@ -81,6 +81,7 @@ static const struct pci_device_id intel_spi_pci_ids[] = {
 	{ PCI_VDEVICE(INTEL, 0x54a4), (unsigned long)&cnl_info },
 	{ PCI_VDEVICE(INTEL, 0x5794), (unsigned long)&cnl_info },
 	{ PCI_VDEVICE(INTEL, 0x5825), (unsigned long)&cnl_info },
+	{ PCI_VDEVICE(INTEL, 0x6e24), (unsigned long)&cnl_info },
 	{ PCI_VDEVICE(INTEL, 0x7723), (unsigned long)&cnl_info },
 	{ PCI_VDEVICE(INTEL, 0x7a24), (unsigned long)&cnl_info },
 	{ PCI_VDEVICE(INTEL, 0x7aa4), (unsigned long)&cnl_info },
Signature · 1 line
2.51.0
author maintainer
#12 lore raw

PATCH 1/1 btrfs: reject new transactions if the fs is fully read-only

In reply to Sasha Levin

From: Qu Wenruo <[email protected]>

[ Upstream commit 1972f44c189c8aacde308fa9284e474c1a5cbd9f ]

[BUG]
There is a bug report where a heavily fuzzed fs is mounted with all rescue mount options, which leads to the following warnings during unmount:

BTRFS: Transaction aborted (error -22)

  Modules linked in:
  CPU: 0 UID: 0 PID: 9758 Comm: repro.out Not tainted
  6.19.0-rc5-00002-gb71e635feefc #7 PREEMPT(full)
  Hardware name: QEMU Standard PC (i440FX + PIIX, 1996), BIOS 1.15.0-1 04/01/2014
  RIP: 0010:find_free_extent_update_loop fs/btrfs/extent-tree.c:4208 [inline]
  RIP: 0010:find_free_extent+0x52f0/0x5d20 fs/btrfs/extent-tree.c:4611
  Call Trace:
   <TASK>
   btrfs_reserve_extent+0x2cd/0x790 fs/btrfs/extent-tree.c:4705
   btrfs_alloc_tree_block+0x1e1/0x10e0 fs/btrfs/extent-tree.c:5157
   btrfs_force_cow_block+0x578/0x2410 fs/btrfs/ctree.c:517
   btrfs_cow_block+0x3c4/0xa80 fs/btrfs/ctree.c:708
   btrfs_search_slot+0xcad/0x2b50 fs/btrfs/ctree.c:2130
   btrfs_truncate_inode_items+0x45d/0x2350 fs/btrfs/inode-item.c:499
   btrfs_evict_inode+0x923/0xe70 fs/btrfs/inode.c:5628
   evict+0x5f4/0xae0 fs/inode.c:837
   __dentry_kill+0x209/0x660 fs/dcache.c:670
   finish_dput+0xc9/0x480 fs/dcache.c:879
   shrink_dcache_for_umount+0xa0/0x170 fs/dcache.c:1661
   generic_shutdown_super+0x67/0x2c0 fs/super.c:621
   kill_anon_super+0x3b/0x70 fs/super.c:1289
   btrfs_kill_super+0x41/0x50 fs/btrfs/super.c:2127
   deactivate_locked_super+0xbc/0x130 fs/super.c:474
   cleanup_mnt+0x425/0x4c0 fs/namespace.c:1318
   task_work_run+0x1d4/0x260 kernel/task_work.c:233
   exit_task_work include/linux/task_work.h:40 [inline]
   do_exit+0x694/0x22f0 kernel/exit.c:971
   do_group_exit+0x21c/0x2d0 kernel/exit.c:1112
   __do_sys_exit_group kernel/exit.c:1123 [inline]
   __se_sys_exit_group kernel/exit.c:1121 [inline]
   __x64_sys_exit_group+0x3f/0x40 kernel/exit.c:1121
   x64_sys_call+0x2210/0x2210 arch/x86/include/generated/asm/syscalls_64.h:232
   do_syscall_x64 arch/x86/entry/syscall_64.c:63 [inline]
   do_syscall_64+0xe8/0xf80 arch/x86/entry/syscall_64.c:94
   entry_SYSCALL_64_after_hwframe+0x77/0x7f
  RIP: 0033:0x44f639
  Code: Unable to access opcode bytes at 0x44f60f.
  RSP: 002b:00007ffc15c4e088 EFLAGS: 00000246 ORIG_RAX: 00000000000000e7
  RAX: ffffffffffffffda RBX: 00000000004c32f0 RCX: 000000000044f639
  RDX: 000000000000003c RSI: 00000000000000e7 RDI: 0000000000000001
  RBP: 0000000000000001 R08: ffffffffffffffc0 R09: 0000000000000000
  R10: 0000000000000000 R11: 0000000000000246 R12: 00000000004c32f0
  R13: 0000000000000001 R14: 0000000000000000 R15: 0000000000000001
   </TASK>

Since rescue mount options will mark the full fs read-only, there should be no new transaction triggered.

But during unmount we will evict all inodes, which can trigger a new transaction, and triggers warnings on a heavily corrupted fs.

[CAUSE]
Btrfs allows new transaction even on a read-only fs, this is to allow log replay happen even on read-only mounts, just like what ext4/xfs do.

However with rescue mount options, the fs is fully read-only and cannot be remounted read-write, thus in that case we should also reject any new transactions.

[FIX]
If we find the fs has rescue mount options, we should treat the fs as error, so that no new transaction can be started.

---

LLM Generated explanations, may be completely bogus:

Now I have all the information I need to analyze this commit. Let me provide a comprehensive analysis.

## Commit Analysis

### 1. COMMIT MESSAGE ANALYSIS

**Subject:** "btrfs: reject new transactions if the fs is fully read- only"

The commit clearly describes a bug fix with:
- A detailed BUG section with a full kernel stack trace showing warnings during unmount with rescue mount options
- A CAUSE section explaining why this bug happens
- A FIX section describing the solution
- The commit is well-documented with Reported-by: tag and a link to the bug report
- Multiple reviews: Reviewed-by: Boris Burkov, Reviewed-by: Johannes Thumshirn, Reviewed-by: David Sterba (the btrfs maintainer)
- Signed off by the btrfs maintainer David Sterba

### 2. CODE CHANGE ANALYSIS

The fix consists of two parts:

**Part 1 - New helper function (fs/btrfs/disk-io.c):**

```c
static bool fs_is_full_ro(const struct btrfs_fs_info *fs_info)
{
    if (!sb_rdonly(fs_info->sb))
        return false;
    if (unlikely(fs_info->mount_opt & BTRFS_MOUNT_FULL_RO_MASK))
        return true;
    return false;
}
```

This helper checks if the filesystem is both read-only AND has any of the rescue mount options set.

**Part 2 - Setting fs_error during mount (fs/btrfs/disk-io.c):**

```c
/* If the fs has any rescue options, no transaction is allowed. */
if (fs_is_full_ro(fs_info))
    WRITE_ONCE(fs_info->fs_error, -EROFS);
```

This sets the fs_error field during mount if rescue options are used.

**Part 3 - New macro (fs/btrfs/fs.h):**

```c
#define BTRFS_MOUNT_FULL_RO_MASK        \
    (BTRFS_MOUNT_NOLOGREPLAY |      \
     BTRFS_MOUNT_IGNOREBADROOTS |       \
     BTRFS_MOUNT_IGNOREDATACSUMS |      \
     BTRFS_MOUNT_IGNOREMETACSUMS |      \
     BTRFS_MOUNT_IGNORESUPERFLAGS)
```

**Why the fix works:**
The existing code in start_transaction() (transaction.c:612-613) checks:

```c
if (BTRFS_FS_ERROR(fs_info))
    return ERR_PTR(-EROFS);
```

By setting fs_error to -EROFS during mount when rescue options are present, any later attempt to start a transaction (including during inode eviction at unmount time) will fail early and return -EROFS instead of proceeding and hitting allocation failures.

### 3. CLASSIFICATION

This is a **bug fix**, not a feature addition. It fixes a real-world issue where:
- Mounting a corrupted filesystem with rescue mount options (which are read-only only)
- Trying to unmount causes inode eviction
- Inode eviction triggers transaction creation
- Transaction starts but fails because the fs can't actually write (it's read-only with rescue options)
- Results in WARN_ON/oops and potential issues

The fix leverages the existing fs_error mechanism to reject transactions early instead of letting them start and fail later with confusing errors.

### 4. SCOPE AND RISK ASSESSMENT

**Lines changed:** ~20 lines added, no lines removed **Files touched:** 2 files (fs/btrfs/disk-io.c, fs/btrfs/fs.h) **Complexity:** Low - simple check and assignment

**Risk assessment:**
- **LOW RISK**: The change is surgical and leverages existing mechanisms
- The fs_error field and BTRFS_FS_ERROR() check are well-established in btrfs
- The rescue mount options already require read-only mode - this just ensures transaction rejection is enforced
- The fix is in the mount path, not a hot path
- Multiple reviews from btrfs maintainers including David Sterba

**Potential impact:**
- Could theoretically affect behavior if some code expected transactions to start (even if they'd fail later)
- But this is the correct behavior - rescue options should never allow writes

### 5. USER IMPACT

**Who is affected:**
- Users mounting heavily corrupted btrfs filesystems with rescue mount options (e.g., rescue=all, rescue=ibadroots, etc.)
- This is a common data recovery scenario

**Severity:**
- Without the fix: Users get confusing WARN_ON messages and potential issues during unmount
- With the fix: Clean rejection of transactions with clear -EROFS error

### 6. STABILITY INDICATORS

- The commit has been reviewed by 3 btrfs experts including the maintainer
- Reviewed-by: Boris Burkov <[email protected]>
- Reviewed-by: Johannes Thumshirn <[email protected]>
- Reviewed-by: David Sterba <[email protected]>
- Signed off by the maintainer

### 7. DEPENDENCY CHECK

- No dependencies on other commits
- The code uses existing infrastructure (fs_error, mount option flags)
- All the mount option flags (BTRFS_MOUNT_NOLOGREPLAY, etc.) exist in all stable kernels where btrfs rescue options exist
- The fix is self-contained

### CONCLUSION

**Recommendation: YES for backport**

This commit fixes a real bug that affects users mounting corrupted btrfs filesystems with rescue mount options - a legitimate and important data recovery scenario. The fix is:

1. **Small and surgical** - Only ~20 lines of simple, readable code
2. **Fixes a real bug** - Prevents warnings and potential issues during unmount with rescue options
3. **Low risk** - Uses existing fs_error mechanism, well-tested pattern
4. **Well reviewed** - Multiple reviews from btrfs maintainers
5. **No new features** - Just ensures correct rejection of transactions that can't succeed anyway
6. **Self-contained** - No dependencies on other patches

The fix ensures that when rescue mount options are used (which are inherently read-only and cannot be remounted read-write), new transactions are rejected cleanly at start rather than failing later with confusing errors and warnings.

**YES**

 fs/btrfs/disk-io.c | 13 +++++++++++++
 fs/btrfs/fs.h      |  8 ++++++++
 2 files changed, 21 insertions(+)
fs/btrfs/disk-io.c +13 -0
index 0aa7e5d1b05f6..c5279aed7503f 100644
@@ -3270,6 +3270,15 @@ int btrfs_check_features(struct btrfs_fs_info *fs_info, bool is_rw_mount)
 	return 0;
 }
 
+static bool fs_is_full_ro(const struct btrfs_fs_info *fs_info)
+{
+	if (!sb_rdonly(fs_info->sb))
+		return false;
+	if (unlikely(fs_info->mount_opt & BTRFS_MOUNT_FULL_RO_MASK))
+		return true;
+	return false;
+}
+
 int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices)
 {
 	u32 sectorsize;
@@ -3378,6 +3387,10 @@ int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_device
 	if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
 		WRITE_ONCE(fs_info->fs_error, -EUCLEAN);
 
+	/* If the fs has any rescue options, no transaction is allowed. */
+	if (fs_is_full_ro(fs_info))
+		WRITE_ONCE(fs_info->fs_error, -EROFS);
+
 	/* Set up fs_info before parsing mount options */
 	nodesize = btrfs_super_nodesize(disk_super);
 	sectorsize = btrfs_super_sectorsize(disk_super);
fs/btrfs/fs.h +8 -0
index 814bbc9417d2a..37aa8d141a83d 100644
@@ -250,6 +250,14 @@ enum {
 	BTRFS_MOUNT_REF_TRACKER			= (1ULL << 33),
 };
 
+/* These mount options require a full read-only fs, no new transaction is allowed. */
+#define BTRFS_MOUNT_FULL_RO_MASK		\
+	(BTRFS_MOUNT_NOLOGREPLAY |		\
+	 BTRFS_MOUNT_IGNOREBADROOTS |		\
+	 BTRFS_MOUNT_IGNOREDATACSUMS |		\
+	 BTRFS_MOUNT_IGNOREMETACSUMS |		\
+	 BTRFS_MOUNT_IGNORESUPERFLAGS)
+
 /*
  * Compat flags that we support.  If any incompat flags are set other than the
  * ones specified below then we will fail to mount
Signature · 1 line
2.51.0
author maintainer
#13 lore raw

PATCH 1/1 riscv: Use 64-bit variable for output in __get_user_asm

In reply to Sasha Levin

From: Nathan Chancellor <[email protected]>

[ Upstream commit bdce162f2e57a969803e5e9375999a3e0546905f ]

After commit f6bff7827a48 ("riscv: uaccess: use 'asm_goto_output' for get_user()"), which was the first commit that started using asm goto with outputs on RISC-V, builds of clang built with assertions enabled start crashing in certain files that use get_user() with:

clang: llvm/lib/CodeGen/SelectionDAG/SelectionDAGBuilder.cpp:12743: Register FollowCopyChain(MachineRegisterInfo &, Register): Assertion `MI->getOpcode() == TargetOpcode::COPY && "start of copy chain MUST be COPY"' failed.

Internally, LLVM generates an addiw instruction when the output of the inline asm (which may be any scalar type) needs to be sign extended for ABI reasons, such as a later function call, so that basic block does not have to do it.

Use a temporary 64-bit variable as the output of the inline assembly in __get_user_asm() and explicitly cast it to truncate it if necessary, avoiding the addiw that triggers the assertion.

---

LLM Generated explanations, may be completely bogus:

Looking at the full analysis based on what we have:

## Analysis Summary

### 1. COMMIT MESSAGE ANALYSIS

The commit message clearly states:
- **After commit f6bff7827a48** - Clearly identifies the regressing commit
- **Builds of clang built with assertions enabled start crashing** - This is a **build failure**, not just a warning
- Provides a link to the ClangBuiltLinux issue tracker
(https://github.com/ClangBuiltLinux/linux/issues/2092)
- The assertion failure message is in LLVM's code generation phase
- Author: Nathan Chancellor (ClangBuiltLinux maintainer, well-known kernel/LLVM expert)

### 2. CODE CHANGE ANALYSIS

The change is small and surgical:
- **Old code (asm_goto_output path):**

  ```c
  #define __get_user_asm(insn, x, ptr, label)  \
  asm_goto_output(                          \
  "1:\n"                                 \
  "  " insn " %0, %1\n"                  \
  _ASM_EXTABLE_UACCESS_ERR(1b, %l2, %0)  \
  : "=&r" (x)                            \
  : "m" (*(ptr)) : : label)
  ```

- **New code:**

  ```c
  #define __get_user_asm(insn, x, ptr, label)  \
  do {                                          \
  u64 __tmp;                                \
  asm_goto_output(                          \
  "1:\n"                                 \
  "  " insn " %0, %1\n"                  \
  _ASM_EXTABLE_UACCESS_ERR(1b, %l2, %0)  \
  : "=&r" (__tmp)                        \
  : "m" (*(ptr)) : : label);             \
  (x) = (__typeof__(x))__tmp;               \
  } while (0)
  ```

**Technical mechanism:**
- The fix uses a 64-bit temporary variable (u64 __tmp) as the output of the inline assembly
- Then explicitly casts it to the expected type of x
- This avoids LLVM generating an addiw instruction to sign-extend the output for ABI reasons
- The addiw was causing an assertion failure in LLVM's code generation because it wasn't recognized as a proper copy instruction

### 3. CLASSIFICATION

This is a **BUILD FIX** - one of the exception categories that is explicitly allowed in stable:
- Prevents compilation with Clang/LLVM on RISC-V
- Without this fix, users cannot build kernel for RISC-V when using Clang with assertions enabled
- The underlying bug likely causes incorrect code generation even when assertions are disabled

### 4. SCOPE AND RISK ASSESSMENT

**Lines changed:** ~10 lines, all in a single macro definition **Files touched:** 1 (arch/riscv/include/asm/uaccess.h) **Subsystem:** RISC-V uaccess (user-space access) **Risk:** Very low
- Uses a temporary variable to hold the assembly output then casts it
- This is a known safe pattern (used elsewhere in the kernel)
- Does not change any runtime behavior for GCC builds
- Only affects the CONFIG_CC_HAS_ASM_GOTO_OUTPUT code path (Clang/modern GCC)

### 5. USER IMPACT

- **Who is affected:** All RISC-V kernel developers and users building with Clang/LLVM
- **Severity:** Cannot build the kernel at all on RISC-V with Clang (when using assertion-enabled builds)
- RISC-V is an increasingly popular architecture
- Clang is a major compiler used by many distributions

### 6. STABILITY INDICATORS

- Written by Nathan Chancellor (ClangBuiltLinux project lead, kernel developer)
- Clear reference to upstream bug reports
- Follows a known workaround pattern

### 7. DEPENDENCY CHECK

**Critical:** This fix depends on commit **f6bff7827a48** ("riscv:
uaccess: use 'asm_goto_output' for get_user()"), which was introduced in **v6.16-rc1**.

The fix is only relevant for stable trees that contain v6.16+. For older stable trees (6.15.y and earlier), the problematic code doesn't exist, so this fix is not needed and wouldn't apply.

### Risk vs. Benefit Analysis

**Benefits:**
- Fixes a **complete build failure** on RISC-V with Clang
- Build fixes are explicitly allowed in stable rules
- Critical for RISC-V users who use Clang

**Risks:**
- Minimal - adds a temporary variable and explicit cast
- Does not change runtime behavior for correct code
- Pattern is well-understood and used elsewhere

### Concerns

1. **Dependency:** Only applicable to stable trees containing 6.16+ (which have commit f6bff7827a48)
2. **LLVM Bug:** This is a workaround for an LLVM bug (tracked at llvm- project#143795). The LLVM bug may eventually be fixed, but kernel builds need to work now.

### Conclusion

This commit is a **build fix** that solves a Clang compilation failure on RISC-V. Build fixes are explicitly allowed in stable kernel rules. The fix is:
- Small (10 lines)
- Surgical (single macro)
- Safe (temporary variable + cast pattern)
- Critical (prevents build failure)
- Well-documented (links to bug reports)
- Written by an expert (Nathan Chancellor)

The only consideration is that it should only be backported to stable trees that contain the parent commit f6bff7827a48 (v6.16+), otherwise the fix addresses code that doesn't exist.

**YES**

 arch/riscv/include/asm/uaccess.h | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)
arch/riscv/include/asm/uaccess.h +12 -2
index f5f4f7f85543f..1029c31026dcf 100644
@@ -97,13 +97,23 @@ static inline unsigned long __untagged_addr_remote(struct mm_struct *mm, unsigne
  */
 
 #ifdef CONFIG_CC_HAS_ASM_GOTO_OUTPUT
+/*
+ * Use a temporary variable for the output of the asm goto to avoid a
+ * triggering an LLVM assertion due to sign extending the output when
+ * it is used in later function calls:
+ * https://github.com/llvm/llvm-project/issues/143795
+ */
 #define __get_user_asm(insn, x, ptr, label)			\
+do {								\
+	u64 __tmp;						\
 	asm_goto_output(					\
 		"1:\n"						\
 		"	" insn " %0, %1\n"			\
 		_ASM_EXTABLE_UACCESS_ERR(1b, %l2, %0)		\
-		: "=&r" (x)					\
-		: "m" (*(ptr)) : : label)
+		: "=&r" (__tmp)					\
+		: "m" (*(ptr)) : : label);			\
+	(x) = (__typeof__(x))__tmp;				\
+} while (0)
 #else /* !CONFIG_CC_HAS_ASM_GOTO_OUTPUT */
 #define __get_user_asm(insn, x, ptr, label)			\
 do {								\
Signature · 1 line
2.51.0
author maintainer
#14 lore raw

PATCH 1/1 regmap: maple: free entry on mas_store_gfp() failure

In reply to Sasha Levin

From: Kaushlendra Kumar <[email protected]>

[ Upstream commit f3f380ce6b3d5c9805c7e0b3d5bc28d9ec41e2e8 ]

regcache_maple_write() allocates a new block ('entry') to merge adjacent ranges and then stores it with mas_store_gfp(). When mas_store_gfp() fails, the new 'entry' remains allocated and is never freed, leaking memory.

Free 'entry' on the failure path; on success continue freeing the replaced neighbor blocks ('lower', 'upper').

---

LLM Generated explanations, may be completely bogus:

### SUMMARY

**What the commit fixes:**
A memory leak in regcache_maple_write() where the allocated entry block is not freed when mas_store_gfp() fails. This is a clear resource leak bug.

**Why it matters to stable users:**
- Memory leaks affect system stability over time, especially on long- running embedded systems that commonly use regmap
- Under memory pressure scenarios, this leak compounds the problem
- regmap is core infrastructure used by many hardware drivers

**Stable kernel criteria assessment:**
1. ✅ **Obviously correct**: The fix follows standard kernel error handling patterns - allocate, try to use, free on failure
2. ✅ **Fixes a real bug**: Memory leak is a real, user-visible issue
3. ✅ **Important issue**: Memory leaks can lead to system instability/OOM
4. ✅ **Small and contained**: ~8 lines changed in a single file, single function
5. ✅ **No new features**: Pure bug fix
6. ✅ **Clean backport**: Self-contained fix with no dependencies

**Risk vs Benefit:**
- **Risk**: Very low - the change only affects the error path of mas_store_gfp() failure
- **Benefit**: Fixes a memory leak in widely-used infrastructure code
- The logic is straightforward and the fix is obviously correct

**Affected versions:**
- The regcache-maple.c file was introduced in v6.4
- Applicable to stable trees: 6.4.y, 6.6.y (LTS), and newer

**Concerns:**
- None - this is a textbook stable backport candidate

**YES**

 drivers/base/regmap/regcache-maple.c | 11 ++++++-----
 1 file changed, 6 insertions(+), 5 deletions(-)
drivers/base/regmap/regcache-maple.c +6 -5
index 2319c30283a6d..9cf0384ce7b95 100644
@@ -95,12 +95,13 @@ static int regcache_maple_write(struct regmap *map, unsigned int reg,
 
 	mas_unlock(&mas);
 
-	if (ret == 0) {
-		kfree(lower);
-		kfree(upper);
+	if (ret) {
+		kfree(entry);
+		return ret;
 	}
-	
-	return ret;
+	kfree(lower);
+	kfree(upper);
+	return 0;
 }
 
 static int regcache_maple_drop(struct regmap *map, unsigned int min,
Signature · 1 line
2.51.0
author maintainer
#15 lore raw

PATCH 1/1 wifi: mac80211: correctly check if CSA is active

In reply to Sasha Levin

From: Miri Korenblit <[email protected]>

[ Upstream commit db1d0b6ab11f612ea8a327663a578c8946efeee9 ]

We are not adding an interface if an existing one is doing CSA. But the check won't work for MLO station interfaces, since for those, vif->bss_conf is zeroed out.
Fix this by checking if any link of the vif has an active CSA.

---

LLM Generated explanations, may be completely bogus:

Now I have a complete picture. Let me analyze this commit comprehensively.

## Analysis

### 1. COMMIT MESSAGE ANALYSIS

**Subject**: "wifi: mac80211: correctly check if CSA is active"

The commit clearly describes a bug fix - the existing CSA (Channel Switch Announcement) check doesn't work properly for MLO (Multi-Link Operation) station interfaces. The message explains:
- The problem: "the check won't work for MLO station interfaces, since for those, vif->bss_conf is zeroed out"
- The fix: "checking if any link of the vif has an active CSA"

**Tags present**:
- Reviewed-by: Johannes Berg (mac80211 maintainer) - strong credibility signal
- Signed-off-by: Miri Korenblit (Intel wireless developer)
- Link to mailing list

No explicit Fixes: tag, but that's expected for commits we're reviewing.

### 2. CODE CHANGE ANALYSIS

**The Bug:**
The original code at line 379:

```c
if (nsdata->vif.bss_conf.csa_active)
    return -EBUSY;
```

This check is used in ieee80211_check_concurrent_iface() to prevent adding a new interface while an existing interface is performing a channel switch operation.

**Why it's broken for MLO:**
For MLO (Multi-Link Operation) station interfaces introduced in WiFi 7 (802.11be):
- vif->bss_conf is zeroed out by design
- Each link has its own BSS configuration stored in link_conf[link_id]
- The CSA state (csa_active) is per-link, not per-VIF
- Checking vif->bss_conf.csa_active will always return false for MLO interfaces, even if one of the links is actively switching channels

**The Fix:**

```c
struct ieee80211_link_data *link;
...
for_each_link_data(nsdata, link) {
    if (link->conf->csa_active)
        return -EBUSY;
}
```

This properly iterates through all valid links and checks if ANY link has an active CSA. The for_each_link_data macro:
- For non-MLO interfaces: iterates once with the single (deflink) link
- For MLO interfaces: iterates through all links with bits set in valid_links

**Technical mechanism**: The fix is correct because it unifies the check
- it works for both MLO and non-MLO interfaces while maintaining the same semantics.

### 3. CLASSIFICATION

This is clearly a **bug fix**, not a new feature:
- The concurrent interface protection during CSA was always intended to work
- It just doesn't work for the newer MLO interface type
- This is a correctness fix for existing functionality

### 4. SCOPE AND RISK ASSESSMENT

**Lines changed**: Small - adds ~6 lines, removes 2 lines (net +4) **Files touched**: 1 file (net/mac80211/iface.c) **Complexity**: Low - simple loop iteration replacing a single field access
**Subsystem**: mac80211 WiFi subsystem - widely used but WiFi-specific

**Risk level**: LOW
- The change is straightforward and the logic is sound
- The for_each_link_data macro is designed for exactly this use case
- Reviewed by Johannes Berg, the mac80211 maintainer
- Failure mode: If the fix doesn't work, we're no worse than before (still have the bug)

### 5. USER IMPACT

**Who is affected?**: Users with MLO-capable WiFi hardware (WiFi 7 / 802.11be devices)
**Severity**: Medium - Without this fix:
- A new interface could be incorrectly allowed to be added during an ongoing channel switch on an MLO interface
- This could cause interference, connectivity issues, or undefined behavior
- Channel switches are relatively rare events, so impact is somewhat limited

### 6. STABILITY INDICATORS

- **Reviewed-by**: Johannes Berg (mac80211 maintainer) - strong positive signal
- Author: Miri Korenblit from Intel - active wireless developer

### 7. DEPENDENCY CHECK

**Critical dependency**: This fix uses the for_each_link_data macro which was introduced in commit f61c7b3d442be ("wifi: mac80211: Add link iteration macro for link data") in kernel v6.16.

**Backport applicability**:
- **v6.16+**: Can be applied directly - has the macro
- **v6.1-v6.15**: Would require either:
1. Backporting the for_each_link_data macro first, OR
2. Writing an alternative fix using open-coded link iteration

MLO support was introduced in v6.1, so the bug exists in all kernels v6.1 through current that have MLO station interface support.

### Summary

| Criteria | Assessment |
|----------|------------|
| Obviously correct | YES - simple iteration fix |
| Fixes real bug | YES - incorrect CSA check for MLO |
| Important issue | MEDIUM - affects interface addition during channel
switch |
| Small and contained | YES - 4 net lines changed |
| No new features | YES - fixes existing feature |
| Applies cleanly | DEPENDS - needs v6.16+ for macro dependency |

### VERDICT

This is a legitimate bug fix for MLO WiFi support:
- It fixes a real, demonstrable bug where CSA detection fails for MLO interfaces
- The fix is small, surgical, and well-reviewed
- It doesn't introduce new features or change APIs
- It improves correctness of existing functionality

**However**, there are important caveats:
1. The fix has a dependency on the for_each_link_data macro (introduced in v6.16)
2. For stable trees before v6.16, a backport would need the macro too or use an alternative approach
3. MLO is relatively new technology (WiFi 7), so the affected user base is smaller

Given that this fix:
- Is obviously correct and addresses a real bug
- Was reviewed by the subsystem maintainer
- Has low risk of regression
- Affects real user scenarios (channel switching during interface operations)

The fix is appropriate for stable backporting to kernels that have both MLO support and the for_each_link_data macro (v6.16+). For older stable trees (v6.1-v6.15), a modified backport with the macro or open- coded iteration would be needed.

**YES**

 net/mac80211/iface.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)
net/mac80211/iface.c +6 -2
index 0ca55b9655a7f..72c129478da08 100644
@@ -350,6 +350,8 @@ static int ieee80211_check_concurrent_iface(struct ieee80211_sub_if_data *sdata,
 	/* we hold the RTNL here so can safely walk the list */
 	list_for_each_entry(nsdata, &local->interfaces, list) {
 		if (nsdata != sdata && ieee80211_sdata_running(nsdata)) {
+			struct ieee80211_link_data *link;
+
 			/*
 			 * Only OCB and monitor mode may coexist
 			 */
@@ -376,8 +378,10 @@ static int ieee80211_check_concurrent_iface(struct ieee80211_sub_if_data *sdata,
 			 * will not add another interface while any channel
 			 * switch is active.
 			 */
-			if (nsdata->vif.bss_conf.csa_active)
-				return -EBUSY;
+			for_each_link_data(nsdata, link) {
+				if (link->conf->csa_active)
+					return -EBUSY;
+			}
 
 			/*
 			 * The remaining checks are only performed for interfaces
Signature · 1 line
2.51.0
author maintainer
#16 lore raw

PATCH 1/1 wifi: cfg80211: Fix bitrate calculation overflow for HE rates

In reply to Sasha Levin

From: Veerendranath Jakkam <[email protected]>

[ Upstream commit a3034bf0746d88a00cceda9541534a5721445a24 ]

An integer overflow occurs in cfg80211_calculate_bitrate_he() when calculating bitrates for high throughput HE configurations. For example, with 160 MHz bandwidth, HE-MCS 13, HE-NSS 4, and HE-GI 0, the multiplication (result * rate->nss) overflows the 32-bit 'result' variable before division by 8, leading to significantly underestimated bitrate values.

The overflow occurs because the NSS multiplication operates on a 32-bit integer that cannot accommodate intermediate values exceeding 4,294,967,295. When overflow happens, the value wraps around, producing incorrect bitrates for high MCS and NSS combinations.

Fix this by utilizing the 64-bit 'tmp' variable for the NSS multiplication and subsequent divisions via do_div(). This approach preserves full precision throughout the entire calculation, with the final value assigned to 'result' only after completing all operations.

---

LLM Generated explanations, may be completely bogus:

I can see the buggy code is still present in this version (the fix hasn't been applied yet to this version of util.c). This is the code being patched. Let me double check the diff shows exactly what I expect:

Looking at the diff again:

```c
- result = tmp;

        /* and take NSS, DCM into account */
- result = (result * rate->nss) / 8;
+       tmp *= rate->nss;
+       do_div(tmp, 8);
        if (rate->he_dcm)
- result /= 2;
+               do_div(tmp, 2);
+
+       result = tmp;
```

The fix:
1. Removes result = tmp after the MCS division (keeps value in 64-bit tmp)
2. Multiplies NSS in 64-bit: tmp *= rate->nss instead of 32-bit result * rate->nss
3. Uses do_div(tmp, 8) instead of 32-bit division
4. Uses do_div(tmp, 2) for DCM instead of 32-bit division
5. Only assigns to 32-bit result at the end when the value is guaranteed to fit

This matches exactly the same fix pattern that was applied to cfg80211_calculate_bitrate_eht() in commit 18429c51c7ff6.

## Summary Analysis

### 1. COMMIT MESSAGE ANALYSIS
- **Subject**: Clearly indicates a bug fix for bitrate calculation overflow in HE rates
- **Body**: Provides detailed technical explanation of the overflow scenario (160 MHz, MCS 13, NSS 4, GI 0)
- **Root cause**: 32-bit integer overflow when multiplying result * rate->nss before division by 8
- **Fix approach**: Use 64-bit tmp variable throughout the calculation, assign to 32-bit result only at the end
- **Tags**: Has Signed-off-by from both Qualcomm developer and Johannes Berg (wireless maintainer)

### 2. CODE CHANGE ANALYSIS
- **Bug mechanism**: When result (a u32) is large (e.g., 0x44b85dd4 = 1,152,933,332), multiplying by NSS 4 produces 0x112e17750 (4,611,733,328) which overflows u32 max (0xFFFFFFFF = 4,294,967,295)
- **Result of bug**: The overflow wraps to 0x12e17750, producing a bitrate of ~3,959 (400 Mbps) instead of correct ~57,646 (5.76 Gbps)
- **Fix correctness**: The fix keeps all arithmetic in 64-bit until the final assignment, preventing overflow
- **DCM handling**: Also moved to 64-bit for consistency and safety

### 3. CLASSIFICATION
- **Type**: Bug fix (integer overflow causing incorrect bitrate reporting)
- **Security**: Not a security issue, but affects user-visible data correctness
- **Exception categories**: Not applicable - this is a straightforward bug fix

### 4. SCOPE AND RISK ASSESSMENT
- **Lines changed**: ~10 lines, very small and localized
- **Files touched**: 1 file (net/wireless/util.c)
- **Subsystem**: WiFi cfg80211, mature and stable
- **Risk**: Very LOW - the exact same fix pattern was already applied to the EHT version of this function and has been in stable since 6.1
- **Could break something**: Extremely unlikely - only changes intermediate arithmetic precision, final result is more accurate

### 5. USER IMPACT
- **Who is affected**: Users with WiFi 6 (802.11ax) devices using high bandwidth (160 MHz), high MCS (12/13), and multiple spatial streams (NSS 3-8)
- **Visibility**: Users see incorrect bitrate reporting in tools like iw, network managers, etc.
- **Severity**: Low-medium - cosmetic but confusing to users (reported speed is much lower than actual)
- **Real-world scenario**: Modern high-end WiFi 6 devices can absolutely hit these configurations

### 6. STABILITY INDICATORS
- **Testing**: Qualcomm developer tested on their hardware
- **Review**: Accepted by Johannes Berg (long-time wireless maintainer)
- **Precedent**: Same fix was applied to EHT function years ago (commit 18429c51c7ff6) and has proven stable

### 7. DEPENDENCY CHECK
- **Dependencies**: None - self-contained fix
- **Affected versions**: The HE MCS 12/13 support was added in v5.11, so stable trees 5.11+ are affected
- **Backport complexity**: Trivial - the affected code exists unchanged in all relevant stable trees

### Risk vs Benefit Trade-off
- **Benefit**: Corrects incorrect bitrate reporting for high-throughput WiFi 6 configurations
- **Risk**: Minimal - follows proven fix pattern already in production since kernel 6.1
- **Verdict**: HIGH benefit, VERY LOW risk

**YES**

 net/wireless/util.c | 8 +++++---
 1 file changed, 5 insertions(+), 3 deletions(-)
net/wireless/util.c +5 -3
index 4eb028ad16836..81d6d27d273cc 100644
@@ -1561,12 +1561,14 @@ static u32 cfg80211_calculate_bitrate_he(struct rate_info *rate)
 	tmp = result;
 	tmp *= SCALE;
 	do_div(tmp, mcs_divisors[rate->mcs]);
-	result = tmp;
 
 	/* and take NSS, DCM into account */
-	result = (result * rate->nss) / 8;
+	tmp *= rate->nss;
+	do_div(tmp, 8);
 	if (rate->he_dcm)
-		result /= 2;
+		do_div(tmp, 2);
+
+	result = tmp;
 
 	return result / 10000;
 }
Signature · 1 line
2.51.0
author maintainer
#17 lore raw

PATCH 1/1 tracing: Avoid possible signed 64-bit truncation

In reply to Sasha Levin

From: Ian Rogers <[email protected]>

[ Upstream commit 00f13e28a9c3acd40f0551cde7e9d2d1a41585bf ]

64-bit truncation to 32-bit can result in the sign of the truncated value changing. The cmp_mod_entry is used in bsearch and so the truncation could result in an invalid search order. This would only happen were the addresses more than 2GB apart and so unlikely, but let's fix the potentially broken compare anyway.

---

LLM Generated explanations, may be completely bogus:

The original buggy code was introduced in v6.15 and later. It's only present in 6.15+ kernels.

### 8. SUMMARY OF ANALYSIS

**The Bug:**
- The cmp_mod_entry() function uses subtraction of two unsigned long values and returns the result as int
- On 64-bit systems, if addresses differ by more than 2^31 (~2GB), the truncation from 64-bit to 32-bit can flip the sign
- This would cause bsearch() to make wrong decisions about search direction
- Result: potentially incorrect module address lookups in trace data

**The Fix:**
- Replaces arithmetic subtraction with simple comparisons
- Returns -1, 0, or 1 directly based on comparisons
- No overflow or truncation possible with the new code
- Logic is more readable and provably correct

**Stable Criteria Evaluation:**
1. ✅ **Obviously correct and tested**: Simple logic, reviewed by maintainers
2. ✅ **Fixes a real bug**: Yes, a potential comparator correctness bug
3. ⚠️ **Important issue**: Moderate - unlikely to trigger (requires >2GB address separation) but could cause incorrect trace output
4. ✅ **Small and contained**: Only changes one function body (~6 lines)
5. ✅ **No new features**: Pure bug fix
6. ✅ **Applies cleanly**: Should apply to 6.15+ kernels where this code exists

**Risk Assessment:**
- Very low risk - the change is small and the new logic is simpler
- The original code has a provable bug (integer overflow on truncation)
- The new code has no such issues

**Concerns:**
- The code only exists in 6.15+ kernels (introduced March 2025)
- The bug is "unlikely" per the author (requires addresses >2GB apart)
- No known real-world reports of this actually causing issues

### DECISION

This is a valid bug fix that:
- Fixes a real (though unlikely to trigger) bug in the comparator function
- Is very small and self-contained
- Has been reviewed and acked by the tracing maintainers
- Has near-zero regression risk
- Applies to 6.15+ kernels only

The fix is surgical, obviously correct, and addresses a potential correctness issue. While the bug is unlikely to trigger in practice (addresses must be >2GB apart), it could cause silent data corruption in trace output when it does trigger. The fix is trivial and risk-free.

**YES**

 kernel/trace/trace.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)
kernel/trace/trace.c +4 -4
index 142e3b737f0bc..907923d5f8bbb 100644
@@ -6061,10 +6061,10 @@ static int cmp_mod_entry(const void *key, const void *pivot)
 	unsigned long addr = (unsigned long)key;
 	const struct trace_mod_entry *ent = pivot;
 
-	if (addr >= ent[0].mod_addr && addr < ent[1].mod_addr)
-		return 0;
-	else
-		return addr - ent->mod_addr;
+	if (addr < ent[0].mod_addr)
+		return -1;
+
+	return addr >= ent[1].mod_addr;
 }
 
 /**
Signature · 1 line
2.51.0
maintainer
#18 lore raw

Re: [PATCH AUTOSEL 6.18] tracing: Avoid possible signed 64-bit truncation

Quoted 4 lines · On Wed, 28 Jan 2026 17:33:16 -0500 Sasha Levin <[email protected]> wrote:

LLM Generated explanations, may be completely bogus:

The original buggy code was introduced in v6.15 and later. It's only present in 6.15+ kernels.

Interesting self discussion from the LLM.

Quoted 18 lines

### 8. SUMMARY OF ANALYSIS

**The Bug:**
- The cmp_mod_entry() function uses subtraction of two unsigned long values and returns the result as int
- On 64-bit systems, if addresses differ by more than 2^31 (~2GB), the truncation from 64-bit to 32-bit can flip the sign
- This would cause bsearch() to make wrong decisions about search direction
- Result: potentially incorrect module address lookups in trace data

**The Fix:**
- Replaces arithmetic subtraction with simple comparisons
- Returns -1, 0, or 1 directly based on comparisons
- No overflow or truncation possible with the new code
- Logic is more readable and provably correct

Quoted 6 lines

**Stable Criteria Evaluation:**
1. ✅ **Obviously correct and tested**: Simple logic, reviewed by maintainers
2. ✅ **Fixes a real bug**: Yes, a potential comparator correctness bug
3. ⚠️ **Important issue**: Moderate - unlikely to trigger (requires >2GB address separation) but could cause incorrect trace output

I purposely didn't add Cc: stable because there's basically no chance of two modules being more than 2GB apart.

Quoted 25 lines

4. ✅ **Small and contained**: Only changes one function body (~6 lines)
5. ✅ **No new features**: Pure bug fix
6. ✅ **Applies cleanly**: Should apply to 6.15+ kernels where this code exists

**Risk Assessment:**
- Very low risk - the change is small and the new logic is simpler
- The original code has a provable bug (integer overflow on truncation)
- The new code has no such issues

**Concerns:**
- The code only exists in 6.15+ kernels (introduced March 2025)
- The bug is "unlikely" per the author (requires addresses >2GB apart)
- No known real-world reports of this actually causing issues

### DECISION

This is a valid bug fix that:
- Fixes a real (though unlikely to trigger) bug in the comparator function
- Is very small and self-contained
- Has been reviewed and acked by the tracing maintainers
- Has near-zero regression risk
- Applies to 6.15+ kernels only

Quoted 6 lines

The fix is surgical, obviously correct, and addresses a potential correctness issue. While the bug is unlikely to trigger in practice (addresses must be >2GB apart), it could cause silent data corruption in trace output when it does trigger. The fix is trivial and risk-free.

**YES**

But I see the bot considered the same thing, but because of the risk factor it decided to take it.

I have no issue with backporting it (I did label it a "fix"). I was actually wondering if the bot would notice likeliness of it not happening. It did, but decided to take it for "correctness" reasons vs risk factor.

Nice,

-- Steve