Skip to contentSkip to conversation

Fixing invalid device size output when "btrfs device usage /" is called as normal user

PATCH New Zoltan Racz 1 participant 1 message Jul 30, 2025 Btrfs file system

lore
Share & tools
lore
#0 lore raw

PATCH 1/1 Fixing invalid device size output when "btrfs device usage /" is called as normal user

This patch fixes bug #979 - "wrong and misleading" device usage output as normal user

When "btrfs device usage /" is being called as a normal user, the function device_get_partition_size in device-utils.c calls device_get_partition_size_sysfs() as a fallback, which reads the size of the partition from "/sys/class/block/[partition]/size".

The problem here is that the size read is not actually the size of the partition but rather a number of how many 512B (or whatever the devices sector size is) sectors the partition contains.

Ex: if read value is 104857600 the size is not 100MB but 104857600 * 512B = 50GB

This patch adds a function named get_partition_sector_size_sysfs which based on the partition name returns the sector size of the device, and replaces "return size" with "return size * sector_size" in device_get_partition_size_sysfs.

---
 common/device-utils.c | 42 +++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 41 insertions(+), 1 deletion(-)
common/device-utils.c +41 -1
index 783d7955..68aaa538 100644
@@ -342,6 +342,42 @@ u64 device_get_partition_size_fd(int fd)
 	return result;
 }
 
+static u64 get_partition_sector_size_sysfs(const char *name)
+{
+	int ret = 0;
+	char real_path[PATH_MAX] = {};
+	char link_path[PATH_MAX] = {};
+	char *dev_name = NULL;
+	int sysfd;
+	char sysfs[PATH_MAX] = {};
+	char sizebuf[128];
+
+	snprintf(link_path, PATH_MAX, "/sys/class/block/%s/..", name);
+
+	if (!realpath(link_path, real_path)) 
+		return 0;
+
+	dev_name = basename(real_path);
+
+	if (!dev_name)
+		return 0;
+
+	snprintf(sysfs, PATH_MAX, "/sys/class/block/%s/queue/hw_sector_size", dev_name);
+	
+	sysfd = open(sysfs, O_RDONLY);
+	if (sysfd < 0)
+		return 0;
+
+	ret = sysfs_read_file(sysfd, sizebuf, sizeof(sizebuf));
+	close(sysfd);
+
+	if (ret < 0) 
+		return 0;
+
+	return atoi(sizebuf);
+}
+
+
 static u64 device_get_partition_size_sysfs(const char *dev)
 {
 	int ret;
@@ -351,6 +387,7 @@ static u64 device_get_partition_size_sysfs(const char *dev)
 	const char *name = NULL;
 	int sysfd;
 	unsigned long long size = 0;
+	unsigned long long sector_size = 0;
 
 	name = realpath(dev, path);
 	if (!name)
@@ -375,7 +412,10 @@ static u64 device_get_partition_size_sysfs(const char *dev)
 		return 0;
 	}
 	close(sysfd);
-	return size;
+
+	sector_size = get_partition_sector_size_sysfs(name);
+
+	return size * sector_size;
 }
 
 u64 device_get_partition_size(const char *dev)
Signature · 1 line
2.50.1