Skip to content

mtd: spinand: end the ID tables with a NULL entry - #343

Merged
openipc-ai merged 1 commit into
OpenIPC:novatek-nt9856xfrom
andrein:nvt-spinand-id-sentinel
Nov 29, 2026
Merged

openipc-ai merged 1 commit into
OpenIPC:novatek-nt9856xfrom
andrein:nvt-spinand-id-sentinel

Conversation

@andrein

@andrein andrein commented Nov 29, 2026

Copy link
Copy Markdown

nand_scan_with_ids() walks the ID table until an entry with a NULL name. Neither spinand_flash_ids (NT9856x) nor the SPI020 copy had one, so for a chip that matches no entry nand_detect() reads past the end of the table. This adds the terminator to both tables.

Following the review advice on #339, drv_nand_read_id() in both drivers now stops at the entry with a NULL name. Bounding it with ARRAY_SIZE() would count the terminator, and a flash answering 00 00 (absent or not responding) would match it and divide by a zero page size. An ID that matches no entry now fails the probe with -ENODEV and the message "flash ID 0x.. 0x.. is not in the ID table". Before, the driver carried on with geometry it never set.

The probe's error path no longer calls kfree() on mtd. That pointer is inside the devm_kzalloc()'d info, and freeing it corrupted the slab: with an unlisted flash the kernel later oopsed in clk_debug_init().

Tested:

  • Reolink E340 (NT98566, FORESEE F35SQA512M), kexec: the flash is found and named, 10 partitions, ECC strength and bitflip threshold 1, UBI attaches, both UBIFS volumes mount, both RTSP streams deliver.
  • qemu-bench nt98566 machine with the camera's flash image: ID cd 70 probes and mounts root; IDs 12 34, 00 00 and ff ff fail the probe cleanly and the boot continues until it cannot mount root. Without this change those IDs end in the clk_debug_init() oops.
  • The SPI020 driver (NA51068 only) was compile-tested.

Depends only on #339, which is merged.

🤖 Generated with Claude Code

nand_scan_with_ids() walks the table it is given until it reaches an
entry whose name is NULL. spinand_flash_ids has no such entry, in this
driver or in the SPI020 driver, so for a chip that matches no entry
nand_detect() runs past the end of the table and reads the memory after
it as more entries. Add the terminator to both tables.

drv_nand_read_id() bounds its own walk with ARRAY_SIZE(), which now
counts the terminator. Its mfr_id and dev_id are 0, so a flash that
answers 00 00, because it is absent or not responding, would match it,
and spinand.c would then set page_size to 0 and divide by it. The review
of OpenIPC#339 pointed this out and suggested stopping the loop at the entry
with a NULL name, which both copies now do.

An ID that matched no entry still made drv_nand_read_id() return
success. spinand.c then went on with page and block sizes it never set,
as flash_info comes from kmalloc(). Print the ID and return -ENODEV
instead, so the probe ends in drv_nand_identify() with the existing
"failed to identify flash" message.

That error path freed mtd, which points into info, and info comes from
devm_kzalloc(). The kfree() corrupted the slab, and later in the boot
the kernel oopsed in clk_debug_init(). Drop it in both drivers; devres
frees info when the probe fails.

Tested on a Reolink E340 (NT98566, FORESEE F35SQA512M) started by
kexec: the flash is found and named, there are 10 partitions, ECC
strength and bitflip threshold read 1, UBI attaches and both UBIFS
volumes mount. Tested in the nt98566 machine of OpenIPC's qemu-bench
with the same camera's flash image: the FORESEE ID cd 70 probes and the
root filesystem mounts; for the IDs 12 34, 00 00 and ff ff the probe
fails with "flash ID 0x.. 0x.. is not in the ID table" and the boot
goes on until it cannot mount root, as expected. Without this change
those three IDs end in the clk_debug_init() oops. The SPI020 driver is
built only for NA51068; it was compile-tested.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@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

Prevent out-of-bounds SPI NAND ID scans and unsafe probe cleanup

🐞 Bug fix 🕐 10-20 Minutes

Grey Divider

AI Description

• Terminate both SPI NAND ID tables so NAND detection stops at their boundaries.
• Reject unknown IDs before using unset flash geometry, and avoid freeing embedded MTD memory.
• Validated NT98566 hardware and emulated IDs; compile-tested the SPI020 driver.
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 implementations read the flash ID, select geometry from the shared local ID-table concept, and feed identification into SPI NAND probe; they are alternate implementations of the same bounded integration rather than separate downstream behaviors.
Sources

drivers/mtd/spiflash/spi020_nand.c[386-386]

	{ NULL }

drivers/mtd/spiflash/spi020_nand.c[677-694]

		for (i = 0; spinand_flash_ids[i].name; i++) {
			if ((card_id[0] == spinand_flash_ids[i].mfr_id) && \
			(card_id[1] == spinand_flash_ids[i].dev_id)) {
				id_count = spinand_flash_ids[i].id_len;
				memset(card_id + id_count, 0, 4 - id_count);
				break;
			}
		}
		if (spinand_flash_ids[i].name) {
			*id = card_id[0] | (card_id[1] << 8) |
				(card_id[2] << 16) | (card_id[3] << 24);
			ret = E_OK;
		} else {
			dev_err(&info->pdev->dev,
				"flash ID 0x%02x 0x%02x is not in the ID table\n",
				card_id[0], card_id[1]);
			ret = -ENODEV;
		}

drivers/mtd/spiflash/spinand.c[438-438]

	{ NULL }

drivers/mtd/spiflash/spinand.c[843-866]

		for (i = 0; spinand_flash_ids[i].name; i++) {
			if ((card_id[0] == spinand_flash_ids[i].mfr_id) && \
			(card_id[1] == spinand_flash_ids[i].dev_id)) {
				id_count = spinand_flash_ids[i].id_len;
				memset(card_id + id_count, 0, 4 - id_count);
				info->flash_info->page_size = spinand_flash_ids[i].pagesize;
				info->flash_info->device_size = spinand_flash_ids[i].chipsize;
				info->flash_info->block_size = spinand_flash_ids[i].erasesize;
				info->flash_info->page_per_block = \
					(spinand_flash_ids[i].erasesize / spinand_flash_ids[i].pagesize);
                info->nand_chip.ecc.strength = spinand_flash_ids[i].ecc.strength_ds;
				break;
			}
		}
		if (spinand_flash_ids[i].name) {
			*id = card_id[0] | (card_id[1] << 8) |
				(card_id[2] << 16) | (card_id[3] << 24);
			ret = E_OK;
		} else {
			dev_err(&info->pdev->dev,
				"flash ID 0x%02x 0x%02x is not in the ID table\n",
				card_id[0], card_id[1]);
			ret = -ENODEV;
		}
Behavioral complexity 🟡 Medium 🧩 Interacting branches

  • Before, the bounded array scan could run through the physical array end and unknown IDs were accepted.
  • After, a sentinel terminates the scan and a known-versus-unknown branch controls success.
  • The new correctness condition is that every table has a valid terminator and only matched IDs proceed to registration; the two outcomes do not introduce a new cross-component protocol.
Sources

drivers/mtd/spiflash/spi020_nand.c[386-386]

	{ NULL }

drivers/mtd/spiflash/spi020_nand.c[677-694]

		for (i = 0; spinand_flash_ids[i].name; i++) {
			if ((card_id[0] == spinand_flash_ids[i].mfr_id) && \
			(card_id[1] == spinand_flash_ids[i].dev_id)) {
				id_count = spinand_flash_ids[i].id_len;
				memset(card_id + id_count, 0, 4 - id_count);
				break;
			}
		}
		if (spinand_flash_ids[i].name) {
			*id = card_id[0] | (card_id[1] << 8) |
				(card_id[2] << 16) | (card_id[3] << 24);
			ret = E_OK;
		} else {
			dev_err(&info->pdev->dev,
				"flash ID 0x%02x 0x%02x is not in the ID table\n",
				card_id[0], card_id[1]);
			ret = -ENODEV;
		}

drivers/mtd/spiflash/spinand.c[438-438]

	{ NULL }

drivers/mtd/spiflash/spinand.c[843-866]

		for (i = 0; spinand_flash_ids[i].name; i++) {
			if ((card_id[0] == spinand_flash_ids[i].mfr_id) && \
			(card_id[1] == spinand_flash_ids[i].dev_id)) {
				id_count = spinand_flash_ids[i].id_len;
				memset(card_id + id_count, 0, 4 - id_count);
				info->flash_info->page_size = spinand_flash_ids[i].pagesize;
				info->flash_info->device_size = spinand_flash_ids[i].chipsize;
				info->flash_info->block_size = spinand_flash_ids[i].erasesize;
				info->flash_info->page_per_block = \
					(spinand_flash_ids[i].erasesize / spinand_flash_ids[i].pagesize);
                info->nand_chip.ecc.strength = spinand_flash_ids[i].ecc.strength_ds;
				break;
			}
		}
		if (spinand_flash_ids[i].name) {
			*id = card_id[0] | (card_id[1] << 8) |
				(card_id[2] << 16) | (card_id[3] << 24);
			ret = E_OK;
		} else {
			dev_err(&info->pdev->dev,
				"flash ID 0x%02x 0x%02x is not in the ID table\n",
				card_id[0], card_id[1]);
			ret = -ENODEV;
		}
Potential damage 🟡 Medium 🩹 Temporary loss

  • For an unsupported or unexpectedly formatted device ID, probe can fail instead of exposing the NAND device.
  • Known table entries retain the existing identification path.
  • This is a direct assessment of the changed branch, not a claimed defect.
  • Rebuilding with the prior behavior or adding the device entry restores probe capability; no persistent NAND state is changed by identification failure.
Sources

drivers/mtd/spiflash/spi020_nand.c[677-694]

		for (i = 0; spinand_flash_ids[i].name; i++) {
			if ((card_id[0] == spinand_flash_ids[i].mfr_id) && \
			(card_id[1] == spinand_flash_ids[i].dev_id)) {
				id_count = spinand_flash_ids[i].id_len;
				memset(card_id + id_count, 0, 4 - id_count);
				break;
			}
		}
		if (spinand_flash_ids[i].name) {
			*id = card_id[0] | (card_id[1] << 8) |
				(card_id[2] << 16) | (card_id[3] << 24);
			ret = E_OK;
		} else {
			dev_err(&info->pdev->dev,
				"flash ID 0x%02x 0x%02x is not in the ID table\n",
				card_id[0], card_id[1]);
			ret = -ENODEV;
		}

drivers/mtd/spiflash/spinand.c[843-866]

		for (i = 0; spinand_flash_ids[i].name; i++) {
			if ((card_id[0] == spinand_flash_ids[i].mfr_id) && \
			(card_id[1] == spinand_flash_ids[i].dev_id)) {
				id_count = spinand_flash_ids[i].id_len;
				memset(card_id + id_count, 0, 4 - id_count);
				info->flash_info->page_size = spinand_flash_ids[i].pagesize;
				info->flash_info->device_size = spinand_flash_ids[i].chipsize;
				info->flash_info->block_size = spinand_flash_ids[i].erasesize;
				info->flash_info->page_per_block = \
					(spinand_flash_ids[i].erasesize / spinand_flash_ids[i].pagesize);
                info->nand_chip.ecc.strength = spinand_flash_ids[i].ecc.strength_ds;
				break;
			}
		}
		if (spinand_flash_ids[i].name) {
			*id = card_id[0] | (card_id[1] << 8) |
				(card_id[2] << 16) | (card_id[3] << 24);
			ret = E_OK;
		} else {
			dev_err(&info->pdev->dev,
				"flash ID 0x%02x 0x%02x is not in the ID table\n",
				card_id[0], card_id[1]);
			ret = -ENODEV;
		}
Assessed commit 57ff026
Diagram

graph TD
  P["SPI NAND probe"] --> R["Read flash ID"] --> T["Sentinel ID table"] --> D{"Known ID?"} -->|matched| S["NAND scan"]
  D -->|unknown| E["Return ENODEV"] --> C["Devres cleanup"]
Loading
High-Level Assessment

Keep the sentinel and name-based lookup in both drivers: the downstream NAND scanner requires a NULL-name terminator, and stopping the driver lookup there also prevents an all-zero ID from matching it. A length-bounded lookup would still need the sentinel for the scanner, while consolidating the two drivers is beyond this focused fix.

Files changed (2) +24 / -12

Bug fix (2) +24 / -12
spi020_nand.cTerminate SPI020 IDs and reject unsupported flash safely +12/-6

Terminate SPI020 IDs and reject unsupported flash safely

• Adds a NULL-name ID-table terminator and stops lookup before it. Unknown IDs now log an error and return -ENODEV; probe failure no longer frees the embedded, device-managed MTD pointer.

drivers/mtd/spiflash/spi020_nand.c

spinand.cBound SPI NAND identification and correct probe cleanup +12/-6

Bound SPI NAND identification and correct probe cleanup

• Terminates the ID table used by NAND scanning and prevents lookup from matching its zero-filled sentinel. Unsupported IDs fail before unset geometry is used, and the probe error path no longer frees the embedded MTD pointer.

drivers/mtd/spiflash/spinand.c

@qodo-free-for-open-source-projects

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

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Unknown flash probes leak memory 🐞 Bug ☼ Reliability
Description
drv_nand_read_id() now returns an error for an unlisted ID, but the probe failure path in both
drivers never frees the separately allocated info->flash_info. Each failed probe reaches the
cleanup labels, which free the data buffer and IRQ but leave that allocation behind.
Code

drivers/mtd/spiflash/spinand.c[865]

+			ret = -ENODEV;
Evidence
Both probes allocate flash metadata with kmalloc(). The new unknown-ID returns reach their probe
error paths, where cleanup releases the IRQ and data buffer but not flash_info; the corresponding
SPI020 change has the same path.

drivers/mtd/spiflash/spinand.c[1292-1306]
drivers/mtd/spiflash/spinand.c[861-865]
drivers/mtd/spiflash/spinand.c[1357-1363]
drivers/mtd/spiflash/spinand.c[1448-1455]
drivers/mtd/spiflash/spi020_nand.c[1069-1083]
drivers/mtd/spiflash/spi020_nand.c[689-694]
drivers/mtd/spiflash/spi020_nand.c[1196-1203]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Unknown-ID failures now leave the separately allocated flash metadata behind in both drivers.
## Fix Focus Areas
- drivers/mtd/spiflash/spinand.c[1292-1296]
- drivers/mtd/spiflash/spi020_nand.c[1069-1073]
## Recommended Fix
Allocate `info->flash_info` with `devm_kzalloc()` in both probes so probe failure releases it with `info`. Preserve allocation-failure handling.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Tip of the day
💡 Did you know, you can switch off images and animations for a plain-text comment

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@openipc-ai openipc-ai 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.

Approving. This is the follow-up from #339, done the way I asked: the terminator, with drv_nand_read_id() stopping at name == NULL rather than at ARRAY_SIZE().

What I checked:

  • The lookup. It ends either on a match, where break leaves i on the entry, or on the sentinel, where .name is NULL and the else arm fails. 00 00 can no longer reach the sentinel's zero geometry, and ff ff, 12 34 or anything else unlisted fails the same way. Both tables now end in { NULL }, and nand_scan_with_ids() is the only other user of either table, so nand_detect() stops at the end too.
  • The error path. drv_nand_identify() maps any non-E_OK to -EIO and the probe reports -ENODEV, so the new message is the only visible change. After identification chip_id is set, so NAND_CMD_READID from the NAND core takes the memcpy path and never re-enters the lookup.
  • kfree(mtd). mtd is nand_to_mtd(&info->nand_chip), inside the devm_kzalloc()'d info. Freeing it was freeing an interior pointer of a devres allocation, which fits the later clk_debug_init() oops you saw. Dropping it is right. The earlier gotos to fail_free_mtd now just return, and devres frees info.
  • What changes for a camera. A listed chip goes through exactly the same steps as before. An unlisted chip used to hang the boot (before #339) or run on with unset geometry and a corrupted slab (since #339). It now fails the probe with a readable line on the console, and the boot continues.

One leftover of the same defect: spinand_remove() still ends in kfree(mtd) in both drivers (spinand.c and spi020_nand.c). It's reached only on unbind, since the driver is built in, so it doesn't block. It's the same two-line fix if you push again, or a follow-up otherwise.

@openipc-ai
openipc-ai merged commit 5f7f91b into OpenIPC:novatek-nt9856x Nov 29, 2026
openipc-ai added a commit that referenced this pull request Nov 29, 2026
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.
openipc-ai added a commit that referenced this pull request Nov 29, 2026
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.
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