From 5aa2ea7db09271aac2a4a280f933479d131866a6 Mon Sep 17 00:00:00 2001 From: David Sterba Date: Mon, 21 Aug 2023 21:26:31 +0200 Subject: [PATCH] btrfs-progs: add more helpers to read values from sysfs In some places we want to read a single u64 value from a sysfs path, or from fsid directory. Add helpers that do that in one go. Signed-off-by: David Sterba --- common/sysfs-utils.c | 38 ++++++++++++++++++++++++++++++++++++++ common/sysfs-utils.h | 4 +++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/common/sysfs-utils.c b/common/sysfs-utils.c index 9a65cf17..6bc546d9 100644 --- a/common/sysfs-utils.c +++ b/common/sysfs-utils.c @@ -94,3 +94,41 @@ int sysfs_read_file(int fd, char *buf, size_t size) return read(fd, buf, size); } +int sysfs_read_file_u64(const char *name, u64 *value) +{ + int fd = -1; + int ret; + char str[32] = { 0 }; + + fd = sysfs_open_file(name); + if (fd < 0) + return fd; + + ret = sysfs_read_file(fd, str, sizeof(str)); + if (ret < 0) + goto out; + /* Raw value in any numeric format should work, followed by a newline. */ + *value = strtoull(str, NULL, 0); +out: + close(fd); + return ret; +} + +int sysfs_read_fsid_file_u64(int fd, const char *name, u64 *value) +{ + int ret; + char str[32] = { 0 }; + + fd = sysfs_open_fsid_file(fd, name); + if (fd < 0) + return fd; + + ret = sysfs_read_file(fd, str, sizeof(str)); + if (ret < 0) + goto out; + /* Raw value in any numeric format should work, followed by a newline. */ + *value = strtoull(str, NULL, 0); +out: + close(fd); + return ret; +} diff --git a/common/sysfs-utils.h b/common/sysfs-utils.h index fba30a1e..b82e5c88 100644 --- a/common/sysfs-utils.h +++ b/common/sysfs-utils.h @@ -19,7 +19,9 @@ int sysfs_open_file(const char *name); int sysfs_open_fsid_file(int fd, const char *filename); -int sysfs_read_file(int fd, char *buf, size_t size); int sysfs_open_fsid_dir(int fd, const char *dirname); +int sysfs_read_fsid_file_u64(int fd, const char *name, u64 *value); +int sysfs_read_file(int fd, char *buf, size_t size); +int sysfs_read_file_u64(const char *name, u64 *value); #endif