[RFC] mtd: spi-nor: Use-after-free in MTD layer when unbinding SPI-NOR with open file handles
Havivi, Itamar
ihavivi at amazon.com
Sun Jan 18 06:14:25 PST 2026
Hi,
We're encountering kernel crashes when unbinding SPI-NOR flash devices that
have open /dev/mtdX file handles. The root cause appears to be that the
mtd_info struct (embedded in spi_nor struct) is freed via devres_release_all()
during unbind, while userspace still holds references.
Kernel versions: v5.10 / v6.12
Config: CONFIG_MTD_PARTITIONED_MASTER=y
Reproduction:
1. Open /dev/mtd0 (SPI-NOR master device)
2. Unbind the SPI device via sysfs
3. Access/close the open file handle -> crash (sometimes not immediately)
The issue occurs because:
- spi_nor structs, and the master mtd_info, are allocated with devm_kzalloc()
- __device_release_driver() calls spi_nor_remove() then devres_release_all()
- MTD device memory is freed regardless of outstanding references
- Subsequent access through open file handles hits freed memory
The recent MTD patches that added kref in mtd_info did not fix this since
the spi-nor and master MTD memory is already freed when the last reference
is dropped, and even the put_mtd_device tries to access them.
This was found on master MTD device, but affecting MTD partitions as well,
since they also access their master device and spi-nor when a reference is put.
Proposed solution:
- Allocate spi_nor with kzalloc() instead of devm_kzalloc()
- Add kref to spi_nor, managed via spi_nor_get/put_device()
- Add "removed" flag to prevent operations after unbind
- Free spi_nor only when both device removal completes and all references drop
This would allow graceful failure for operations on open handles rather than
use-after-free crashes, and closing the files successfully.
Before I prepare patches, I wanted to check:
1. Is this approach acceptable, or is there a better way to handle this?
2. Are there existing mechanisms in MTD/SPI-NOR I should use?
I will provide a patch series if this direction is acceptable.
Thanks,
Itamar
More information about the linux-mtd
mailing list