[PATCH V3] loop: Add sanity check for read/write_iter

From: Lizhi Xu
Date: Fri Apr 25 2025 - 22:11:27 EST


Some file systems do not support read_iter/write_iter, such as selinuxfs
in this issue.
So before calling them, first confirm that the interface is supported and
then call it.

Fixes: f2fed441c69b ("loop: stop using vfs_iter__{read,write} for buffered I/O")
Reported-by: syzbot+6af973a3b8dfd2faefdc@xxxxxxxxxxxxxxxxxxxxxxxxx
Closes: https://syzkaller.appspot.com/bug?extid=6af973a3b8dfd2faefdc
Signed-off-by: Lizhi Xu <lizhi.xu@xxxxxxxxxxxxx>
---
V1 -> V2: move check to loop_configure and loop_change_fd
V2 -> V3: using helper for this check

drivers/block/loop.c | 22 ++++++++++++++++++++++
1 file changed, 22 insertions(+)

diff --git a/drivers/block/loop.c b/drivers/block/loop.c
index 674527d770dc..7b78ddf7b819 100644
--- a/drivers/block/loop.c
+++ b/drivers/block/loop.c
@@ -582,6 +582,19 @@ static void loop_assign_backing_file(struct loop_device *lo, struct file *file)
lo->lo_min_dio_size = loop_query_min_dio_size(lo);
}

+static int loop_check_backing_file(struct file *file, blk_mode_t mode, bool change)
+{
+ if (!file->f_op->read_iter)
+ return -EINVAL;
+
+ if (((file->f_mode & FMODE_WRITE) ||
+ (!change && (mode & BLK_OPEN_WRITE))) &&
+ (!file->f_op->write_iter))
+ return -EINVAL;
+
+ return 0;
+}
+
/*
* loop_change_fd switched the backing store of a loopback device to
* a new file. This is useful for operating system installers to free up
@@ -603,6 +616,10 @@ static int loop_change_fd(struct loop_device *lo, struct block_device *bdev,
if (!file)
return -EBADF;

+ error = loop_check_backing_file(file, 0, true);
+ if (error)
+ return error;
+
/* suppress uevents while reconfiguring the device */
dev_set_uevent_suppress(disk_to_dev(lo->lo_disk), 1);

@@ -1039,6 +1056,11 @@ static int loop_configure(struct loop_device *lo, blk_mode_t mode,

if (!file)
return -EBADF;
+
+ error = loop_check_backing_file(file, mode, false);
+ if (error)
+ return error;
+
is_loop = is_loop_device(file);

/* This is safe, since we have a reference from open(). */
--
2.43.0