[PATCH 1/2] zram: refuse to use zero sized block device as backing device

From: Kairui Song
Date: Wed Dec 04 2024 - 13:08:09 EST


From: Kairui Song <kasong@xxxxxxxxxxx>

Setting a zero sized block device as backing device is pointless, and
one can easily create a recursive loop by setting the uninitialized
ZRAM device itself as its own backing device by (zram0 is uninitialized):

echo /dev/zram0 > /sys/block/zram0/backing_dev

It's definitely a wrong config, and the module will pin itself,
kernel should refuse doing so in the first place.

By refusing to use zero sized device we avoided misuse cases
including this one above.

Fixes: 013bf95a83ec ("zram: add interface to specif backing device")
Reported-by: Desheng Wu <deshengwu@xxxxxxxxxxx>
Signed-off-by: Kairui Song <kasong@xxxxxxxxxxx>
Cc: stable@xxxxxxxxxxxxxxx
---
drivers/block/zram/zram_drv.c | 6 ++++++
1 file changed, 6 insertions(+)

diff --git a/drivers/block/zram/zram_drv.c b/drivers/block/zram/zram_drv.c
index 0ca6d55c9917..dd48df5b97c8 100644
--- a/drivers/block/zram/zram_drv.c
+++ b/drivers/block/zram/zram_drv.c
@@ -614,6 +614,12 @@ static ssize_t backing_dev_store(struct device *dev,
}

nr_pages = i_size_read(inode) >> PAGE_SHIFT;
+ /* Refuse to use zero sized device (also prevents self reference) */
+ if (!nr_pages) {
+ err = -EINVAL;
+ goto out;
+ }
+
bitmap_sz = BITS_TO_LONGS(nr_pages) * sizeof(long);
bitmap = kvzalloc(bitmap_sz, GFP_KERNEL);
if (!bitmap) {
--
2.47.0