[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

[Nbd] [PATCH] Fix size setup ioctls for small devices



For devices smaller than 4096 the current code results in a blockdevice
size of 0.

For devices with a different blocksize than 4096 the code potentially
leads to more dropped blocks at the end of the file than necessary. For
example a device with size 6144 would have only 4096 bytes available on
client side even if the blocksize is set to 512.

This patch tries to use the user-given blocksize if possible. Otherwise
it falls back to using 4096.

Signed-off-by: Markus Pargmann <mpa@...1897...>
---
 nbd-client.c | 21 ++++++++++++++++-----
 1 file changed, 16 insertions(+), 5 deletions(-)

diff --git a/nbd-client.c b/nbd-client.c
index 2c387f8c8c4c..40d6b7abac3c 100644
--- a/nbd-client.c
+++ b/nbd-client.c
@@ -462,14 +462,25 @@ void setsizes(int nbd, u64 size64, int blocksize, u32 flags) {
 	if (size64>>12 > (uint64_t)~0UL)
 		err("Device too large.\n");
 	else {
-		if (ioctl(nbd, NBD_SET_BLKSIZE, 4096UL) < 0)
+		int tmp_blocksize = 4096;
+		if (size64 / (u64)blocksize <= (uint64_t)~0UL)
+			tmp_blocksize = blocksize;
+		if (ioctl(nbd, NBD_SET_BLKSIZE, tmp_blocksize) < 0) {
+			fprintf(stderr, "Failed to set blocksize %d\n",
+				tmp_blocksize);
 			err("Ioctl/1.1a failed: %m\n");
-		size = (unsigned long)(size64>>12);
+		}
+		size = (unsigned long)(size64 / (u64)tmp_blocksize);
 		if (ioctl(nbd, NBD_SET_SIZE_BLOCKS, size) < 0)
 			err("Ioctl/1.1b failed: %m\n");
-		if (ioctl(nbd, NBD_SET_BLKSIZE, (unsigned long)blocksize) < 0)
-			err("Ioctl/1.1c failed: %m\n");
-		fprintf(stderr, "bs=%d, sz=%llu bytes\n", blocksize, 4096ULL*size);
+		if (tmp_blocksize != blocksize) {
+			if (ioctl(nbd, NBD_SET_BLKSIZE, (unsigned long)blocksize) < 0) {
+				fprintf(stderr, "Failed to set blocksize %d\n",
+					blocksize);
+				err("Ioctl/1.1c failed: %m\n");
+			}
+		}
+		fprintf(stderr, "bs=%d, sz=%llu bytes\n", blocksize, (u64)tmp_blocksize * size);
 	}
 
 	ioctl(nbd, NBD_CLEAR_SOCK);
-- 
2.7.0.rc3




Reply to: