diff mbox series

[1/3] btrfs-progs: remove use BLKGETSIZE64

Message ID 20200315152430.7532-2-kreijack@libero.it (mailing list archive)
State New, archived
Headers show
Series [1/3] btrfs-progs: remove use BLKGETSIZE64 | expand

Commit Message

Goffredo Baroncelli March 15, 2020, 3:24 p.m. UTC
From: Goffredo Baroncelli <kreijack@inwind.it>

Allow the get_partition_size() to be called without
root privileges.

Signed-off-by: Goffredo baroncelli <kreijack@inwind.it>
---
 common/device-utils.c | 29 +++++++++++++++++++++--------
 1 file changed, 21 insertions(+), 8 deletions(-)
diff mbox series

Patch

diff --git a/common/device-utils.c b/common/device-utils.c
index b03d62fa..9519dbce 100644
--- a/common/device-utils.c
+++ b/common/device-utils.c
@@ -17,6 +17,8 @@ 
 #include <sys/ioctl.h>
 #include <sys/mount.h>
 #include <sys/statfs.h>
+#include <sys/types.h>
+#include <sys/sysmacros.h>
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
@@ -238,17 +240,28 @@  u64 disk_size(const char *path)
 
 u64 get_partition_size(const char *dev)
 {
-	u64 result;
-	int fd = open(dev, O_RDONLY);
+	struct stat statbuf;
+	int r;
+	int fd;
+	char buf[100];
 
-	if (fd < 0)
+	r = stat(dev, &statbuf);
+	if (r != 0)
 		return 0;
-	if (ioctl(fd, BLKGETSIZE64, &result) < 0) {
-		close(fd);
-		return 0;
-	}
+
+	snprintf(buf, sizeof(buf),
+		"/sys/dev/block/%d:%d/size", gnu_dev_major(statbuf.st_rdev),
+		 gnu_dev_minor(statbuf.st_rdev));
+
+	fd = open(buf, O_RDONLY);
+	BUG_ON(fd < 0);
+
+	r = read(fd, buf, sizeof(buf)-1);
 	close(fd);
 
-	return result;
+	BUG_ON(r < 0);
+	buf[r] = 0;
+
+	return atoll(buf) * 512;
 }