From 605c4899379e5e54ff79e0ec8e1594b369686d83 Mon Sep 17 00:00:00 2001 From: Joachim Wiberg Date: Tue, 26 Apr 2022 22:57:22 +0200 Subject: [PATCH] Follow-up to 57c97d8, issue #224: add swapon/swapoff fstab wrappers The swapon and swapoff commands do not support a custom fstab, they assume /etc/fstab is the only true source of swap devices and files. This change adds rudimentary (!) support for figuring out any swap device or file to use from any finit.fstab. Please note, options are not supported at the moment. Signed-off-by: Joachim Wiberg --- src/finit.c | 27 +++++++++++++++++++++++++-- src/sig.c | 30 ++++++++++++++++++++++++++++-- 2 files changed, 53 insertions(+), 4 deletions(-) diff --git a/src/finit.c b/src/finit.c index bd7fc88a..5445881e 100644 --- a/src/finit.c +++ b/src/finit.c @@ -323,6 +323,29 @@ static void fs_finalize(void) fs_mount("tmpfs", "/tmp", "tmpfs", MS_NOSUID | MS_NODEV, "mode=1777"); } +static void fs_swapon(char *cmd, size_t len) +{ + struct mntent *mnt; + FILE *fp; + + if (!whichp("swapon")) + return; + + fp = setmntent(fstab, "r"); + if (!fp) + return; + + while ((mnt = getmntent(fp))) { + if (strcmp(mnt->mnt_type, MNTTYPE_SWAP)) + continue; + + snprintf(cmd, len, "swapon %s", mnt->mnt_fsname); + run_interactive(cmd, "Enabling swap %s", mnt->mnt_fsname); + } + + endmntent(fp); +} + static void fs_mount_all(void) { char cmd[256] = "mount -na"; @@ -361,8 +384,8 @@ static void fs_mount_all(void) _d("Calling extra mount hook, after mount -a ..."); plugin_run_hooks(HOOK_MOUNT_POST); - if (whichp("swapon")) - run_interactive("swapon -ea", "Enabling system swap"); + _d("Enable any swap ..."); + fs_swapon(cmd, sizeof(cmd)); _d("Finalize, ensure common file systems are available ..."); fs_finalize(); diff --git a/src/sig.c b/src/sig.c index 36a756ae..20890fc0 100644 --- a/src/sig.c +++ b/src/sig.c @@ -70,6 +70,9 @@ */ #include +#ifdef HAVE_MNTENT_H +#include +#endif #include /* strerror() */ #include #include @@ -166,6 +169,30 @@ void mdadm_wait(void); void unmount_tmpfs(void); void unmount_regular(void); +static void fs_swapoff(void) +{ + struct mntent *mnt; + char cmd[256]; + FILE *fp; + + if (!whichp("swapoff")) + return; + + fp = setmntent(fstab, "r"); + if (!fp) + return; + + while ((mnt = getmntent(fp))) { + if (strcmp(mnt->mnt_type, MNTTYPE_SWAP)) + continue; + + snprintf(cmd, sizeof(cmd), "swapoff %s", mnt->mnt_fsname); + run_interactive(cmd, "Disabling swap %s", mnt->mnt_fsname); + } + + endmntent(fp); +} + /* * Kernel threads have no cmdline so fgets() returns NULL for them. We * also skip "special" processes, e.g. mdadm/mdmon or watchdogd that must @@ -323,8 +350,7 @@ void do_shutdown(shutop_t op) /* Unmount any tmpfs before unmounting swap ... */ unmount_tmpfs(); - if (whichp("swapoff")) - run_interactive("swapoff -a", "Disabling system swap"); + fs_swapoff(); /* ... unmount remaining regular file systems. */ unmount_regular();