[PATCH 2/2] cmd: mtd: fix default length calculation when offset is specified

Peter Suti peter.suti at streamunlimited.com
Tue Dec 16 14:40:42 CET 2025


When the 'mtd read' command is issued with an offset but no size (argc=1),
the length defaults to the full partition size ('mtd->size').

This calculation is incorrect because reading 'mtd->size' bytes starting
from a non-zero offset results in a read request that extends past the
end of the partition. This causes the MTD layer to return error -22
(EINVAL).

Fix the default length calculation to be 'mtd->size - offset' so that
reads starting from an offset effectively read "to the end of the
partition" rather than attempting to read out of bounds.

Signed-off-by: Peter Suti <peter.suti at streamunlimited.com>
[add {} for better readability]
Signed-off-by: Radek Dostál <radek.dostal at streamunlimited.com>
---
 cmd/mtd.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)

diff --git a/cmd/mtd.c b/cmd/mtd.c
index 1d1845bce44..9f6e3226c15 100644
--- a/cmd/mtd.c
+++ b/cmd/mtd.c
@@ -519,7 +519,15 @@ static int do_mtd_io(struct cmd_tbl *cmdtp, int flag, int argc,
 		goto out_put_mtd;
 	}
 
-	default_len = dump ? mtd->writesize : mtd->size;
+	if (dump) {
+		default_len = mtd->writesize;
+	} else {
+		if (start_off < mtd->size)
+			default_len = mtd->size - start_off;
+		else
+			default_len = 0;
+	}
+
 	len = argc > 1 ? hextoul(argv[1], NULL) : default_len;
 	if (!mtd_is_aligned_with_min_io_size(mtd, len)) {
 		len = round_up(len, mtd->writesize);
-- 
2.43.0



More information about the U-Boot mailing list