[PATCH v5-fix 1/5] block: Don't invalidate pagecache for invalid falloc modes

From: Sarthak Kukreti
Date: Wed Apr 19 2023 - 21:47:57 EST


Only call truncate_bdev_range() if the fallocate mode is
supported. This fixes a bug where data in the pagecache
could be invalidated if the fallocate() was called on the
block device with an invalid mode.

Fixes: 25f4c41415e5 ("block: implement (some of) fallocate for block devices")
Signed-off-by: Sarthak Kukreti <sarthakkukreti@xxxxxxxxxxxx>
---
block/fops.c | 37 ++++++++++++++++++++++++-------------
1 file changed, 24 insertions(+), 13 deletions(-)

diff --git a/block/fops.c b/block/fops.c
index d2e6be4e3d1c..d359254c645d 100644
--- a/block/fops.c
+++ b/block/fops.c
@@ -648,26 +648,37 @@ static long blkdev_fallocate(struct file *file, int mode, loff_t start,

filemap_invalidate_lock(inode->i_mapping);

- /* Invalidate the page cache, including dirty pages. */
- error = truncate_bdev_range(bdev, file->f_mode, start, end);
- if (error)
- goto fail;
-
+ /*
+ * Invalidate the page cache, including dirty pages, for valid
+ * de-allocate mode calls to fallocate().
+ */
switch (mode) {
case FALLOC_FL_ZERO_RANGE:
case FALLOC_FL_ZERO_RANGE | FALLOC_FL_KEEP_SIZE:
- error = blkdev_issue_zeroout(bdev, start >> SECTOR_SHIFT,
- len >> SECTOR_SHIFT, GFP_KERNEL,
- BLKDEV_ZERO_NOUNMAP);
+ error = truncate_bdev_range(bdev, file->f_mode, start, end);
+ if (!error)
+ error = blkdev_issue_zeroout(bdev,
+ start >> SECTOR_SHIFT,
+ len >> SECTOR_SHIFT,
+ GFP_KERNEL,
+ BLKDEV_ZERO_NOUNMAP);
break;
case FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE:
- error = blkdev_issue_zeroout(bdev, start >> SECTOR_SHIFT,
- len >> SECTOR_SHIFT, GFP_KERNEL,
- BLKDEV_ZERO_NOFALLBACK);
+ error = truncate_bdev_range(bdev, file->f_mode, start, end);
+ if (!error)
+ error = blkdev_issue_zeroout(bdev,
+ start >> SECTOR_SHIFT,
+ len >> SECTOR_SHIFT,
+ GFP_KERNEL,
+ BLKDEV_ZERO_NOFALLBACK);
break;
case FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE | FALLOC_FL_NO_HIDE_STALE:
- error = blkdev_issue_discard(bdev, start >> SECTOR_SHIFT,
- len >> SECTOR_SHIFT, GFP_KERNEL);
+ error = truncate_bdev_range(bdev, file->f_mode, start, end);
+ if (!error)
+ error = blkdev_issue_discard(bdev,
+ start >> SECTOR_SHIFT,
+ len >> SECTOR_SHIFT,
+ GFP_KERNEL);
break;
default:
error = -EOPNOTSUPP;
--
2.40.0.634.g4ca3ef3211-goog