Claude review: mm/zone_device: Do not touch device folio after calling ->folio_free()

Claude Code Review Bot
2026-04-11T23:15:49Z

Patch Review

**The bug:**

In `free_zone_device_folio()`, a local variable `pgmap` is saved from `folio->pgmap` at function entry (line 418 of the current tree):

```c
struct dev_pagemap *pgmap = folio->pgmap;
```

This local is used correctly throughout the function — except at line 457, where the code dereferences `folio->pgmap` again instead of using the local:

```c
pgmap->ops->folio_free(folio);
- percpu_ref_put_many(&folio->pgmap->ref, nr);
+ percpu_ref_put_many(&pgmap->ref, nr);
```

After `folio_free()` returns, the driver may have already reallocated the folio's backing memory with a different order, meaning `folio->pgmap` can contain garbage. The stack trace confirms this — RAX holds `0x0900000000000000`, a non-canonical address, which is what you'd expect from reading a corrupted `pgmap` pointer out of a recycled folio.

**The fix:**

The one-line change replaces `folio->pgmap->ref` with `pgmap->ref`, using the local variable that was already captured before the folio was freed. This is the obviously correct fix.

**Additional observations:**

1. **Correctness**: The fix is correct. `pgmap` is captured before any mutation of the folio, and `percpu_ref_put_many` on `pgmap->ref` is the right thing to do after the folio has been freed.

2. **Fixes tag**: The `Fixes:` tag references `d245f9b4ab80 ("mm/zone_device: support large zone device private folios")` which is the commit that introduced the `nr` variable and the `percpu_ref_put_many` call (replacing an earlier `percpu_ref_put`). This seems like a reasonable attribution — the use of `folio->pgmap` instead of the local `pgmap` was likely introduced or preserved in that commit.

3. **Scope check**: Looking at the other cases in the same `switch` statement, `MEMORY_DEVICE_PCI_P2PDMA` (line 472-476) also calls `pgmap->ops->folio_free(folio)` but does not call `percpu_ref_put_many` afterward, so it doesn't have this bug. The `MEMORY_DEVICE_GENERIC` and `MEMORY_DEVICE_FS_DAX` cases don't call `folio_free` at all.

4. **Cc list**: The patch is appropriately CC'd to mm maintainers and relevant mailing lists.

**Reviewed-by worthy**: Yes, this is a clean, minimal, correct fix for a real use-after-free. No concerns.

---
Generated by Claude Code Patch Reviewer