linux boot drive capacity

This commit is contained in:
deepend committed 2026-12-04 19:23:49 -06:00
1 parent 81709c7235
commit 38e7a5c763
2 files changed
+179 -242

No files matched your search

+177 -239
View File
@@ -1,294 +1,232 @@
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* SPDX-License-Identifier: GPL-2.0-or-later */
/* Report mounted local filesystem capacity without probing network mounts. */ /* Whole capacity of the disk backing the boot filesystem. */
#define _XOPEN_SOURCE 700
#include <errno.h> #include <errno.h>
#include <fcntl.h> #include <stdlib.h>
#include <string.h> #include <string.h>
#include <sys/ioctl.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <sys/statvfs.h>
#include <sys/sysmacros.h> #include <sys/sysmacros.h>
#include <unistd.h>
#if defined(__has_include)
# if __has_include(<linux/btrfs.h>)
# include <linux/btrfs.h>
# endif
#endif
#include <glib.h> #include <glib.h>
#include "../format.h"
#include "../sysinfo-backend.h" #include "../sysinfo-backend.h"
#include "storage.h" #include "storage.h"
typedef struct static gboolean
read_capacity (const char *entry, guint64 *capacity)
{ {
guint64 total; char *path = g_build_filename (entry, "size", NULL);
guint64 available; char *contents = NULL;
} StorageUsage; char *end;
guint64 sectors;
static char *
decode_mount_field (const char *field)
{
GString *value = g_string_new (NULL);
const char *p;
for (p = field; *p; p++)
{
/* mountinfo escapes whitespace and backslashes as octal. */
if (*p == '\\' && p[1] && p[2] && p[3] &&
p[1] >= '0' && p[1] <= '3' &&
p[2] >= '0' && p[2] <= '7' && p[3] >= '0' && p[3] <= '7')
{
guint code = (p[1] - '0') * 64 + (p[2] - '0') * 8 + p[3] - '0';
if (code == 0)
{
g_string_free (value, TRUE);
return NULL;
}
g_string_append_c (value, (char) code);
p += 3;
}
else
g_string_append_c (value, *p);
}
return g_string_free (value, FALSE);
}
gboolean
sysinfo_linux_mountinfo_parse (const char *line, char **device,
char **mountpoint, char **filesystem, char **source)
{
char **fields;
guint i, n;
gboolean valid = FALSE; gboolean valid = FALSE;
*device = *mountpoint = *filesystem = *source = NULL; if (g_file_get_contents (path, &contents, NULL, NULL))
fields = g_strsplit (line, " ", -1);
n = g_strv_length (fields);
for (i = 6; i + 3 < n; i++)
{ {
if (strcmp (fields[i], "-") != 0) g_strstrip (contents);
continue; if (g_ascii_isdigit (contents[0]))
if (!strchr (fields[2], ':') || fields[4][0] != '/' || !fields[i + 1][0])
break;
*mountpoint = decode_mount_field (fields[4]);
*source = decode_mount_field (fields[i + 2]);
if (*mountpoint && *source)
{ {
*device = g_strdup (fields[2]); errno = 0;
*filesystem = g_strdup (fields[i + 1]); sectors = g_ascii_strtoull (contents, &end, 10);
/* Linux reports size in 512-byte sectors, including 4Kn disks. */
if (!errno && *end == '\0' && sectors && sectors <= G_MAXUINT64 / 512)
{
*capacity = sectors * 512;
valid = TRUE; valid = TRUE;
} }
else
{
g_clear_pointer (mountpoint, g_free);
g_clear_pointer (source, g_free);
} }
break;
} }
g_strfreev (fields); g_free (contents);
g_free (path);
return valid; return valid;
} }
static gboolean static gboolean
local_filesystem (const char *filesystem) has_entry (const char *entry, const char *name)
{ {
/* A conservative list avoids statvfs on NFS, SMB, autofs and remote FUSE. char *path = g_build_filename (entry, name, NULL);
* fuseblk is accepted only when a real block device is verified below. */ gboolean present = g_file_test (path, G_FILE_TEST_EXISTS);
static const char *types[] = { g_free (path);
"ext2", "ext3", "ext4", "xfs", "btrfs", "bcachefs", "f2fs", return present;
"jfs", "reiserfs", "nilfs2", "vfat", "msdos", "exfat", "ntfs", }
"ntfs3", "fuseblk", "hfs", "hfsplus", "ufs", "minix", "zfs", NULL
}; /* Resolve the kernel device link before walking from a partition to its
guint i; * parent. Never infer the parent by stripping digits from a device name. */
for (i = 0; types[i]; i++) static gboolean
if (strcmp (types[i], filesystem) == 0) resolve_disk (const char *entry, char **disk, guint depth)
return TRUE; {
return FALSE; char *resolved = realpath (entry, NULL);
char *slaves = NULL;
GDir *dir = NULL;
const char *name;
gboolean valid = FALSE;
if (!resolved || depth >= 32)
goto done;
if (has_entry (resolved, "partition"))
{
char *parent = g_path_get_dirname (resolved);
valid = resolve_disk (parent, disk, depth + 1);
g_free (parent);
goto done;
}
/* Follow LUKS/LVM/MD layers. Multiple distinct underlying disks are
* ambiguous, so don't arbitrarily choose one of them. */
slaves = g_build_filename (resolved, "slaves", NULL);
dir = g_dir_open (slaves, 0, NULL);
if (dir && (name = g_dir_read_name (dir)) != NULL)
{
do
{
char *child = g_build_filename (slaves, name, NULL);
valid = resolve_disk (child, disk, depth + 1);
g_free (child);
if (!valid)
goto done;
} while ((name = g_dir_read_name (dir)) != NULL);
goto done;
}
name = strrchr (resolved, '/');
name = name ? name + 1 : resolved;
if (g_str_has_prefix (name, "loop") || g_str_has_prefix (name, "ram") ||
g_str_has_prefix (name, "zram") || g_str_has_prefix (name, "sr") ||
g_str_has_prefix (name, "fd") || g_str_has_prefix (name, "dm-") ||
g_str_has_prefix (name, "md") || !has_entry (resolved, "device"))
goto done;
if (!*disk)
*disk = g_strdup (resolved);
valid = strcmp (*disk, resolved) == 0;
done:
if (dir)
g_dir_close (dir);
g_free (slaves);
free (resolved);
return valid;
}
static guint
boot_mount_priority (const char *mountpoint)
{
if (strcmp (mountpoint, "/boot") == 0)
return 4;
if (strcmp (mountpoint, "/boot/efi") == 0)
return 3;
if (strcmp (mountpoint, "/efi") == 0)
return 2;
if (strcmp (mountpoint, "/") == 0)
return 1;
return 0;
} }
static gboolean static gboolean
read_usage (const char *path, StorageUsage *usage) valid_device_number (const char *id)
{ {
struct statvfs fs; const char *p = id;
guint64 block_size; if (!g_ascii_isdigit (*p))
if (statvfs (path, &fs) != 0)
return FALSE; return FALSE;
block_size = fs.f_frsize ? (guint64) fs.f_frsize : (guint64) fs.f_bsize; while (g_ascii_isdigit (*p))
if (!block_size || !fs.f_blocks || (guint64) fs.f_blocks > G_MAXUINT64 / block_size) p++;
if (*p++ != ':' || !g_ascii_isdigit (*p))
return FALSE; return FALSE;
usage->total = (guint64) fs.f_blocks * block_size; while (g_ascii_isdigit (*p))
usage->available = MIN ((guint64) fs.f_bavail, (guint64) fs.f_blocks) * block_size; p++;
return TRUE; return *p == '\0';
} }
static char * static char *
filesystem_key (const char *device, const char *mountpoint, resolve_mount_device (const char *sysfs, const char *id, const char *source)
const char *filesystem, const char *source)
{ {
char *entry = NULL;
struct stat st; struct stat st;
char *id, *sys_path, *target, *name;
gboolean block_source = FALSE;
if (strcmp (filesystem, "zfs") == 0) /* Btrfs and some other filesystems expose a synthetic mount device
* number. Prefer a verified source block device in that case. */
if (valid_device_number (id))
{ {
/* Datasets share their pool; don't add its capacity repeatedly. */ entry = g_build_filename (sysfs, "dev", "block", id, NULL);
const char *slash = strchr (source, '/'); if (g_file_test (entry, G_FILE_TEST_EXISTS))
return source[0] && source[0] != '/' ? return entry;
g_strdup_printf ("zfs:%.*s", (int) (slash ? (gsize) (slash - source) : strlen (source)), source) : NULL; g_free (entry);
} }
/* A bind mount shares the device number. Btrfs subvolumes can have
* separate synthetic device numbers, so prefer the source block device. */
if (g_str_has_prefix (source, "/dev/") && stat (source, &st) == 0 && S_ISBLK (st.st_mode)) if (g_str_has_prefix (source, "/dev/") && stat (source, &st) == 0 && S_ISBLK (st.st_mode))
{ {
id = g_strdup_printf ("%u:%u", (unsigned int) major (st.st_rdev), char *number = g_strdup_printf ("%u:%u", (unsigned int) major (st.st_rdev),
(unsigned int) minor (st.st_rdev)); (unsigned int) minor (st.st_rdev));
block_source = TRUE; entry = g_build_filename (sysfs, "dev", "block", number, NULL);
g_free (number);
return entry;
} }
else /* A sandbox may hide /dev nodes but still expose kernel block names.
id = g_strdup (device); * Only accept a direct /dev/<name>, never guess a mapper/UUID alias. */
if (g_str_has_prefix (source, "/dev/") && source[5] &&
sys_path = g_build_filename ("/sys/dev/block", id, NULL); strcmp (source + 5, ".") != 0 && strcmp (source + 5, "..") != 0 &&
target = g_file_read_link (sys_path, NULL); !strchr (source + 5, '/') && !strchr (source + 5, '\\'))
g_free (sys_path); return g_build_filename (sysfs, "class", "block", source + 5, NULL);
if (!target && !block_source)
{
g_free (id);
return NULL; return NULL;
}
name = g_path_get_basename (target ? target : source);
g_free (target);
if (g_str_has_prefix (name, "loop") || g_str_has_prefix (name, "ram") ||
g_str_has_prefix (name, "zram") || g_str_has_prefix (name, "fd") ||
g_str_has_prefix (name, "sr"))
{
g_free (name);
g_free (id);
return NULL;
}
g_free (name);
#ifdef BTRFS_IOC_FS_INFO
if (strcmp (filesystem, "btrfs") == 0)
{
/* The filesystem UUID is shared by all subvolumes and members of
* a multi-device filesystem (unlike st_dev or statfs.f_fsid). */
int fd = open (mountpoint, O_RDONLY);
if (fd >= 0)
{
struct btrfs_ioctl_fs_info_args info = {0};
if (ioctl (fd, BTRFS_IOC_FS_INFO, &info) == 0)
{
GString *uuid = g_string_new ("btrfs:");
guint i;
for (i = 0; i < sizeof (info.fsid); i++)
g_string_append_printf (uuid, "%02x", (unsigned int) info.fsid[i]);
g_free (id);
id = g_string_free (uuid, FALSE);
}
close (fd);
}
}
#else
(void) mountpoint;
#endif
return id;
} }
static char * char *
format_scoped_usage (const StorageUsage *usage, const char *scope) sysinfo_linux_boot_disk (const char *sysfs, const char *mountinfo)
{ {
char *formatted = sysinfo_format_usage (usage->total, usage->available); char **lines = g_strsplit (mountinfo, "\n", -1);
char *result; char *entry = NULL, *disk = NULL, *result = NULL;
if (!formatted) guint priority = 0, i;
return NULL; guint64 capacity;
result = g_strdup_printf ("%s (%s)", formatted, scope); gboolean ambiguous = FALSE;
g_free (formatted);
for (i = 0; lines[i]; i++)
{
char **fields = g_strsplit (lines[i], " ", -1);
guint count = g_strv_length (fields), rank, j;
if (count < 10 || !(rank = boot_mount_priority (fields[4])) || rank < priority)
{
g_strfreev (fields);
continue;
}
for (j = 6; j + 3 < count; j++)
if (strcmp (fields[j], "-") == 0)
{
char *candidate = resolve_mount_device (sysfs, fields[2], fields[j + 2]);
if (rank > priority)
{
g_free (entry);
entry = candidate;
priority = rank;
ambiguous = FALSE;
}
else
{
if (g_strcmp0 (entry, candidate) != 0)
ambiguous = TRUE;
g_free (candidate);
}
break;
}
g_strfreev (fields);
}
g_strfreev (lines);
if (!ambiguous && entry && resolve_disk (entry, &disk, 0) &&
read_capacity (disk, &capacity))
result = g_format_size (capacity);
g_free (disk);
g_free (entry);
return result; return result;
} }
char * char *
sysinfo_backend_get_disk (void) sysinfo_backend_get_disk (void)
{ {
const gboolean flatpak = g_file_test ("/.flatpak-info", G_FILE_TEST_IS_REGULAR);
const char *path = flatpak ? g_get_user_data_dir () : g_get_home_dir ();
StorageUsage aggregate = {0, 0};
char *mountinfo = NULL; char *mountinfo = NULL;
char *result;
/* Flatpak sees a sandbox mount namespace, not all host disks. */ /* The sandbox root is not the host boot filesystem. Without a trusted
if (!flatpak && g_file_get_contents ("/proc/self/mountinfo", &mountinfo, NULL, NULL)) * host mount table there is no reliable way to identify its boot disk. */
{ if (g_file_test ("/.flatpak-info", G_FILE_TEST_IS_REGULAR) ||
GHashTable *volumes = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free); !g_file_get_contents ("/proc/self/mountinfo", &mountinfo, NULL, NULL))
char **lines = g_strsplit (mountinfo, "\n", -1);
guint i;
GHashTableIter iter;
gpointer value;
for (i = 0; lines[i]; i++)
{
char *device, *mountpoint, *filesystem, *source;
char *key = NULL;
StorageUsage usage;
struct stat st;
char *actual_device = NULL;
if (!sysinfo_linux_mountinfo_parse (lines[i], &device, &mountpoint, &filesystem, &source))
continue;
/* A covered mount must not be measured as the filesystem on top of it. */
if (local_filesystem (filesystem) && stat (mountpoint, &st) == 0)
{
actual_device = g_strdup_printf ("%u:%u", (unsigned int) major (st.st_dev),
(unsigned int) minor (st.st_dev));
if (strcmp (device, actual_device) == 0)
key = filesystem_key (device, mountpoint, filesystem, source);
}
if (key && read_usage (mountpoint, &usage))
{
StorageUsage *previous = g_hash_table_lookup (volumes, key);
/* Quotas may expose different sizes on the same filesystem.
* Keep one observation rather than adding shared capacity. */
if (!previous || usage.total > previous->total ||
(usage.total == previous->total && usage.available > previous->available))
{
StorageUsage *copy = g_new (StorageUsage, 1);
*copy = usage;
g_hash_table_replace (volumes, key, copy);
key = NULL;
}
}
g_free (actual_device);
g_free (key);
g_free (device);
g_free (mountpoint);
g_free (filesystem);
g_free (source);
}
g_hash_table_iter_init (&iter, volumes);
while (g_hash_table_iter_next (&iter, NULL, &value))
{
const StorageUsage *usage = value;
if (usage->total > G_MAXUINT64 - aggregate.total)
{
aggregate.total = 0;
break;
}
aggregate.total += usage->total;
aggregate.available += usage->available;
}
g_hash_table_unref (volumes);
g_strfreev (lines);
g_free (mountinfo);
if (aggregate.total)
return format_scoped_usage (&aggregate, "mounted local filesystems");
}
/* Containers and unusual filesystems may not expose block identities.
* Do not describe this limited view as the whole machine's capacity. */
if (!path || !path[0])
path = "/";
if (!read_usage (path, &aggregate))
return NULL; return NULL;
return format_scoped_usage (&aggregate, flatpak ? "app data filesystem" : "home filesystem"); result = sysinfo_linux_boot_disk ("/sys", mountinfo);
g_free (mountinfo);
return result;
} }
+2 -3
View File
@@ -4,8 +4,7 @@
#include <glib.h> #include <glib.h>
/* The returned strings are owned by the caller. */ /* Returns the whole boot disk size, or NULL if it cannot be identified. */
gboolean sysinfo_linux_mountinfo_parse (const char *line, char **device, char *sysinfo_linux_boot_disk (const char *sysfs, const char *mountinfo);
char **mountpoint, char **filesystem, char **source);
#endif #endif