Skip to content

mtd: spinand: free flash_info with the device, and fix the remove path - #344

Merged
openipc-ai merged 2 commits into
novatek-nt9856xfrom
nvt-spinand-devm-flash-info
Nov 29, 2026
Merged

openipc-ai merged 2 commits into
novatek-nt9856xfrom
nvt-spinand-devm-flash-info

Conversation

@openipc-ai

@openipc-ai openipc-ai commented Nov 29, 2026 •

Copy link
Copy Markdown

Follow-up to #343. Two commits, both in spinand.c and its SPI020 copy spi020_nand.c.

1. mtd: spinand: allocate flash_info with the device. This is the leak Qodo found on #343. info->flash_info was kmalloc()'d in the probe and never freed on any path, not in the error labels and not in remove. It is now devm_kzalloc()'d with the device, like info itself. The allocation is also zeroed now. The only field the driver read without writing first is num_blocks: it sizes the static_info proc dump, which could therefore run past erase_count[4096], and now lists no blocks.

2. mtd: spinand: take back the driver data the probe stored. The probe stores info as driver data, but remove, suspend and resume read it back as an mtd_info and take info from mtd->priv. Nothing sets mtd->priv (the probe sets chip->priv), so info is NULL there. Unbinding the device dereferences NULL in free_irq(info->irq, info). One step later, remove would kfree(mtd), an interior pointer of the devm allocation: the same defect #343 removed from the probe's error path. The driver data is now read back as info, mtd comes from nand_to_mtd(), and the kfree(mtd) is gone. Suspend and resume get the same lookup. They are built only with CONFIG_PM, which the NT9856x configs leave off.

Tested

The tests ran in qemu-bench, -M nt98566 with a blank 128 MiB SPI NAND, on kernels built from nt98566.nand.config (the nt98566_ultimate config): one from novatek-nt9856x at 5f7f91b (base) and one from this branch (fix). The guest is a busybox initramfs.

Unbind and rebind, listed flash (default W25N01GV, ef aa 21):

base: T-UNBIND-START
      Unable to handle kernel NULL pointer dereference at virtual address 00000524
      PC is at spinand_remove+0x20/0x40
      Kernel panic - not syncing: Fatal exception
fix:  T-UNBIND-RC: 0
      T-MTD-LINES-AFTER-UNBIND: 1        (header only: mtd0 gone)
      T-BIND-RC: 0
      T-MTD-REBOUND: mtd0: 08000000 00020000 "spi_nand.0"

The rebind also warns that nvt_info/nvt_flash is already registered and logs "create nand static proc failed". Remove never takes the proc entries down. That is unchanged here.

Leak, unlisted flash (flash-jedec=0x123400, so ID 12 34). SUnreclaim from /proc/meminfo around 2000 bind attempts, each one a failed probe ("flash ID 0x12 0x34 is not in the ID table"), with caches dropped before each reading:

before after growth per probe
base 2268 kB 2768 kB 500 kB ~256 B
fix 2252 kB 2504 kB 252 kB ~126 B

The ~124 B per probe this removes is struct nvt_nand_flash (84 bytes, so a kmalloc-128 object).

kmemleak could not be used for this: it turns itself off at boot on this platform ("Cannot insert 0x87ff6000 into the object search tree (overlaps existing)").

The SPI020 driver (NA51068 only) was compile-tested.

Not changed

A second leak remains. The ~126 B per failed probe still left is the clock handle. drv_nand_reset() calls clk_get(), clk_prepare() and clk_enable() on every probe and every resume, and nothing calls clk_put() or disables the clock again. Fixing it means turning the NAND controller clock off on a failed probe and on remove, which is a behaviour change of its own, so it belongs in a separate PR.

Digital twin of an nt98566_ultimate camera. The tests above use a test initramfs. This one runs the published firmware: qemu-bench -M nt98566,sensor=sc401ai with a 128 MiB NAND laid out as the install writes it. That is the release's u-boot-nt98566-nand.bin at 0 and rootfs.ubi.nt98566 from openipc.nt98566-nand-ultimate.tgz (2026-11-28) at 0x300000, the start of UBI. The camera's U-Boot ran its own bootflash steps with one change: after ubi part ubi; ubifsmount ubi0:rootfs, the kernel came from tftpboot instead of ubifsload /boot/uImage. The bootargs are the image's own. The kernels are uImages built from nt98566.nand.config with the release's version string, so the image's modules load. Both base and fix:

Kernel command line: mem=32M console=ttyS0,115200 panic=20 init=/init root=ubi0:rootfs rootfstype=ubifs ubi.mtd=2,2048 mtdparts=spi_nand.0:2816k(boot),256k(env),-(ubi)
nand: Winbond W25N01GV 1G 3.3V
spi_nand f0400000.nand: 4-bit mode @ 40000000 Hz
Creating 3 MTD partitions on "spi_nand.0":
ubi0: attached mtd2 (name "ubi", size 125 MiB)
VFS: Mounted root (ubifs filesystem) readonly on device 0:13.
Starting majestic: OK
openipc-nt98566 login:

From the host, majestic answers /setup.html with 200 and / with 302, which is right for an unclaimed camera. The two consoles from Starting kernel on are 187 lines each and identical, apart from the order of one ubi_bgt0d line, the fresh rootfs_data UUID and the time ntpd set. Neither has a warning or an oops.

The remove fix cannot be exercised on the twin: unbinding the flash under a mounted root is not something a camera does. On a camera, commit 1 changes two things: who frees the allocation, and that it starts zeroed. The only visible effect is num_blocks in static_info, as above. Commit 2 changes only remove, suspend and resume, which a booting camera never runs. Not run on physical hardware.

Both SPI NAND probes allocate info->flash_info with kmalloc() and no
path frees it: not the probe's error labels and not remove. Since #343
an ID that is not in the table fails the probe, so every such probe
leaks the allocation, and so did every earlier failure (a READID
timeout, a failed nand_scan_with_ids()).

Allocate it with devm_kzalloc() on the platform device, like info
itself, so devres releases it on a failed probe and on unbind.

The allocation is now zeroed. Every field the probe and the I/O path
read is written first except num_blocks, which nothing sets:
drv_nand_identify() copies it into total_block_cnt, the number of
erase_count[4096] entries the static_info proc file prints. That count
was whatever kmalloc() returned, and could walk the file past the end
of the array. It is now 0, so the file lists no blocks.
The probe stores info with platform_set_drvdata(), but remove, suspend
and resume read the driver data back as a struct mtd_info and take info
from mtd->priv. The pointer is the same address, since nand_chip is the
first member of info and mtd the first member of nand_chip. But nothing
sets mtd->priv (the probe sets chip->priv), so info comes back NULL.
Unbinding the device, which sysfs allows even for this built-in driver,
dereferences NULL in free_irq(info->irq, info). Past that, remove would
kfree(mtd), an interior pointer of the devm_kzalloc()'d info: the same
slab corruption #343 removed from the probe's error path.

Read the driver data as info, get mtd with nand_to_mtd(), and drop the
kfree(mtd) from remove. devres frees info. suspend and resume get the
same lookup; they are built only with CONFIG_PM, which the NT9856x
configs leave off.

Not changed: remove leaves /proc/nvt_info/nvt_flash in place, so a
second bind warns that the proc entry is already registered, logs
"create nand static proc failed", and keeps the old entries.
@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 29, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

Fix SPI NAND flash metadata ownership and device removal

🐞 Bug fix 🕐 10-20 Minutes

Grey Divider

AI Description

• Device-managed flash metadata prevents leaks after failed probes and device removal.
• Remove and power-management callbacks now retrieve the driver state stored by probe.
• Removal no longer frees an MTD pointer embedded in device-managed memory.
Merge Risk 🟡 Medium

Blast radius 🟢 Low 💥 1 capability

  • 1 affected end-to-end capability after fault-specific containment; implementation boundaries do not widen its functional scope.
  • Both changed files implement the same bounded SPI NAND platform-driver integration: probe establishes one drv_nand_dev_info containing the nand_chip and embedded MTD, while remove and PM callbacks consume that same device state.
  • The changes do not establish independent user-visible functional domains; the second file is a parallel driver variant of the same lifecycle behavior.
Behavioral complexity 🟡 Medium 🧩 Coordinated invariants

  • Before, platform driver data was consumed inconsistently across lifecycle callbacks and flash metadata used manual allocation/freeing.
  • After, platform driver data is consistently treated as drv_nand_dev_info, MTD is derived from the embedded nand_chip, and flash metadata is device-managed in both variants.
  • New correctness condition: probe, remove, suspend, resume, and devm cleanup must agree on one drv_nand_dev_info lifetime and must not manually free embedded or device-managed objects.
  • The same invariant is duplicated across two driver implementations; no new algorithm or concurrency protocol is introduced.
Potential damage 🟡 Medium 🩹 Temporary loss

  • If the changed lifecycle invariant regresses, device detach or suspend/resume may fail, crash, or leave the SPI NAND device unavailable.
  • The affected end-to-end capability is the driver lifecycle itself; no persistent flash-data corruption or unrelated consumer effect is supported.
  • Recovery is generally a device rebind or reboot after code correction, while the source does not establish an automatic repair worker.
  • The code change does not itself alter NAND contents or external records.
  • A lifecycle failure may require reloading or rebooting the device; device-managed allocations are reclaimed when the device is released, but no automatic recovery path is shown.
Assessed commit 96d67c0
Diagram

graph TD
  Device["Platform device"] --> Probe["SPI NAND probe"] --> Info["Driver state"] --> Flash["Flash metadata"]
  Device --> Remove["SPI NAND remove"] --> Info --> MTD["MTD device"]
  Device --> PM["PM callbacks"] --> Info
Loading
High-Level Assessment

Device-managed flash metadata matches the existing driver-state ownership and covers both failed probes and unbind. Explicitly freeing the allocation on every exit path would add cleanup branches without improving the ownership model. Reading back the exact pointer stored by probe is the direct fix for the callbacks.

Files changed (2) +12 / -16

Bug fix (2) +12 / -16
spi020_nand.cFix SPI020 NAND metadata lifetime and callbacks +6/-8

Fix SPI020 NAND metadata lifetime and callbacks

• Allocates flash metadata with devm_kzalloc so it is zeroed and released with the device. Remove, suspend, and resume retrieve driver state directly; remove derives the MTD pointer from its NAND chip instead of freeing the embedded pointer.

drivers/mtd/spiflash/spi020_nand.c

spinand.cFix SPI NAND metadata lifetime and callbacks +6/-8

Fix SPI NAND metadata lifetime and callbacks

• Makes flash metadata device-managed and zero-initialized, preventing its leak on failed probes and unbind. Corrects driver-data lookup in remove and power-management callbacks, and removes the invalid free of the embedded MTD pointer.

drivers/mtd/spiflash/spinand.c

@andrein andrein left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I read both commits against the code and the claims hold. nand_chip is the first member of drv_nand_dev_info and mtd is the first member of nand_chip, so the old cast found the right address, and mtd->priv is never set, so info was NULL. Nothing else in the probe or the I/O path depends on what kmalloc() left in flash_info. Only num_blocks did. devres frees info and flash_info after remove has freed the IRQ, so nothing touches them after they are gone.

Tested on a Reolink E340 (NT98566, FORESEE F35SQA512M), with this branch on top of 5f7f91b and started by kexec. The flash is found, ECC strength and bitflip threshold read 1, UBI attaches, both UBIFS volumes mount, and both video streams run (HEVC 2592x1944 at 30 fps, H.264 640x480). static_info prints a single empty line, as the commit message says. No oops or warning in the log.

A possible follow-up, outside this PR: drv_nand_read_id() already fills in device_size (in MiB) and block_size from the ID table, so setting num_blocks = (device_size << 20) / block_size there would make static_info list the real blocks. The largest entry in the table comes to 4096 blocks, which still fits erase_count[4096].

@openipc-ai
openipc-ai merged commit 75ff4dd into novatek-nt9856x Nov 29, 2026
@openipc-ai
openipc-ai deleted the nvt-spinand-devm-flash-info branch November 29, 2026 10:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants