Fixed busybox swaponoff to not die if one of the swapfiles listed in /etc/fstab doesn...
[tomato.git] / release / src / router / busybox / util-linux / swaponoff.c
blobc988d029447f671f3a6253e9e0febcd589ca670d
1 /* vi: set sw=4 ts=4: */
2 /*
3 * Mini swapon/swapoff implementation for busybox
5 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
7 * Licensed under the GPL version 2, see the file LICENSE in this tarball.
8 */
10 #include "libbb.h"
11 #include <mntent.h>
12 #include <sys/swap.h>
14 #if ENABLE_FEATURE_MOUNT_LABEL
15 #include "volume_id.h"
16 #endif
18 #if ENABLE_FEATURE_SWAPON_PRI
19 struct globals {
20 int flags;
22 #define G (*(struct globals*)&bb_common_bufsiz1)
23 #define g_flags (G.flags)
24 #else
25 #define g_flags 0
26 #endif
28 static int swap_enable_disable(char *device)
30 int status;
31 struct stat st;
33 #if ENABLE_FEATURE_MOUNT_LABEL
34 char *tmp = NULL;
36 if (!strncmp(device, "UUID=", 5))
37 tmp = get_devname_from_uuid(device + 5);
38 else if (!strncmp(device, "LABEL=", 6))
39 tmp = get_devname_from_label(device + 6);
40 if (tmp)
41 device = tmp;
42 #endif
44 if (stat(device, &st)) {
45 bb_perror_msg("can't stat '%s'", device);
46 return 1;
49 #if ENABLE_DESKTOP
50 /* test for holes */
51 if (S_ISREG(st.st_mode))
52 if (st.st_blocks * (off_t)512 < st.st_size)
53 bb_error_msg("warning: swap file has holes");
54 #endif
56 if (applet_name[5] == 'n')
57 status = swapon(device, g_flags);
58 else
59 status = swapoff(device);
61 if (status != 0) {
62 bb_simple_perror_msg(device);
63 return 1;
66 return 0;
69 static int do_em_all(void)
71 struct mntent *m;
72 FILE *f;
73 int err;
75 f = setmntent("/etc/fstab", "r");
76 if (f == NULL)
77 bb_perror_msg_and_die("/etc/fstab");
79 err = 0;
80 while ((m = getmntent(f)) != NULL)
81 if (strcmp(m->mnt_type, MNTTYPE_SWAP) == 0)
82 err += swap_enable_disable(m->mnt_fsname);
84 endmntent(f);
86 return err;
89 int swap_on_off_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
90 int swap_on_off_main(int argc UNUSED_PARAM, char **argv)
92 int ret;
94 #if !ENABLE_FEATURE_SWAPON_PRI
95 ret = getopt32(argv, "a");
96 #else
97 opt_complementary = "p+";
98 ret = getopt32(argv, (applet_name[5] == 'n') ? "ap:" : "a", &g_flags);
100 if (ret & 2) { // -p
101 g_flags = SWAP_FLAG_PREFER |
102 ((g_flags & SWAP_FLAG_PRIO_MASK) << SWAP_FLAG_PRIO_SHIFT);
103 ret &= 1;
105 #endif
107 if (ret /* & 1: not needed */) // -a
108 return do_em_all();
110 argv += optind;
111 if (!*argv)
112 bb_show_usage();
114 /* ret = 0; redundant */
115 do {
116 ret += swap_enable_disable(*argv);
117 } while (*++argv);
119 return ret;