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 <[email protected]>
---
 cmd/mtd.c | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/cmd/mtd.c b/cmd/mtd.c
index 1d1845bce44..29189925b24 100644
--- a/cmd/mtd.c
+++ b/cmd/mtd.c
@@ -519,7 +519,17 @@ 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) {
+                       printf("Start offset 0x%llx is greater or equal to mtd 
size 0x%llx\n", start_off, mtd->size);
+                       ret = CMD_RET_FAILURE;
+                       goto out_put_mtd;
+               }
+               default_len = mtd->size - start_off;
+       }
+
        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

Reply via email to