[PATCH v2 2/3] mtd: rawnand: cadence: Resize the bounce buffer before the BBT scan
From: Miquel Raynal
Date: Tue Nov 24 2026 - 04:24:43 EST
The bounce buffer is allocated with a default size and only resized to
the actual page + OOB size once all the chips have been
scanned. However, the bad block table is scanned during nand_scan(),
before that resize happens, using the same bounce buffer. Chips with a
page + OOB size larger than the default size may therefore overflow the
heap buffer.
In practice, this default is safe since it is set to 16kiB and I
currently know no chip with a bigger page size, but chances are that
this is not a future-proof bet, so let's resize the bounce buffer
whenever we attach a chip whose geometry needs a bigger buffer.
Fixes: ec4ba01e894d ("mtd: rawnand: Add new Cadence NAND driver to MTD subsystem")
Cc: stable@xxxxxxxxxxxxxxx
Signed-off-by: Miquel Raynal <miquel.raynal@xxxxxxxxxxx>
---
drivers/mtd/nand/raw/cadence-nand-controller.c | 25 +++++++++++++++----------
1 file changed, 15 insertions(+), 10 deletions(-)
diff --git a/drivers/mtd/nand/raw/cadence-nand-controller.c b/drivers/mtd/nand/raw/cadence-nand-controller.c
index 42cc62b36457..912148f90ece 100644
--- a/drivers/mtd/nand/raw/cadence-nand-controller.c
+++ b/drivers/mtd/nand/raw/cadence-nand-controller.c
@@ -2970,8 +2970,17 @@ static int cadence_nand_attach_chip(struct nand_chip *chip)
chip->ecc.read_oob_raw = cadence_nand_read_oob_raw;
chip->ecc.write_oob_raw = cadence_nand_write_oob_raw;
- if ((mtd->writesize + mtd->oobsize) > cdns_ctrl->buf_size)
+ if ((mtd->writesize + mtd->oobsize) > cdns_ctrl->buf_size) {
+ u8 *buf;
+
+ buf = krealloc(cdns_ctrl->buf, mtd->writesize + mtd->oobsize,
+ GFP_KERNEL);
+ if (!buf)
+ return -ENOMEM;
+
+ cdns_ctrl->buf = buf;
cdns_ctrl->buf_size = mtd->writesize + mtd->oobsize;
+ }
/* Is 32-bit DMA supported? */
ret = dma_set_mask(cdns_ctrl->dev, DMA_BIT_MASK(32));
@@ -3136,8 +3145,11 @@ static int cadence_nand_init(struct cdns_nand_ctrl *cdns_ctrl)
if (!cdns_ctrl->cdma_desc)
return -ENOMEM;
- cdns_ctrl->buf_size = SZ_16K;
- cdns_ctrl->buf = kmalloc(cdns_ctrl->buf_size, GFP_KERNEL);
+ /*
+ * Allocate a scratch buffer for the identification phase. It gets
+ * resized to the actual chip geometry in ->attach_chip().
+ */
+ cdns_ctrl->buf = kmalloc(SZ_16K, GFP_KERNEL);
if (!cdns_ctrl->buf) {
ret = -ENOMEM;
goto free_buf_desc;
@@ -3194,13 +3206,6 @@ static int cadence_nand_init(struct cdns_nand_ctrl *cdns_ctrl)
goto unmap_dma_resource;
}
- kfree(cdns_ctrl->buf);
- cdns_ctrl->buf = kzalloc(cdns_ctrl->buf_size, GFP_KERNEL);
- if (!cdns_ctrl->buf) {
- ret = -ENOMEM;
- goto unmap_dma_resource;
- }
-
return 0;
unmap_dma_resource:
--
2.56.0