xref: /freebsd/sbin/swapon/swapon.c (revision cbd30a72ca196976c1c700400ecd424baa1b9c16)
1 /*-
2  * Copyright (c) 1980, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29 
30 #if 0
31 #ifndef lint
32 static const char copyright[] =
33 "@(#) Copyright (c) 1980, 1993\n\
34 	The Regents of the University of California.  All rights reserved.\n";
35 #endif /* not lint */
36 
37 #ifndef lint
38 static char sccsid[] = "@(#)swapon.c	8.1 (Berkeley) 6/5/93";
39 #endif /* not lint */
40 #endif
41 #include <sys/cdefs.h>
42 __FBSDID("$FreeBSD$");
43 
44 #include <sys/param.h>
45 #include <sys/types.h>
46 #include <sys/mdioctl.h>
47 #include <sys/stat.h>
48 #include <sys/sysctl.h>
49 #include <sys/wait.h>
50 #include <vm/vm_param.h>
51 
52 #include <err.h>
53 #include <errno.h>
54 #include <fcntl.h>
55 #include <fnmatch.h>
56 #include <fstab.h>
57 #include <libgen.h>
58 #include <libutil.h>
59 #include <limits.h>
60 #include <paths.h>
61 #include <stdarg.h>
62 #include <stdio.h>
63 #include <stdlib.h>
64 #include <string.h>
65 #include <unistd.h>
66 
67 static void usage(void);
68 static const char *swap_on_off(const char *, int, char *);
69 static const char *swap_on_off_gbde(const char *, int);
70 static const char *swap_on_off_geli(const char *, char *, int);
71 static const char *swap_on_off_md(const char *, char *, int);
72 static const char *swap_on_off_sfile(const char *, int);
73 static void swaplist(int, int, int);
74 static int run_cmd(int *, const char *, ...) __printflike(2, 3);
75 
76 static enum { SWAPON, SWAPOFF, SWAPCTL } orig_prog, which_prog = SWAPCTL;
77 
78 static int qflag;
79 
80 int
81 main(int argc, char **argv)
82 {
83 	struct fstab *fsp;
84 	const char *swfile;
85 	char *ptr;
86 	int ret, ch, doall;
87 	int sflag, lflag, late, hflag;
88 	const char *etc_fstab;
89 
90 	sflag = lflag = late = hflag = 0;
91 	if ((ptr = strrchr(argv[0], '/')) == NULL)
92 		ptr = argv[0];
93 	if (strstr(ptr, "swapon") != NULL)
94 		which_prog = SWAPON;
95 	else if (strstr(ptr, "swapoff") != NULL)
96 		which_prog = SWAPOFF;
97 	orig_prog = which_prog;
98 
99 	doall = 0;
100 	etc_fstab = NULL;
101 	while ((ch = getopt(argc, argv, "AadghklLmqsUF:")) != -1) {
102 		switch(ch) {
103 		case 'A':
104 			if (which_prog == SWAPCTL) {
105 				doall = 1;
106 				which_prog = SWAPON;
107 			} else
108 				usage();
109 			break;
110 		case 'a':
111 			if (which_prog == SWAPON || which_prog == SWAPOFF)
112 				doall = 1;
113 			else
114 				which_prog = SWAPON;
115 			break;
116 		case 'd':
117 			if (which_prog == SWAPCTL)
118 				which_prog = SWAPOFF;
119 			else
120 				usage();
121 			break;
122 		case 'g':
123 			hflag = 'G';
124 			break;
125 		case 'h':
126 			hflag = 'H';
127 			break;
128 		case 'k':
129 			hflag = 'K';
130 			break;
131 		case 'l':
132 			lflag = 1;
133 			break;
134 		case 'L':
135 			late = 1;
136 			break;
137 		case 'm':
138 			hflag = 'M';
139 			break;
140 		case 'q':
141 			if (which_prog == SWAPON || which_prog == SWAPOFF)
142 				qflag = 1;
143 			break;
144 		case 's':
145 			sflag = 1;
146 			break;
147 		case 'U':
148 			if (which_prog == SWAPCTL) {
149 				doall = 1;
150 				which_prog = SWAPOFF;
151 			} else
152 				usage();
153 			break;
154 		case 'F':
155 			etc_fstab = optarg;
156 			break;
157 		case '?':
158 		default:
159 			usage();
160 		}
161 	}
162 	argv += optind;
163 
164 	ret = 0;
165 	swfile = NULL;
166 	if (etc_fstab != NULL)
167 		setfstab(etc_fstab);
168 	if (which_prog == SWAPON || which_prog == SWAPOFF) {
169 		if (doall) {
170 			while ((fsp = getfsent()) != NULL) {
171 				if (strcmp(fsp->fs_type, FSTAB_SW) != 0)
172 					continue;
173 				if (strstr(fsp->fs_mntops, "noauto") != NULL)
174 					continue;
175 				if (which_prog != SWAPOFF &&
176 				    strstr(fsp->fs_mntops, "late") &&
177 				    late == 0)
178 					continue;
179 				if (which_prog == SWAPOFF &&
180 				    strstr(fsp->fs_mntops, "late") == NULL &&
181 				    late != 0)
182 					continue;
183 				swfile = swap_on_off(fsp->fs_spec, 1,
184 				    fsp->fs_mntops);
185 				if (swfile == NULL) {
186 					ret = 1;
187 					continue;
188 				}
189 				if (qflag == 0) {
190 					printf("%s: %sing %s as swap device\n",
191 					    getprogname(),
192 					    (which_prog == SWAPOFF) ?
193 					    "remov" : "add", swfile);
194 				}
195 			}
196 		} else if (*argv == NULL)
197 			usage();
198 		for (; *argv; ++argv) {
199 			swfile = swap_on_off(*argv, 0, NULL);
200 			if (swfile == NULL) {
201 				ret = 1;
202 				continue;
203 			}
204 			if (orig_prog == SWAPCTL) {
205 				printf("%s: %sing %s as swap device\n",
206 				    getprogname(),
207 				    (which_prog == SWAPOFF) ? "remov" : "add",
208 				    swfile);
209 			}
210 		}
211 	} else {
212 		if (lflag || sflag)
213 			swaplist(lflag, sflag, hflag);
214 		else
215 			usage();
216 	}
217 	exit(ret);
218 }
219 
220 static const char *
221 swap_on_off(const char *name, int doingall, char *mntops)
222 {
223 	char *base, *basebuf;
224 
225 	/* Swap on vnode-backed md(4) device. */
226 	if (mntops != NULL &&
227 	    (fnmatch(_PATH_DEV MD_NAME "[0-9]*", name, 0) == 0 ||
228 	     fnmatch(MD_NAME "[0-9]*", name, 0) == 0 ||
229 	     strncmp(_PATH_DEV MD_NAME, name,
230 		sizeof(_PATH_DEV) + sizeof(MD_NAME)) == 0 ||
231 	     strncmp(MD_NAME, name, sizeof(MD_NAME)) == 0))
232 		return (swap_on_off_md(name, mntops, doingall));
233 
234 	basebuf = strdup(name);
235 	base = basename(basebuf);
236 
237 	/* Swap on encrypted device by GEOM_BDE. */
238 	if (fnmatch("*.bde", base, 0) == 0) {
239 		free(basebuf);
240 		return (swap_on_off_gbde(name, doingall));
241 	}
242 
243 	/* Swap on encrypted device by GEOM_ELI. */
244 	if (fnmatch("*.eli", base, 0) == 0) {
245 		free(basebuf);
246 		return (swap_on_off_geli(name, mntops, doingall));
247 	}
248 
249 	/* Swap on special file. */
250 	free(basebuf);
251 	return (swap_on_off_sfile(name, doingall));
252 }
253 
254 /* Strip off .bde or .eli suffix from swap device name */
255 static char *
256 swap_basename(const char *name)
257 {
258 	char *dname, *p;
259 
260 	dname = strdup(name);
261 	p = strrchr(dname, '.');
262 	/* assert(p != NULL); */
263 	*p = '\0';
264 
265 	return (dname);
266 }
267 
268 static const char *
269 swap_on_off_gbde(const char *name, int doingall)
270 {
271 	const char *ret;
272 	char pass[64 * 2 + 1];
273 	unsigned char bpass[64];
274 	char *dname;
275 	int i, error;
276 
277 	dname = swap_basename(name);
278 	if (dname == NULL)
279 		return (NULL);
280 
281 	if (which_prog == SWAPON) {
282 		arc4random_buf(bpass, sizeof(bpass));
283 		for (i = 0; i < (int)sizeof(bpass); i++)
284 			sprintf(&pass[2 * i], "%02x", bpass[i]);
285 		pass[sizeof(pass) - 1] = '\0';
286 
287 		error = run_cmd(NULL, "%s init %s -P %s", _PATH_GBDE,
288 		    dname, pass);
289 		if (error) {
290 			/* bde device found.  Ignore it. */
291 			free(dname);
292 			if (qflag == 0)
293 				warnx("%s: Device already in use", name);
294 			return (NULL);
295 		}
296 		error = run_cmd(NULL, "%s attach %s -p %s", _PATH_GBDE,
297 		    dname, pass);
298 		free(dname);
299 		if (error) {
300 			warnx("gbde (attach) error: %s", name);
301 			return (NULL);
302 		}
303 	}
304 
305 	ret = swap_on_off_sfile(name, doingall);
306 
307 	if (which_prog == SWAPOFF) {
308 		error = run_cmd(NULL, "%s detach %s", _PATH_GBDE, dname);
309 		free(dname);
310 		if (error) {
311 			/* bde device not found.  Ignore it. */
312 			if (qflag == 0)
313 				warnx("%s: Device not found", name);
314 			return (NULL);
315 		}
316 	}
317 
318 	return (ret);
319 }
320 
321 /* Build geli(8) arguments from mntops */
322 static char *
323 swap_on_geli_args(const char *mntops)
324 {
325 	const char *aalgo, *ealgo, *keylen_str, *sectorsize_str;
326 	const char *aflag, *eflag, *lflag, *Tflag, *sflag;
327 	char *p, *args, *token, *string, *ops;
328 	int pagesize;
329 	size_t pagesize_len;
330 	u_long ul;
331 
332 	/* Use built-in defaults for geli(8). */
333 	aalgo = ealgo = keylen_str = "";
334 	aflag = eflag = lflag = Tflag = "";
335 
336 	/* We will always specify sectorsize. */
337 	sflag = " -s ";
338 	sectorsize_str = NULL;
339 
340 	if (mntops != NULL) {
341 		string = ops = strdup(mntops);
342 
343 		while ((token = strsep(&string, ",")) != NULL) {
344 			if ((p = strstr(token, "aalgo=")) == token) {
345 				aalgo = p + sizeof("aalgo=") - 1;
346 				aflag = " -a ";
347 			} else if ((p = strstr(token, "ealgo=")) == token) {
348 				ealgo = p + sizeof("ealgo=") - 1;
349 				eflag = " -e ";
350 			} else if ((p = strstr(token, "keylen=")) == token) {
351 				keylen_str = p + sizeof("keylen=") - 1;
352 				errno = 0;
353 				ul = strtoul(keylen_str, &p, 10);
354 				if (errno == 0) {
355 					if (*p != '\0' || ul > INT_MAX)
356 						errno = EINVAL;
357 				}
358 				if (errno) {
359 					warn("Invalid keylen: %s", keylen_str);
360 					free(ops);
361 					return (NULL);
362 				}
363 				lflag = " -l ";
364 			} else if ((p = strstr(token, "sectorsize=")) == token) {
365 				sectorsize_str = p + sizeof("sectorsize=") - 1;
366 				errno = 0;
367 				ul = strtoul(sectorsize_str, &p, 10);
368 				if (errno == 0) {
369 					if (*p != '\0' || ul > INT_MAX)
370 						errno = EINVAL;
371 				}
372 				if (errno) {
373 					warn("Invalid sectorsize: %s",
374 					    sectorsize_str);
375 					free(ops);
376 					return (NULL);
377 				}
378 			} else if ((p = strstr(token, "notrim")) == token) {
379 				Tflag = " -T ";
380 			} else if (strcmp(token, "sw") != 0) {
381 				warnx("Invalid option: %s", token);
382 				free(ops);
383 				return (NULL);
384 			}
385 		}
386 	} else
387 		ops = NULL;
388 
389 	/*
390 	 * If we do not have a sector size at this point, fill in
391 	 * pagesize as sector size.
392 	 */
393 	if (sectorsize_str == NULL) {
394 		/* Use pagesize as default sectorsize. */
395 		pagesize = getpagesize();
396 		pagesize_len = snprintf(NULL, 0, "%d", pagesize) + 1;
397 		p = alloca(pagesize_len);
398 		snprintf(p, pagesize_len, "%d", pagesize);
399 		sectorsize_str = p;
400 	}
401 
402 	(void)asprintf(&args, "%s%s%s%s%s%s%s%s%s -d",
403 	    aflag, aalgo, eflag, ealgo, lflag, keylen_str, Tflag,
404 	    sflag, sectorsize_str);
405 
406 	free(ops);
407 	return (args);
408 }
409 
410 static const char *
411 swap_on_off_geli(const char *name, char *mntops, int doingall)
412 {
413 	struct stat sb;
414 	char *dname, *args;
415 	int error;
416 
417 	error = stat(name, &sb);
418 
419 	if (which_prog == SWAPON) do {
420 		/* Skip if the .eli device already exists. */
421 		if (error == 0)
422 			break;
423 
424 		args = swap_on_geli_args(mntops);
425 		if (args == NULL)
426 			return (NULL);
427 
428 		dname = swap_basename(name);
429 		if (dname == NULL) {
430 			free(args);
431 			return (NULL);
432 		}
433 
434 		error = run_cmd(NULL, "%s onetime%s %s", _PATH_GELI, args,
435 		    dname);
436 
437 		free(dname);
438 		free(args);
439 
440 		if (error) {
441 			/* error occurred during creation. */
442 			if (qflag == 0)
443 				warnx("%s: Invalid parameters", name);
444 			return (NULL);
445 		}
446 	} while (0);
447 
448 	return (swap_on_off_sfile(name, doingall));
449 }
450 
451 static const char *
452 swap_on_off_md(const char *name, char *mntops, int doingall)
453 {
454 	FILE *sfd;
455 	int fd, mdunit, error;
456 	const char *ret;
457 	static char mdpath[PATH_MAX], linebuf[PATH_MAX];
458 	char *p, *vnodefile;
459 	size_t linelen;
460 	u_long ul;
461 
462 	fd = -1;
463 	sfd = NULL;
464 	if (strlen(name) == (sizeof(MD_NAME) - 1))
465 		mdunit = -1;
466 	else {
467 		errno = 0;
468 		ul = strtoul(name + 2, &p, 10);
469 		if (errno == 0) {
470 			if (*p != '\0' || ul > INT_MAX)
471 				errno = EINVAL;
472 		}
473 		if (errno) {
474 			warn("Bad device unit: %s", name);
475 			return (NULL);
476 		}
477 		mdunit = (int)ul;
478 	}
479 
480 	vnodefile = NULL;
481 	if ((p = strstr(mntops, "file=")) != NULL) {
482 		vnodefile = strdup(p + sizeof("file=") - 1);
483 		p = strchr(vnodefile, ',');
484 		if (p != NULL)
485 			*p = '\0';
486 	}
487 	if (vnodefile == NULL) {
488 		warnx("file option not found for %s", name);
489 		return (NULL);
490 	}
491 
492 	if (which_prog == SWAPON) {
493 		if (mdunit == -1) {
494 			error = run_cmd(&fd, "%s -l -n -f %s",
495 			    _PATH_MDCONFIG, vnodefile);
496 			if (error == 0) {
497 				/* md device found.  Ignore it. */
498 				close(fd);
499 				if (!qflag)
500 					warnx("%s: Device already in use",
501 					    vnodefile);
502 				free(vnodefile);
503 				return (NULL);
504 			}
505 			error = run_cmd(&fd, "%s -a -t vnode -n -f %s",
506 			    _PATH_MDCONFIG, vnodefile);
507 			if (error) {
508 				warnx("mdconfig (attach) error: file=%s",
509 				    vnodefile);
510 				free(vnodefile);
511 				return (NULL);
512 			}
513 			sfd = fdopen(fd, "r");
514 			if (sfd == NULL) {
515 				warn("mdconfig (attach) fdopen error");
516 				ret = NULL;
517 				goto err;
518 			}
519 			p = fgetln(sfd, &linelen);
520 			if (p == NULL &&
521 			    (linelen < 2 || linelen > sizeof(linebuf))) {
522 				warn("mdconfig (attach) unexpected output");
523 				ret = NULL;
524 				goto err;
525 			}
526 			strncpy(linebuf, p, linelen);
527 			linebuf[linelen - 1] = '\0';
528 			errno = 0;
529 			ul = strtoul(linebuf, &p, 10);
530 			if (errno == 0) {
531 				if (*p != '\0' || ul > INT_MAX)
532 					errno = EINVAL;
533 			}
534 			if (errno) {
535 				warn("mdconfig (attach) unexpected output: %s",
536 				    linebuf);
537 				ret = NULL;
538 				goto err;
539 			}
540 			mdunit = (int)ul;
541 		} else {
542 			error = run_cmd(&fd, "%s -l -n -f %s -u %d",
543 			    _PATH_MDCONFIG, vnodefile, mdunit);
544 			if (error == 0) {
545 				/* md device found.  Ignore it. */
546 				close(fd);
547 				if (qflag == 0)
548 					warnx("md%d on %s: Device already "
549 					    "in use", mdunit, vnodefile);
550 				free(vnodefile);
551 				return (NULL);
552 			}
553 			error = run_cmd(NULL, "%s -a -t vnode -u %d -f %s",
554 			    _PATH_MDCONFIG, mdunit, vnodefile);
555 			if (error) {
556 				warnx("mdconfig (attach) error: "
557 				    "md%d on file=%s", mdunit, vnodefile);
558 				free(vnodefile);
559 				return (NULL);
560 			}
561 		}
562 	} else /* SWAPOFF */ {
563 		if (mdunit == -1) {
564 			error = run_cmd(&fd, "%s -l -n -f %s",
565 			    _PATH_MDCONFIG, vnodefile);
566 			if (error) {
567 				/* md device not found.  Ignore it. */
568 				close(fd);
569 				if (!qflag)
570 					warnx("md on %s: Device not found",
571 					    vnodefile);
572 				free(vnodefile);
573 				return (NULL);
574 			}
575 			sfd = fdopen(fd, "r");
576 			if (sfd == NULL) {
577 				warn("mdconfig (list) fdopen error");
578 				ret = NULL;
579 				goto err;
580 			}
581 			p = fgetln(sfd, &linelen);
582 			if (p == NULL &&
583 			    (linelen < 2 || linelen > sizeof(linebuf) - 1)) {
584 				warn("mdconfig (list) unexpected output");
585 				ret = NULL;
586 				goto err;
587 			}
588 			strncpy(linebuf, p, linelen);
589 			linebuf[linelen - 1] = '\0';
590 			p = strchr(linebuf, ' ');
591 			if (p != NULL)
592 				*p = '\0';
593 			errno = 0;
594 			ul = strtoul(linebuf, &p, 10);
595 			if (errno == 0) {
596 				if (*p != '\0' || ul > INT_MAX)
597 					errno = EINVAL;
598 			}
599 			if (errno) {
600 				warn("mdconfig (list) unexpected output: %s",
601 				    linebuf);
602 				ret = NULL;
603 				goto err;
604 			}
605 			mdunit = (int)ul;
606 		} else {
607 			error = run_cmd(&fd, "%s -l -n -f %s -u %d",
608 			    _PATH_MDCONFIG, vnodefile, mdunit);
609 			if (error) {
610 				/* md device not found.  Ignore it. */
611 				close(fd);
612 				if (!qflag)
613 					warnx("md%d on %s: Device not found",
614 					    mdunit, vnodefile);
615 				free(vnodefile);
616 				return (NULL);
617 			}
618 		}
619 	}
620 	snprintf(mdpath, sizeof(mdpath), "%s%s%d", _PATH_DEV,
621 	    MD_NAME, mdunit);
622 	mdpath[sizeof(mdpath) - 1] = '\0';
623 	ret = swap_on_off_sfile(mdpath, doingall);
624 
625 	if (which_prog == SWAPOFF) {
626 		if (ret != NULL) {
627 			error = run_cmd(NULL, "%s -d -u %d",
628 			    _PATH_MDCONFIG, mdunit);
629 			if (error)
630 				warn("mdconfig (detach) detach failed: %s%s%d",
631 				    _PATH_DEV, MD_NAME, mdunit);
632 		}
633 	}
634 err:
635 	if (sfd != NULL)
636 		fclose(sfd);
637 	if (fd != -1)
638 		close(fd);
639 	free(vnodefile);
640 	return (ret);
641 }
642 
643 static int
644 run_cmd(int *ofd, const char *cmdline, ...)
645 {
646 	va_list ap;
647 	char **argv, **argvp, *cmd, *p;
648 	int argc, pid, status, rv;
649 	int pfd[2], nfd, dup2dn;
650 
651 	va_start(ap, cmdline);
652 	rv = vasprintf(&cmd, cmdline, ap);
653 	if (rv == -1) {
654 		warn("%s", __func__);
655 		va_end(ap);
656 		return (rv);
657 	}
658 	va_end(ap);
659 
660 	for (argc = 1, p = cmd; (p = strchr(p, ' ')) != NULL; p++)
661 		argc++;
662 	argv = (char **)malloc(sizeof(*argv) * (argc + 1));
663 	for (p = cmd, argvp = argv; (*argvp = strsep(&p, " ")) != NULL;)
664 		if (**argvp != '\0' && (++argvp > &argv[argc])) {
665 			*argvp = NULL;
666 			break;
667 		}
668 	/* The argv array ends up NULL-terminated here. */
669 #if 0
670 	{
671 		int i;
672 
673 		fprintf(stderr, "DEBUG: running:");
674 		/* Should be equivalent to 'cmd' (before strsep, of course). */
675 		for (i = 0; argv[i] != NULL; i++)
676 			fprintf(stderr, " %s", argv[i]);
677 		fprintf(stderr, "\n");
678 	}
679 #endif
680 	dup2dn = 1;
681 	if (ofd != NULL) {
682 		if (pipe(&pfd[0]) == -1) {
683 			warn("%s: pipe", __func__);
684 			return (-1);
685 		}
686 		*ofd = pfd[0];
687 		dup2dn = 0;
688 	}
689 	pid = fork();
690 	switch (pid) {
691 	case 0:
692 		/* Child process. */
693 		if (ofd != NULL)
694 			if (dup2(pfd[1], STDOUT_FILENO) < 0)
695 				err(1, "dup2 in %s", __func__);
696 		nfd = open(_PATH_DEVNULL, O_RDWR);
697 		if (nfd == -1)
698 			err(1, "%s: open %s", __func__, _PATH_DEVNULL);
699 		if (dup2(nfd, STDIN_FILENO) < 0)
700 			err(1, "%s: dup2", __func__);
701 		if (dup2dn && dup2(nfd, STDOUT_FILENO) < 0)
702 			err(1, "%s: dup2", __func__);
703 		if (dup2(nfd, STDERR_FILENO) < 0)
704 			err(1, "%s: dup2", __func__);
705 		execv(argv[0], argv);
706 		warn("exec: %s", argv[0]);
707 		_exit(-1);
708 	case -1:
709 		err(1, "%s: fork", __func__);
710 	}
711 	free(cmd);
712 	free(argv);
713 	while (waitpid(pid, &status, 0) != pid)
714 		;
715 	return (WEXITSTATUS(status));
716 }
717 
718 static const char *
719 swap_on_off_sfile(const char *name, int doingall)
720 {
721 	int error;
722 
723 	if (which_prog == SWAPON)
724 		error = swapon(name);
725 	else /* SWAPOFF */
726 		error = swapoff(name);
727 
728 	if (error == -1) {
729 		switch (errno) {
730 		case EBUSY:
731 			if (doingall == 0)
732 				warnx("%s: Device already in use", name);
733 			break;
734 		case EINVAL:
735 			if (which_prog == SWAPON)
736 				warnx("%s: NSWAPDEV limit reached", name);
737 			else if (doingall == 0)
738 				warn("%s", name);
739 			break;
740 		default:
741 			warn("%s", name);
742 			break;
743 		}
744 		return (NULL);
745 	}
746 	return (name);
747 }
748 
749 static void
750 usage(void)
751 {
752 
753 	fprintf(stderr, "usage: %s ", getprogname());
754 	switch(orig_prog) {
755 	case SWAPON:
756 	case SWAPOFF:
757 	    fprintf(stderr, "[-F fstab] -aLq | file ...\n");
758 	    break;
759 	case SWAPCTL:
760 	    fprintf(stderr, "[-AghklmsU] [-a file ... | -d file ...]\n");
761 	    break;
762 	}
763 	exit(1);
764 }
765 
766 static void
767 sizetobuf(char *buf, size_t bufsize, int hflag, long long val, int hlen,
768     long blocksize)
769 {
770 	char tmp[16];
771 
772 	if (hflag == 'H') {
773 		humanize_number(tmp, 5, (int64_t)val, "", HN_AUTOSCALE,
774 		    HN_B | HN_NOSPACE | HN_DECIMAL);
775 		snprintf(buf, bufsize, "%*s", hlen, tmp);
776 	} else
777 		snprintf(buf, bufsize, "%*lld", hlen, val / blocksize);
778 }
779 
780 static void
781 swaplist(int lflag, int sflag, int hflag)
782 {
783 	size_t mibsize, size;
784 	struct xswdev xsw;
785 	int hlen, mib[16], n, pagesize;
786 	long blocksize;
787 	long long total = 0;
788 	long long used = 0;
789 	long long tmp_total;
790 	long long tmp_used;
791 	char buf[32];
792 
793 	pagesize = getpagesize();
794 	switch(hflag) {
795 	case 'G':
796 		blocksize = 1024 * 1024 * 1024;
797 		strlcpy(buf, "1GB-blocks", sizeof(buf));
798 		hlen = 10;
799 		break;
800 	case 'H':
801 		blocksize = -1;
802 		strlcpy(buf, "Bytes", sizeof(buf));
803 		hlen = 10;
804 		break;
805 	case 'K':
806 		blocksize = 1024;
807 		strlcpy(buf, "1kB-blocks", sizeof(buf));
808 		hlen = 10;
809 		break;
810 	case 'M':
811 		blocksize = 1024 * 1024;
812 		strlcpy(buf, "1MB-blocks", sizeof(buf));
813 		hlen = 10;
814 		break;
815 	default:
816 		getbsize(&hlen, &blocksize);
817 		snprintf(buf, sizeof(buf), "%ld-blocks", blocksize);
818 		break;
819 	}
820 
821 	mibsize = nitems(mib);
822 	if (sysctlnametomib("vm.swap_info", mib, &mibsize) == -1)
823 		err(1, "sysctlnametomib()");
824 
825 	if (lflag) {
826 		printf("%-13s %*s %*s\n",
827 		    "Device:",
828 		    hlen, buf,
829 		    hlen, "Used:");
830 	}
831 
832 	for (n = 0; ; ++n) {
833 		mib[mibsize] = n;
834 		size = sizeof xsw;
835 		if (sysctl(mib, mibsize + 1, &xsw, &size, NULL, 0) == -1)
836 			break;
837 		if (xsw.xsw_version != XSWDEV_VERSION)
838 			errx(1, "xswdev version mismatch");
839 
840 		tmp_total = (long long)xsw.xsw_nblks * pagesize;
841 		tmp_used  = (long long)xsw.xsw_used * pagesize;
842 		total += tmp_total;
843 		used  += tmp_used;
844 		if (lflag) {
845 			sizetobuf(buf, sizeof(buf), hflag, tmp_total, hlen,
846 			    blocksize);
847 			printf("/dev/%-8s %s ", devname(xsw.xsw_dev, S_IFCHR),
848 			    buf);
849 			sizetobuf(buf, sizeof(buf), hflag, tmp_used, hlen,
850 			    blocksize);
851 			printf("%s\n", buf);
852 		}
853 	}
854 	if (errno != ENOENT)
855 		err(1, "sysctl()");
856 
857 	if (sflag) {
858 		sizetobuf(buf, sizeof(buf), hflag, total, hlen, blocksize);
859 		printf("Total:        %s ", buf);
860 		sizetobuf(buf, sizeof(buf), hflag, used, hlen, blocksize);
861 		printf("%s\n", buf);
862 	}
863 }
864 
865