[PATCH v2 2/2] mtd: rawnand: ingenic: validate BCH error index in jz4780_correct()

From: Guanglei Zhu

Date: Wed Nov 04 2026 - 23:26:13 EST


From: Weibin Liu <liuwb@xxxxxxxxxxxx>

The JZ4780 BCH controller reports each corrected bit error as a byte
pair index, in the INDEX field of the BCH_BHERR registers. The field
is 11 bits wide, but nothing in jz4780_correct() checks the reported
index against the size of the data buffer being corrected:

buf[(index * 2) + 0] ^= mask;
buf[(index * 2) + 1] ^= mask >> 8;

With data or ECC coming from an untrusted flash, the decoder can
report an index that points past the end of the data buffer, and the
above statements then flip bits outside the buffer.

Skip the correction when the reported index does not point into
the data area. A bitflip in the parity bytes does not affect the
data, so rejecting the page for it would fail reads that are
perfectly correctable, and an index beyond the codeword has no
buffer to update in the first place.

Fixes: ae02ab00aa3c ("mtd: nand: jz4780: driver for NAND devices on JZ4780 SoCs")
Signed-off-by: Weibin Liu <liuwb@xxxxxxxxxxxx>
---
Changes in v2: skip the correction for an index that does not point
into the data area instead of failing the page with -EBADMSG. A
correctable bitflip in the ECC bytes leaves the data valid, and the
early exit also dropped the error entries that followed it. This
matches how jz4740_ecc_correct() treats its indexes.

Verified with a userspace replica of the correction loop: with
params->size = 512, an index of 256 (first parity word) or at the
field maximum (0x7ff) produces no write outside the data buffer,
and in-range indexes keep correcting as before.

drivers/mtd/nand/raw/ingenic/jz4780_bch.c | 4 ++++
1 file changed, 4 insertions(+)

diff --git a/drivers/mtd/nand/raw/ingenic/jz4780_bch.c b/drivers/mtd/nand/raw/ingenic/jz4780_bch.c
index 12b5b0484fe9..3a4c5d6e7f8a 100644
--- a/drivers/mtd/nand/raw/ingenic/jz4780_bch.c
+++ b/drivers/mtd/nand/raw/ingenic/jz4780_bch.c
@@ -216,6 +216,10 @@ static int jz4780_correct(struct ingenic_ecc *bch,
BCH_BHERR_MASK_SHIFT;
index = (reg & BCH_BHERR_INDEX_MASK) >>
BCH_BHERR_INDEX_SHIFT;
+ /* Skip indexes outside the data area. */
+ if ((index * 2) + 1 >= params->size)
+ continue;
+
buf[(index * 2) + 0] ^= mask;
buf[(index * 2) + 1] ^= mask >> 8;
}
--
2.50.1