[PATCH v2 2/3] libkmod/libkmod-module: add refcnt fd helper

From: Luis Chamberlain
Date: Tue Aug 10 2021 - 01:16:21 EST


The first part of kmod_module_get_refcnt() is to open the
file descriptor for the refcnt file. Add a helper to do this
as it can then be used in other cases in the library.

Signed-off-by: Luis Chamberlain <mcgrof@xxxxxxxxxx>
---
libkmod/libkmod-module.c | 37 ++++++++++++++++++++++++-------------
1 file changed, 24 insertions(+), 13 deletions(-)

diff --git a/libkmod/libkmod-module.c b/libkmod/libkmod-module.c
index 6e0ff1a..04bb4d9 100644
--- a/libkmod/libkmod-module.c
+++ b/libkmod/libkmod-module.c
@@ -1877,25 +1877,16 @@ done:
return size;
}

-/**
- * kmod_module_get_refcnt:
- * @mod: kmod module
- *
- * Get the ref count of this @mod, as returned by Linux Kernel, by reading
- * /sys filesystem.
- *
- * Returns: the reference count on success or < 0 on failure.
- */
-KMOD_EXPORT int kmod_module_get_refcnt(const struct kmod_module *mod)
+static int kmod_module_get_refcnt_fd(const struct kmod_module *mod)
{
char path[PATH_MAX];
- long refcnt;
int fd, err;

if (mod == NULL)
return -ENOENT;

snprintf(path, sizeof(path), "/sys/module/%s/refcnt", mod->name);
+
fd = open(path, O_RDONLY|O_CLOEXEC);
if (fd < 0) {
err = -errno;
@@ -1903,12 +1894,32 @@ KMOD_EXPORT int kmod_module_get_refcnt(const struct kmod_module *mod)
path, strerror(errno));
return err;
}
+ return fd;
+}
+
+/**
+ * kmod_module_get_refcnt:
+ * @mod: kmod module
+ *
+ * Get the ref count of this @mod, as returned by Linux Kernel, by reading
+ * /sys filesystem.
+ *
+ * Returns: the reference count on success or < 0 on failure.
+ */
+KMOD_EXPORT int kmod_module_get_refcnt(const struct kmod_module *mod)
+{
+ long refcnt;
+ int fd, err;
+
+ fd = kmod_module_get_refcnt_fd(mod);
+ if (fd < 0)
+ return fd;

err = read_str_long(fd, &refcnt, 10);
close(fd);
if (err < 0) {
- ERR(mod->ctx, "could not read integer from '%s': '%s'\n",
- path, strerror(-err));
+ ERR(mod->ctx, "could not read integer from '/sys/module/%s/refcnt': '%s'\n",
+ mod->name, strerror(-err));
return err;
}

--
2.30.2