[PATCH v3] block: add check that partition length needs to be aligned with block size

From: Min Li
Date: Wed Jun 28 2023 - 04:56:42 EST


Before calling add partition or resize partition, there is no check
on whether the length is aligned with the logical block size.
If the logical block size of the disk is larger than 512 bytes,
then the partition size maybe not the multiple of the logical block size,
and when the last sector is read, bio_truncate() will adjust the bio size,
resulting in an IO error if the size of the read command is smaller than
the logical block size.If integrity data is supported, this will also
result in a null pointer dereference when calling bio_integrity_free.

Signed-off-by: Min Li <min15.li@xxxxxxxxxxx>

---
Changes from v1:

- Add a space after /* and before */.
- Move length alignment check before the "start = p.start >> SECTOR_SHIFT"
- Move check for p.start being aligned together with this length alignment check.

Changes from v2:

- Add the assignment on the first line and merge the two lines into one.
- Use IS_ALIGNED function to check alignment.
---
block/ioctl.c | 9 +++++----
1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/block/ioctl.c b/block/ioctl.c
index 3be11941fb2d..1a351132bf4e 100644
--- a/block/ioctl.c
+++ b/block/ioctl.c
@@ -16,9 +16,9 @@
static int blkpg_do_ioctl(struct block_device *bdev,
struct blkpg_partition __user *upart, int op)
{
+ long long blksz = bdev_logical_block_size(bdev), start, length;
struct gendisk *disk = bdev->bd_disk;
struct blkpg_partition p;
- long long start, length;

if (!capable(CAP_SYS_ADMIN))
return -EACCES;
@@ -33,14 +33,15 @@ static int blkpg_do_ioctl(struct block_device *bdev,
if (op == BLKPG_DEL_PARTITION)
return bdev_del_partition(disk, p.pno);

+ /* Check that the partition is aligned to the block size */
+ if (!IS_ALIGNED(p.start | p.length, blksz))
+ return -EINVAL;
+
start = p.start >> SECTOR_SHIFT;
length = p.length >> SECTOR_SHIFT;

switch (op) {
case BLKPG_ADD_PARTITION:
- /* check if partition is aligned to blocksize */
- if (p.start & (bdev_logical_block_size(bdev) - 1))
- return -EINVAL;
return bdev_add_partition(disk, p.pno, start, length);
case BLKPG_RESIZE_PARTITION:
return bdev_resize_partition(disk, p.pno, start, length);
--
2.34.1