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