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/disklabel.h>
49 #include <sys/mdioctl.h>
51 #include <sys/sysctl.h>
53 #include <vm/vm_param.h>
70 static void usage(void);
71 static const char *swap_on_off(const char *, int, char *);
72 static const char *swap_on_off_gbde(const char *, int);
73 static const char *swap_on_off_geli(const char *, char *, int);
74 static const char *swap_on_off_md(const char *, char *, int);
75 static const char *swap_on_off_sfile(const char *, int);
76 static void swaplist(int, int, int);
77 static int run_cmd(int *, const char *, ...) __printflike(2, 3);
79 static enum { SWAPON, SWAPOFF, SWAPCTL } orig_prog, which_prog = SWAPCTL;
81 static int Eflag, qflag;
84 main(int argc, char **argv)
90 int sflag, lflag, late, hflag;
91 const char *etc_fstab;
93 sflag = lflag = late = hflag = 0;
94 if ((ptr = strrchr(argv[0], '/')) == NULL)
96 if (strstr(ptr, "swapon") != NULL)
98 else if (strstr(ptr, "swapoff") != NULL)
100 orig_prog = which_prog;
104 while ((ch = getopt(argc, argv, "AadEghklLmqsUF:")) != -1) {
107 if (which_prog == SWAPCTL) {
114 if (which_prog == SWAPON || which_prog == SWAPOFF)
120 if (which_prog == SWAPCTL)
121 which_prog = SWAPOFF;
126 if (which_prog == SWAPON)
150 if (which_prog == SWAPON || which_prog == SWAPOFF)
157 if (which_prog == SWAPCTL) {
159 which_prog = SWAPOFF;
175 if (etc_fstab != NULL)
177 if (which_prog == SWAPON || which_prog == SWAPOFF) {
179 while ((fsp = getfsent()) != NULL) {
180 if (strcmp(fsp->fs_type, FSTAB_SW) != 0)
182 if (strstr(fsp->fs_mntops, "noauto") != NULL)
184 if (which_prog != SWAPOFF &&
185 strstr(fsp->fs_mntops, "late") &&
188 if (which_prog == SWAPOFF &&
189 strstr(fsp->fs_mntops, "late") == NULL &&
192 Eflag |= (strstr(fsp->fs_mntops, "trimonce") != NULL);
193 swfile = swap_on_off(fsp->fs_spec, 1,
196 if (swfile == NULL) {
201 printf("%s: %sing %s as swap device\n",
203 (which_prog == SWAPOFF) ?
204 "remov" : "add", swfile);
207 } else if (*argv == NULL)
209 for (; *argv; ++argv) {
210 swfile = swap_on_off(*argv, 0, NULL);
211 if (swfile == NULL) {
215 if (orig_prog == SWAPCTL) {
216 printf("%s: %sing %s as swap device\n",
218 (which_prog == SWAPOFF) ? "remov" : "add",
224 swaplist(lflag, sflag, hflag);
232 swap_on_off(const char *name, int doingall, char *mntops)
234 char *base, *basebuf;
236 /* Swap on vnode-backed md(4) device. */
237 if (mntops != NULL &&
238 (fnmatch(_PATH_DEV MD_NAME "[0-9]*", name, 0) == 0 ||
239 fnmatch(MD_NAME "[0-9]*", name, 0) == 0 ||
240 strncmp(_PATH_DEV MD_NAME, name,
241 sizeof(_PATH_DEV) + sizeof(MD_NAME)) == 0 ||
242 strncmp(MD_NAME, name, sizeof(MD_NAME)) == 0))
243 return (swap_on_off_md(name, mntops, doingall));
245 basebuf = strdup(name);
246 base = basename(basebuf);
248 /* Swap on encrypted device by GEOM_BDE. */
249 if (fnmatch("*.bde", base, 0) == 0) {
251 return (swap_on_off_gbde(name, doingall));
254 /* Swap on encrypted device by GEOM_ELI. */
255 if (fnmatch("*.eli", base, 0) == 0) {
257 return (swap_on_off_geli(name, mntops, doingall));
260 /* Swap on special file. */
262 return (swap_on_off_sfile(name, doingall));
265 /* Strip off .bde or .eli suffix from swap device name */
267 swap_basename(const char *name)
271 dname = strdup(name);
272 p = strrchr(dname, '.');
273 /* assert(p != NULL); */
280 swap_on_off_gbde(const char *name, int doingall)
283 char pass[64 * 2 + 1];
284 unsigned char bpass[64];
288 dname = swap_basename(name);
292 if (which_prog == SWAPON) {
293 arc4random_buf(bpass, sizeof(bpass));
294 for (i = 0; i < (int)sizeof(bpass); i++)
295 sprintf(&pass[2 * i], "%02x", bpass[i]);
296 pass[sizeof(pass) - 1] = '\0';
298 error = run_cmd(NULL, "%s init %s -P %s", _PATH_GBDE,
301 /* bde device found. Ignore it. */
304 warnx("%s: Device already in use", name);
307 error = run_cmd(NULL, "%s attach %s -p %s", _PATH_GBDE,
311 warnx("gbde (attach) error: %s", name);
316 ret = swap_on_off_sfile(name, doingall);
318 if (which_prog == SWAPOFF) {
319 error = run_cmd(NULL, "%s detach %s", _PATH_GBDE, dname);
322 /* bde device not found. Ignore it. */
324 warnx("%s: Device not found", name);
332 /* Build geli(8) arguments from mntops */
334 swap_on_geli_args(const char *mntops)
336 const char *aalgo, *ealgo, *keylen_str, *sectorsize_str;
337 const char *aflag, *eflag, *lflag, *Tflag, *sflag;
338 char *p, *args, *token, *string, *ops;
343 /* Use built-in defaults for geli(8). */
344 aalgo = ealgo = keylen_str = "";
345 aflag = eflag = lflag = Tflag = "";
347 /* We will always specify sectorsize. */
349 sectorsize_str = NULL;
351 if (mntops != NULL) {
352 string = ops = strdup(mntops);
354 while ((token = strsep(&string, ",")) != NULL) {
355 if ((p = strstr(token, "aalgo=")) == token) {
356 aalgo = p + sizeof("aalgo=") - 1;
358 } else if ((p = strstr(token, "ealgo=")) == token) {
359 ealgo = p + sizeof("ealgo=") - 1;
361 } else if ((p = strstr(token, "keylen=")) == token) {
362 keylen_str = p + sizeof("keylen=") - 1;
364 ul = strtoul(keylen_str, &p, 10);
366 if (*p != '\0' || ul > INT_MAX)
370 warn("Invalid keylen: %s", keylen_str);
375 } else if ((p = strstr(token, "sectorsize=")) == token) {
376 sectorsize_str = p + sizeof("sectorsize=") - 1;
378 ul = strtoul(sectorsize_str, &p, 10);
380 if (*p != '\0' || ul > INT_MAX)
384 warn("Invalid sectorsize: %s",
389 } else if (strcmp(token, "notrim") == 0) {
391 warn("Options \"notrim\" and "
392 "\"trimonce\" conflict");
397 } else if (strcmp(token, "late") == 0) {
398 /* ignore known option */
399 } else if (strcmp(token, "noauto") == 0) {
400 /* ignore known option */
401 } else if (strcmp(token, "sw") == 0) {
402 /* ignore known option */
403 } else if (strcmp(token, "trimonce") == 0) {
404 /* ignore known option */
406 warnx("Invalid option: %s", token);
415 * If we do not have a sector size at this point, fill in
416 * pagesize as sector size.
418 if (sectorsize_str == NULL) {
419 /* Use pagesize as default sectorsize. */
420 pagesize = getpagesize();
421 pagesize_len = snprintf(NULL, 0, "%d", pagesize) + 1;
422 p = alloca(pagesize_len);
423 snprintf(p, pagesize_len, "%d", pagesize);
427 (void)asprintf(&args, "%s%s%s%s%s%s%s%s%s -d",
428 aflag, aalgo, eflag, ealgo, lflag, keylen_str, Tflag,
429 sflag, sectorsize_str);
436 swap_on_off_geli(const char *name, char *mntops, int doingall)
442 error = stat(name, &sb);
444 if (which_prog == SWAPON) do {
445 /* Skip if the .eli device already exists. */
449 args = swap_on_geli_args(mntops);
453 dname = swap_basename(name);
459 error = run_cmd(NULL, "%s onetime%s %s", _PATH_GELI, args,
466 /* error occurred during creation. */
468 warnx("%s: Invalid parameters", name);
473 return (swap_on_off_sfile(name, doingall));
477 swap_on_off_md(const char *name, char *mntops, int doingall)
480 int fd, mdunit, error;
482 static char mdpath[PATH_MAX], linebuf[PATH_MAX];
489 if (strlen(name) == (sizeof(MD_NAME) - 1))
493 ul = strtoul(name + 2, &p, 10);
495 if (*p != '\0' || ul > INT_MAX)
499 warn("Bad device unit: %s", name);
506 if ((p = strstr(mntops, "file=")) != NULL) {
507 vnodefile = strdup(p + sizeof("file=") - 1);
508 p = strchr(vnodefile, ',');
512 if (vnodefile == NULL) {
513 warnx("file option not found for %s", name);
517 if (which_prog == SWAPON) {
519 error = run_cmd(&fd, "%s -l -n -f %s",
520 _PATH_MDCONFIG, vnodefile);
522 /* md device found. Ignore it. */
525 warnx("%s: Device already in use",
530 error = run_cmd(&fd, "%s -a -t vnode -n -f %s",
531 _PATH_MDCONFIG, vnodefile);
533 warnx("mdconfig (attach) error: file=%s",
538 sfd = fdopen(fd, "r");
540 warn("mdconfig (attach) fdopen error");
544 p = fgetln(sfd, &linelen);
546 (linelen < 2 || linelen > sizeof(linebuf))) {
547 warn("mdconfig (attach) unexpected output");
551 strlcpy(linebuf, p, linelen);
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))) {
608 warn("mdconfig (list) unexpected output");
612 strlcpy(linebuf, p, linelen);
613 p = strchr(linebuf, ' ');
617 ul = strtoul(linebuf, &p, 10);
619 if (*p != '\0' || ul > INT_MAX)
623 warn("mdconfig (list) unexpected output: %s",
630 error = run_cmd(&fd, "%s -l -n -f %s -u %d",
631 _PATH_MDCONFIG, vnodefile, mdunit);
633 /* md device not found. Ignore it. */
636 warnx("md%d on %s: Device not found",
643 snprintf(mdpath, sizeof(mdpath), "%s%s%d", _PATH_DEV,
645 mdpath[sizeof(mdpath) - 1] = '\0';
646 ret = swap_on_off_sfile(mdpath, doingall);
648 if (which_prog == SWAPOFF) {
650 error = run_cmd(NULL, "%s -d -u %d",
651 _PATH_MDCONFIG, mdunit);
653 warn("mdconfig (detach) detach failed: %s%s%d",
654 _PATH_DEV, MD_NAME, mdunit);
667 run_cmd(int *ofd, const char *cmdline, ...)
670 char **argv, **argvp, *cmd, *p;
671 int argc, pid, status, rv;
672 int pfd[2], nfd, dup2dn;
674 va_start(ap, cmdline);
675 rv = vasprintf(&cmd, cmdline, ap);
677 warn("%s", __func__);
683 for (argc = 1, p = cmd; (p = strchr(p, ' ')) != NULL; p++)
685 argv = (char **)malloc(sizeof(*argv) * (argc + 1));
686 for (p = cmd, argvp = argv; (*argvp = strsep(&p, " ")) != NULL;)
687 if (**argvp != '\0' && (++argvp > &argv[argc])) {
691 /* The argv array ends up NULL-terminated here. */
696 fprintf(stderr, "DEBUG: running:");
697 /* Should be equivalent to 'cmd' (before strsep, of course). */
698 for (i = 0; argv[i] != NULL; i++)
699 fprintf(stderr, " %s", argv[i]);
700 fprintf(stderr, "\n");
705 if (pipe(&pfd[0]) == -1) {
706 warn("%s: pipe", __func__);
717 if (dup2(pfd[1], STDOUT_FILENO) < 0)
718 err(1, "dup2 in %s", __func__);
719 nfd = open(_PATH_DEVNULL, O_RDWR);
721 err(1, "%s: open %s", __func__, _PATH_DEVNULL);
722 if (dup2(nfd, STDIN_FILENO) < 0)
723 err(1, "%s: dup2", __func__);
724 if (dup2dn && dup2(nfd, STDOUT_FILENO) < 0)
725 err(1, "%s: dup2", __func__);
726 if (dup2(nfd, STDERR_FILENO) < 0)
727 err(1, "%s: dup2", __func__);
728 execv(argv[0], argv);
729 warn("exec: %s", argv[0]);
732 err(1, "%s: fork", __func__);
736 while (waitpid(pid, &status, 0) != pid)
738 return (WEXITSTATUS(status));
742 swapon_trim(const char *name)
748 /* Open a descriptor to create a consumer of the device. */
749 fd = open(name, O_WRONLY);
751 errx(1, "Cannot open %s", name);
752 /* Find the device size. */
753 if (fstat(fd, &sb) < 0)
754 errx(1, "Cannot stat %s", name);
755 if (S_ISREG(sb.st_mode))
757 else if (S_ISCHR(sb.st_mode)) {
758 if (ioctl(fd, DIOCGMEDIASIZE, &sz) != 0)
759 err(1, "ioctl(DIOCGMEDIASIZE)");
761 errx(1, "%s has an invalid file type", name);
762 /* Trim the device. */
764 ioarg[1] = sz - BBSIZE;
765 if (ioctl(fd, DIOCGDELETE, ioarg) != 0)
766 warn("ioctl(DIOCGDELETE)");
768 /* Start using the device for swapping, creating a second consumer. */
769 error = swapon(name);
772 * Do not close the device until the swap pager has attempted to create
773 * another consumer. For GELI devices created with the 'detach -l'
774 * option, removing the last consumer causes the device to be detached
775 * - that is, to disappear. This ordering ensures that the device will
776 * not be detached until swapoff is called.
783 swap_on_off_sfile(const char *name, int doingall)
787 if (which_prog == SWAPON)
788 error = Eflag ? swapon_trim(name) : swapon(name);
790 error = swapoff(name);
796 warnx("%s: Device already in use", name);
799 if (which_prog == SWAPON)
800 warnx("%s: NSWAPDEV limit reached", name);
801 else if (doingall == 0)
817 fprintf(stderr, "usage: %s ", getprogname());
820 fprintf(stderr, "[-F fstab] -aLq | [-E] file ...\n");
823 fprintf(stderr, "[-F fstab] -aLq | file ...\n");
826 fprintf(stderr, "[-AghklmsU] [-a file ... | -d file ...]\n");
833 sizetobuf(char *buf, size_t bufsize, int hflag, long long val, int hlen,
839 humanize_number(tmp, 5, (int64_t)val, "", HN_AUTOSCALE,
840 HN_B | HN_NOSPACE | HN_DECIMAL);
841 snprintf(buf, bufsize, "%*s", hlen, tmp);
843 snprintf(buf, bufsize, "%*lld", hlen, val / blocksize);
847 swaplist(int lflag, int sflag, int hflag)
849 size_t mibsize, size;
851 int hlen, mib[16], n, pagesize;
859 pagesize = getpagesize();
862 blocksize = 1024 * 1024 * 1024;
863 strlcpy(buf, "1GB-blocks", sizeof(buf));
868 strlcpy(buf, "Bytes", sizeof(buf));
873 strlcpy(buf, "1kB-blocks", sizeof(buf));
877 blocksize = 1024 * 1024;
878 strlcpy(buf, "1MB-blocks", sizeof(buf));
882 getbsize(&hlen, &blocksize);
883 snprintf(buf, sizeof(buf), "%ld-blocks", blocksize);
887 mibsize = nitems(mib);
888 if (sysctlnametomib("vm.swap_info", mib, &mibsize) == -1)
889 err(1, "sysctlnametomib()");
892 printf("%-13s %*s %*s\n",
901 if (sysctl(mib, mibsize + 1, &xsw, &size, NULL, 0) == -1)
903 if (xsw.xsw_version != XSWDEV_VERSION)
904 errx(1, "xswdev version mismatch");
906 tmp_total = (long long)xsw.xsw_nblks * pagesize;
907 tmp_used = (long long)xsw.xsw_used * pagesize;
911 sizetobuf(buf, sizeof(buf), hflag, tmp_total, hlen,
913 printf("/dev/%-8s %s ", devname(xsw.xsw_dev, S_IFCHR),
915 sizetobuf(buf, sizeof(buf), hflag, tmp_used, hlen,
924 sizetobuf(buf, sizeof(buf), hflag, total, hlen, blocksize);
925 printf("Total: %s ", buf);
926 sizetobuf(buf, sizeof(buf), hflag, used, hlen, blocksize);