2 * SPDX-License-Identifier: BSD-3-Clause
4 * Copyright (c) 1980, 1993
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34 static const char copyright[] =
35 "@(#) Copyright (c) 1980, 1993\n\
36 The Regents of the University of California. All rights reserved.\n";
40 static char sccsid[] = "@(#)swapon.c 8.1 (Berkeley) 6/5/93";
43 #include <sys/cdefs.h>
44 __FBSDID("$FreeBSD$");
46 #include <sys/param.h>
48 #include <sys/mdioctl.h>
50 #include <sys/sysctl.h>
52 #include <vm/vm_param.h>
69 static void usage(void);
70 static const char *swap_on_off(const char *, int, char *);
71 static const char *swap_on_off_gbde(const char *, int);
72 static const char *swap_on_off_geli(const char *, char *, int);
73 static const char *swap_on_off_md(const char *, char *, int);
74 static const char *swap_on_off_sfile(const char *, int);
75 static void swaplist(int, int, int);
76 static int run_cmd(int *, const char *, ...) __printflike(2, 3);
78 static enum { SWAPON, SWAPOFF, SWAPCTL } orig_prog, which_prog = SWAPCTL;
80 static int Eflag, qflag;
83 main(int argc, char **argv)
89 int sflag, lflag, late, hflag;
90 const char *etc_fstab;
92 sflag = lflag = late = hflag = 0;
93 if ((ptr = strrchr(argv[0], '/')) == NULL)
95 if (strstr(ptr, "swapon") != NULL)
97 else if (strstr(ptr, "swapoff") != NULL)
99 orig_prog = which_prog;
103 while ((ch = getopt(argc, argv, "AadEghklLmqsUF:")) != -1) {
106 if (which_prog == SWAPCTL) {
113 if (which_prog == SWAPON || which_prog == SWAPOFF)
119 if (which_prog == SWAPCTL)
120 which_prog = SWAPOFF;
125 if (which_prog == SWAPON)
149 if (which_prog == SWAPON || which_prog == SWAPOFF)
156 if (which_prog == SWAPCTL) {
158 which_prog = SWAPOFF;
174 if (etc_fstab != NULL)
176 if (which_prog == SWAPON || which_prog == SWAPOFF) {
178 while ((fsp = getfsent()) != NULL) {
179 if (strcmp(fsp->fs_type, FSTAB_SW) != 0)
181 if (strstr(fsp->fs_mntops, "noauto") != NULL)
183 if (which_prog != SWAPOFF &&
184 strstr(fsp->fs_mntops, "late") &&
187 if (which_prog == SWAPOFF &&
188 strstr(fsp->fs_mntops, "late") == NULL &&
191 Eflag |= (strstr(fsp->fs_mntops, "trimonce") != NULL);
192 swfile = swap_on_off(fsp->fs_spec, 1,
195 if (swfile == NULL) {
200 printf("%s: %sing %s as swap device\n",
202 (which_prog == SWAPOFF) ?
203 "remov" : "add", swfile);
206 } else if (*argv == NULL)
208 for (; *argv; ++argv) {
209 swfile = swap_on_off(*argv, 0, NULL);
210 if (swfile == NULL) {
214 if (orig_prog == SWAPCTL) {
215 printf("%s: %sing %s as swap device\n",
217 (which_prog == SWAPOFF) ? "remov" : "add",
223 swaplist(lflag, sflag, hflag);
231 swap_on_off(const char *name, int doingall, char *mntops)
233 char *base, *basebuf;
235 /* Swap on vnode-backed md(4) device. */
236 if (mntops != NULL &&
237 (fnmatch(_PATH_DEV MD_NAME "[0-9]*", name, 0) == 0 ||
238 fnmatch(MD_NAME "[0-9]*", name, 0) == 0 ||
239 strncmp(_PATH_DEV MD_NAME, name,
240 sizeof(_PATH_DEV) + sizeof(MD_NAME)) == 0 ||
241 strncmp(MD_NAME, name, sizeof(MD_NAME)) == 0))
242 return (swap_on_off_md(name, mntops, doingall));
244 basebuf = strdup(name);
245 base = basename(basebuf);
247 /* Swap on encrypted device by GEOM_BDE. */
248 if (fnmatch("*.bde", base, 0) == 0) {
250 return (swap_on_off_gbde(name, doingall));
253 /* Swap on encrypted device by GEOM_ELI. */
254 if (fnmatch("*.eli", base, 0) == 0) {
256 return (swap_on_off_geli(name, mntops, doingall));
259 /* Swap on special file. */
261 return (swap_on_off_sfile(name, doingall));
264 /* Strip off .bde or .eli suffix from swap device name */
266 swap_basename(const char *name)
270 dname = strdup(name);
271 p = strrchr(dname, '.');
272 /* assert(p != NULL); */
279 swap_on_off_gbde(const char *name, int doingall)
282 char pass[64 * 2 + 1];
283 unsigned char bpass[64];
287 dname = swap_basename(name);
291 if (which_prog == SWAPON) {
292 arc4random_buf(bpass, sizeof(bpass));
293 for (i = 0; i < (int)sizeof(bpass); i++)
294 sprintf(&pass[2 * i], "%02x", bpass[i]);
295 pass[sizeof(pass) - 1] = '\0';
297 error = run_cmd(NULL, "%s init %s -P %s", _PATH_GBDE,
300 /* bde device found. Ignore it. */
303 warnx("%s: Device already in use", name);
306 error = run_cmd(NULL, "%s attach %s -p %s", _PATH_GBDE,
310 warnx("gbde (attach) error: %s", name);
315 ret = swap_on_off_sfile(name, doingall);
317 if (which_prog == SWAPOFF) {
318 error = run_cmd(NULL, "%s detach %s", _PATH_GBDE, dname);
321 /* bde device not found. Ignore it. */
323 warnx("%s: Device not found", name);
331 /* Build geli(8) arguments from mntops */
333 swap_on_geli_args(const char *mntops)
335 const char *aalgo, *ealgo, *keylen_str, *sectorsize_str;
336 const char *aflag, *eflag, *lflag, *Tflag, *sflag;
337 char *p, *args, *token, *string, *ops;
342 /* Use built-in defaults for geli(8). */
343 aalgo = ealgo = keylen_str = "";
344 aflag = eflag = lflag = Tflag = "";
346 /* We will always specify sectorsize. */
348 sectorsize_str = NULL;
350 if (mntops != NULL) {
351 string = ops = strdup(mntops);
353 while ((token = strsep(&string, ",")) != NULL) {
354 if ((p = strstr(token, "aalgo=")) == token) {
355 aalgo = p + sizeof("aalgo=") - 1;
357 } else if ((p = strstr(token, "ealgo=")) == token) {
358 ealgo = p + sizeof("ealgo=") - 1;
360 } else if ((p = strstr(token, "keylen=")) == token) {
361 keylen_str = p + sizeof("keylen=") - 1;
363 ul = strtoul(keylen_str, &p, 10);
365 if (*p != '\0' || ul > INT_MAX)
369 warn("Invalid keylen: %s", keylen_str);
374 } else if ((p = strstr(token, "sectorsize=")) == token) {
375 sectorsize_str = p + sizeof("sectorsize=") - 1;
377 ul = strtoul(sectorsize_str, &p, 10);
379 if (*p != '\0' || ul > INT_MAX)
383 warn("Invalid sectorsize: %s",
388 } else if (strcmp(token, "notrim") == 0) {
390 warn("Options \"notrim\" and "
391 "\"trimonce\" conflict");
396 } else if (strcmp(token, "late") == 0) {
397 /* ignore known option */
398 } else if (strcmp(token, "noauto") == 0) {
399 /* ignore known option */
400 } else if (strcmp(token, "sw") == 0) {
401 /* ignore known option */
402 } else if (strcmp(token, "trimonce") == 0) {
403 /* ignore known option */
405 warnx("Invalid option: %s", token);
414 * If we do not have a sector size at this point, fill in
415 * pagesize as sector size.
417 if (sectorsize_str == NULL) {
418 /* Use pagesize as default sectorsize. */
419 pagesize = getpagesize();
420 pagesize_len = snprintf(NULL, 0, "%d", pagesize) + 1;
421 p = alloca(pagesize_len);
422 snprintf(p, pagesize_len, "%d", pagesize);
426 (void)asprintf(&args, "%s%s%s%s%s%s%s%s%s -d",
427 aflag, aalgo, eflag, ealgo, lflag, keylen_str, Tflag,
428 sflag, sectorsize_str);
435 swap_on_off_geli(const char *name, char *mntops, int doingall)
441 error = stat(name, &sb);
443 if (which_prog == SWAPON) do {
444 /* Skip if the .eli device already exists. */
448 args = swap_on_geli_args(mntops);
452 dname = swap_basename(name);
458 error = run_cmd(NULL, "%s onetime%s %s", _PATH_GELI, args,
465 /* error occurred during creation. */
467 warnx("%s: Invalid parameters", name);
472 return (swap_on_off_sfile(name, doingall));
476 swap_on_off_md(const char *name, char *mntops, int doingall)
479 int fd, mdunit, error;
481 static char mdpath[PATH_MAX], linebuf[PATH_MAX];
488 if (strlen(name) == (sizeof(MD_NAME) - 1))
492 ul = strtoul(name + 2, &p, 10);
494 if (*p != '\0' || ul > INT_MAX)
498 warn("Bad device unit: %s", name);
505 if ((p = strstr(mntops, "file=")) != NULL) {
506 vnodefile = strdup(p + sizeof("file=") - 1);
507 p = strchr(vnodefile, ',');
511 if (vnodefile == NULL) {
512 warnx("file option not found for %s", name);
516 if (which_prog == SWAPON) {
518 error = run_cmd(&fd, "%s -l -n -f %s",
519 _PATH_MDCONFIG, vnodefile);
521 /* md device found. Ignore it. */
524 warnx("%s: Device already in use",
529 error = run_cmd(&fd, "%s -a -t vnode -n -f %s",
530 _PATH_MDCONFIG, vnodefile);
532 warnx("mdconfig (attach) error: file=%s",
537 sfd = fdopen(fd, "r");
539 warn("mdconfig (attach) fdopen error");
543 p = fgetln(sfd, &linelen);
545 (linelen < 2 || linelen > sizeof(linebuf))) {
546 warn("mdconfig (attach) unexpected output");
550 strncpy(linebuf, p, linelen);
551 linebuf[linelen - 1] = '\0';
553 ul = strtoul(linebuf, &p, 10);
555 if (*p != '\0' || ul > INT_MAX)
559 warn("mdconfig (attach) unexpected output: %s",
566 error = run_cmd(&fd, "%s -l -n -f %s -u %d",
567 _PATH_MDCONFIG, vnodefile, mdunit);
569 /* md device found. Ignore it. */
572 warnx("md%d on %s: Device already "
573 "in use", mdunit, vnodefile);
577 error = run_cmd(NULL, "%s -a -t vnode -u %d -f %s",
578 _PATH_MDCONFIG, mdunit, vnodefile);
580 warnx("mdconfig (attach) error: "
581 "md%d on file=%s", mdunit, vnodefile);
586 } else /* SWAPOFF */ {
588 error = run_cmd(&fd, "%s -l -n -f %s",
589 _PATH_MDCONFIG, vnodefile);
591 /* md device not found. Ignore it. */
594 warnx("md on %s: Device not found",
599 sfd = fdopen(fd, "r");
601 warn("mdconfig (list) fdopen error");
605 p = fgetln(sfd, &linelen);
607 (linelen < 2 || linelen > sizeof(linebuf) - 1)) {
608 warn("mdconfig (list) unexpected output");
612 strncpy(linebuf, p, linelen);
613 linebuf[linelen - 1] = '\0';
614 p = strchr(linebuf, ' ');
618 ul = strtoul(linebuf, &p, 10);
620 if (*p != '\0' || ul > INT_MAX)
624 warn("mdconfig (list) unexpected output: %s",
631 error = run_cmd(&fd, "%s -l -n -f %s -u %d",
632 _PATH_MDCONFIG, vnodefile, mdunit);
634 /* md device not found. Ignore it. */
637 warnx("md%d on %s: Device not found",
644 snprintf(mdpath, sizeof(mdpath), "%s%s%d", _PATH_DEV,
646 mdpath[sizeof(mdpath) - 1] = '\0';
647 ret = swap_on_off_sfile(mdpath, doingall);
649 if (which_prog == SWAPOFF) {
651 error = run_cmd(NULL, "%s -d -u %d",
652 _PATH_MDCONFIG, mdunit);
654 warn("mdconfig (detach) detach failed: %s%s%d",
655 _PATH_DEV, MD_NAME, mdunit);
668 run_cmd(int *ofd, const char *cmdline, ...)
671 char **argv, **argvp, *cmd, *p;
672 int argc, pid, status, rv;
673 int pfd[2], nfd, dup2dn;
675 va_start(ap, cmdline);
676 rv = vasprintf(&cmd, cmdline, ap);
678 warn("%s", __func__);
684 for (argc = 1, p = cmd; (p = strchr(p, ' ')) != NULL; p++)
686 argv = (char **)malloc(sizeof(*argv) * (argc + 1));
687 for (p = cmd, argvp = argv; (*argvp = strsep(&p, " ")) != NULL;)
688 if (**argvp != '\0' && (++argvp > &argv[argc])) {
692 /* The argv array ends up NULL-terminated here. */
697 fprintf(stderr, "DEBUG: running:");
698 /* Should be equivalent to 'cmd' (before strsep, of course). */
699 for (i = 0; argv[i] != NULL; i++)
700 fprintf(stderr, " %s", argv[i]);
701 fprintf(stderr, "\n");
706 if (pipe(&pfd[0]) == -1) {
707 warn("%s: pipe", __func__);
718 if (dup2(pfd[1], STDOUT_FILENO) < 0)
719 err(1, "dup2 in %s", __func__);
720 nfd = open(_PATH_DEVNULL, O_RDWR);
722 err(1, "%s: open %s", __func__, _PATH_DEVNULL);
723 if (dup2(nfd, STDIN_FILENO) < 0)
724 err(1, "%s: dup2", __func__);
725 if (dup2dn && dup2(nfd, STDOUT_FILENO) < 0)
726 err(1, "%s: dup2", __func__);
727 if (dup2(nfd, STDERR_FILENO) < 0)
728 err(1, "%s: dup2", __func__);
729 execv(argv[0], argv);
730 warn("exec: %s", argv[0]);
733 err(1, "%s: fork", __func__);
737 while (waitpid(pid, &status, 0) != pid)
739 return (WEXITSTATUS(status));
743 swapon_trim(const char *name)
749 /* Open a descriptor to create a consumer of the device. */
750 fd = open(name, O_WRONLY);
752 errx(1, "Cannot open %s", name);
753 /* Find the device size. */
754 if (fstat(fd, &sb) < 0)
755 errx(1, "Cannot stat %s", name);
756 if (S_ISREG(sb.st_mode))
758 else if (S_ISCHR(sb.st_mode)) {
759 if (ioctl(fd, DIOCGMEDIASIZE, &sz) != 0)
760 err(1, "ioctl(DIOCGMEDIASIZE)");
762 errx(1, "%s has an invalid file type", name);
763 /* Trim the device. */
766 if (ioctl(fd, DIOCGDELETE, ioarg) != 0)
767 warn("ioctl(DIOCGDELETE)");
769 /* Start using the device for swapping, creating a second consumer. */
770 error = swapon(name);
773 * Do not close the device until the swap pager has attempted to create
774 * another consumer. For GELI devices created with the 'detach -l'
775 * option, removing the last consumer causes the device to be detached
776 * - that is, to disappear. This ordering ensures that the device will
777 * not be detached until swapoff is called.
784 swap_on_off_sfile(const char *name, int doingall)
788 if (which_prog == SWAPON)
789 error = Eflag ? swapon_trim(name) : swapon(name);
791 error = swapoff(name);
797 warnx("%s: Device already in use", name);
800 if (which_prog == SWAPON)
801 warnx("%s: NSWAPDEV limit reached", name);
802 else if (doingall == 0)
818 fprintf(stderr, "usage: %s ", getprogname());
821 fprintf(stderr, "[-F fstab] -aLq | [-E] file ...\n");
824 fprintf(stderr, "[-F fstab] -aLq | file ...\n");
827 fprintf(stderr, "[-AghklmsU] [-a file ... | -d file ...]\n");
834 sizetobuf(char *buf, size_t bufsize, int hflag, long long val, int hlen,
840 humanize_number(tmp, 5, (int64_t)val, "", HN_AUTOSCALE,
841 HN_B | HN_NOSPACE | HN_DECIMAL);
842 snprintf(buf, bufsize, "%*s", hlen, tmp);
844 snprintf(buf, bufsize, "%*lld", hlen, val / blocksize);
848 swaplist(int lflag, int sflag, int hflag)
850 size_t mibsize, size;
852 int hlen, mib[16], n, pagesize;
860 pagesize = getpagesize();
863 blocksize = 1024 * 1024 * 1024;
864 strlcpy(buf, "1GB-blocks", sizeof(buf));
869 strlcpy(buf, "Bytes", sizeof(buf));
874 strlcpy(buf, "1kB-blocks", sizeof(buf));
878 blocksize = 1024 * 1024;
879 strlcpy(buf, "1MB-blocks", sizeof(buf));
883 getbsize(&hlen, &blocksize);
884 snprintf(buf, sizeof(buf), "%ld-blocks", blocksize);
888 mibsize = nitems(mib);
889 if (sysctlnametomib("vm.swap_info", mib, &mibsize) == -1)
890 err(1, "sysctlnametomib()");
893 printf("%-13s %*s %*s\n",
902 if (sysctl(mib, mibsize + 1, &xsw, &size, NULL, 0) == -1)
904 if (xsw.xsw_version != XSWDEV_VERSION)
905 errx(1, "xswdev version mismatch");
907 tmp_total = (long long)xsw.xsw_nblks * pagesize;
908 tmp_used = (long long)xsw.xsw_used * pagesize;
912 sizetobuf(buf, sizeof(buf), hflag, tmp_total, hlen,
914 printf("/dev/%-8s %s ", devname(xsw.xsw_dev, S_IFCHR),
916 sizetobuf(buf, sizeof(buf), hflag, tmp_used, hlen,
925 sizetobuf(buf, sizeof(buf), hflag, total, hlen, blocksize);
926 printf("Total: %s ", buf);
927 sizetobuf(buf, sizeof(buf), hflag, used, hlen, blocksize);