[PATCH v4 2/4] mtd: mtdchar: clamp bounce buffer size to the remaining transfer
From: Ping Li
Date: Fri Dec 04 2026 - 04:16:56 EST
mtdchar_read() and mtdchar_write() initialize the bounce buffer
size with the raw count from userspace, then clamp count to what
actually remains in the device. The bounce buffer therefore gets
allocated with the unclamped size: a read() of a few MiB near the
end of a small device allocates a few MiB of bounce buffer to
carry only a few KiB, which wastes memory and vmalloc space and
may even fail with -ENOMEM for a trivially small transfer.
Set the bounce buffer size after count has been clamped.
Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Cc: stable@xxxxxxxxxxxxxxx
Signed-off-by: Ping Li <leeonion.muyu@xxxxxxxxx>
---
drivers/mtd/mtdchar.c | 6 ++++--
1 file changed, 4 insertions(+), 2 deletions(-)
diff --git a/drivers/mtd/mtdchar.c b/drivers/mtd/mtdchar.c
index bf01e6ac72931..2b6e70864bfbb 100644
--- a/drivers/mtd/mtdchar.c
+++ b/drivers/mtd/mtdchar.c
@@ -133,7 +133,7 @@ static ssize_t mtdchar_read(struct file *file, char __user *buf, size_t count,
size_t total_retlen=0;
int ret=0;
int len;
- size_t size = count;
+ size_t size;
char *kbuf;
pr_debug("MTD_read\n");
@@ -148,6 +148,7 @@ static ssize_t mtdchar_read(struct file *file, char __user *buf, size_t count,
if (!count)
return 0;
+ size = count;
kbuf = mtd_kmalloc_up_to(mtd, &size);
if (!kbuf)
return -ENOMEM;
@@ -219,7 +220,7 @@ static ssize_t mtdchar_write(struct file *file, const char __user *buf, size_t c
{
struct mtd_file_info *mfi = file->private_data;
struct mtd_info *mtd = mfi->mtd;
- size_t size = count;
+ size_t size;
char *kbuf;
size_t retlen;
size_t total_retlen=0;
@@ -237,6 +238,7 @@ static ssize_t mtdchar_write(struct file *file, const char __user *buf, size_t c
if (!count)
return 0;
+ size = count;
kbuf = mtd_kmalloc_up_to(mtd, &size);
if (!kbuf)
return -ENOMEM;
--
2.34.1