xref: /freebsd/sbin/sysctl/sysctl.c (revision 6193855fc76c591ffabe6168cd674e6ec0dafa8e)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 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 #include <sys/param.h>
33 #include <sys/time.h>
34 #include <sys/resource.h>
35 #include <sys/stat.h>
36 #include <sys/sysctl.h>
37 #include <sys/vmmeter.h>
38 #include <dev/evdev/input.h>
39 
40 #ifdef __amd64__
41 #include <sys/efi.h>
42 #include <machine/metadata.h>
43 #endif
44 
45 #if defined(__amd64__) || defined(__i386__)
46 #include <machine/pc/bios.h>
47 #endif
48 
49 #include <assert.h>
50 #include <ctype.h>
51 #include <err.h>
52 #include <errno.h>
53 #include <inttypes.h>
54 #include <locale.h>
55 #include <stdbool.h>
56 #include <stdio.h>
57 #include <stdlib.h>
58 #include <string.h>
59 #include <sysexits.h>
60 #include <unistd.h>
61 
62 static const char *conffile;
63 
64 static int	aflag, bflag, Bflag, dflag, eflag, hflag, iflag;
65 static int	Nflag, nflag, oflag, qflag, tflag, Tflag, Wflag, xflag;
66 static bool	Fflag, Jflag, lflag, Vflag;
67 
68 static int	oidfmt(int *, int, char *, u_int *);
69 static int	parsefile(FILE *);
70 static int	parse(const char *, int);
71 static int	show_var(int *, int, bool);
72 static int	sysctl_all(int *, int);
73 static int	name2oid(const char *, int *);
74 
75 static int	strIKtoi(const char *, char **, const char *);
76 
77 static int ctl_sign[CTLTYPE+1] = {
78 	[CTLTYPE_INT] = 1,
79 	[CTLTYPE_LONG] = 1,
80 	[CTLTYPE_S8] = 1,
81 	[CTLTYPE_S16] = 1,
82 	[CTLTYPE_S32] = 1,
83 	[CTLTYPE_S64] = 1,
84 };
85 
86 static int ctl_size[CTLTYPE+1] = {
87 	[CTLTYPE_INT] = sizeof(int),
88 	[CTLTYPE_UINT] = sizeof(u_int),
89 	[CTLTYPE_LONG] = sizeof(long),
90 	[CTLTYPE_ULONG] = sizeof(u_long),
91 	[CTLTYPE_S8] = sizeof(int8_t),
92 	[CTLTYPE_S16] = sizeof(int16_t),
93 	[CTLTYPE_S32] = sizeof(int32_t),
94 	[CTLTYPE_S64] = sizeof(int64_t),
95 	[CTLTYPE_U8] = sizeof(uint8_t),
96 	[CTLTYPE_U16] = sizeof(uint16_t),
97 	[CTLTYPE_U32] = sizeof(uint32_t),
98 	[CTLTYPE_U64] = sizeof(uint64_t),
99 };
100 
101 static const char *ctl_typename[CTLTYPE+1] = {
102 	[CTLTYPE_INT] = "integer",
103 	[CTLTYPE_UINT] = "unsigned integer",
104 	[CTLTYPE_LONG] = "long integer",
105 	[CTLTYPE_ULONG] = "unsigned long",
106 	[CTLTYPE_U8] = "uint8_t",
107 	[CTLTYPE_U16] = "uint16_t",
108 	[CTLTYPE_U32] = "uint32_t",
109 	[CTLTYPE_U64] = "uint64_t",
110 	[CTLTYPE_S8] = "int8_t",
111 	[CTLTYPE_S16] = "int16_t",
112 	[CTLTYPE_S32] = "int32_t",
113 	[CTLTYPE_S64] = "int64_t",
114 	[CTLTYPE_NODE] = "node",
115 	[CTLTYPE_STRING] = "string",
116 	[CTLTYPE_OPAQUE] = "opaque",
117 };
118 
119 static void
120 usage(void)
121 {
122 
123 	(void)fprintf(stderr, "%s\n%s\n",
124 	    "usage: sysctl [-bdeFhiJlNnoqTtVWx] [ -B <bufsize> ] [-f filename] name[=value] ...",
125 	    "       sysctl [-bdeFhJlNnoqTtVWx] [ -B <bufsize> ] -a");
126 	exit(1);
127 }
128 
129 int
130 main(int argc, char **argv)
131 {
132 	int ch;
133 	int warncount = 0;
134 	FILE *file = NULL;
135 
136 	setlocale(LC_NUMERIC, "");
137 	setbuf(stdout,0);
138 	setbuf(stderr,0);
139 
140 	while ((ch = getopt(argc, argv, "AaB:bdeFf:hiJlNnoqTtVWwXx")) != -1) {
141 		switch (ch) {
142 		case 'A':
143 			/* compatibility */
144 			aflag = oflag = 1;
145 			break;
146 		case 'a':
147 			aflag = 1;
148 			break;
149 		case 'B':
150 			Bflag = strtol(optarg, NULL, 0);
151 			break;
152 		case 'b':
153 			bflag = 1;
154 			break;
155 		case 'd':
156 			dflag = 1;
157 			break;
158 		case 'e':
159 			eflag = 1;
160 			break;
161 		case 'F':
162 			Fflag = true;
163 			break;
164 		case 'f':
165 			conffile = optarg;
166 			break;
167 		case 'h':
168 			hflag = 1;
169 			break;
170 		case 'i':
171 			iflag = 1;
172 			break;
173 		case 'J':
174 			Jflag = true;
175 			break;
176 		case 'l':
177 			lflag = true;
178 			break;
179 		case 'N':
180 			Nflag = 1;
181 			break;
182 		case 'n':
183 			nflag = 1;
184 			break;
185 		case 'o':
186 			oflag = 1;
187 			break;
188 		case 'q':
189 			qflag = 1;
190 			break;
191 		case 'T':
192 			Tflag = 1;
193 			break;
194 		case 't':
195 			tflag = 1;
196 			break;
197 		case 'V':
198 			Vflag = true;
199 			break;
200 		case 'W':
201 			Wflag = 1;
202 			break;
203 		case 'w':
204 			/* compatibility */
205 			/* ignored */
206 			break;
207 		case 'X':
208 			/* compatibility */
209 			aflag = xflag = 1;
210 			break;
211 		case 'x':
212 			xflag = 1;
213 			break;
214 		default:
215 			usage();
216 		}
217 	}
218 	argc -= optind;
219 	argv += optind;
220 
221 	/* Nflag is name only and doesn't make sense to combine with these */
222 	/* TODO: few other combinations do not make sense but come back later */
223 	if (Nflag && (lflag || nflag))
224 		usage();
225 	if (aflag && argc == 0)
226 		exit(sysctl_all(NULL, 0));
227 	if (argc == 0 && conffile == NULL)
228 		usage();
229 
230 	if (conffile != NULL) {
231 		file = fopen(conffile, "r");
232 		if (file == NULL)
233 			err(EX_NOINPUT, "%s", conffile);
234 		warncount += parsefile(file);
235 		fclose(file);
236 	}
237 
238 	while (argc-- > 0)
239 		warncount += parse(*argv++, 0);
240 
241 	return (warncount);
242 }
243 
244 /*
245  * Parse a single numeric value, append it to 'newbuf', and update
246  * 'newsize'.  Returns true if the value was parsed and false if the
247  * value was invalid.  Non-numeric types (strings) are handled
248  * directly in parse().
249  */
250 static bool
251 parse_numeric(const char *newvalstr, const char *fmt, u_int kind,
252     void **newbufp, size_t *newsizep)
253 {
254 	void *newbuf;
255 	const void *newval;
256 	int8_t i8val;
257 	uint8_t u8val;
258 	int16_t i16val;
259 	uint16_t u16val;
260 	int32_t i32val;
261 	uint32_t u32val;
262 	int intval;
263 	unsigned int uintval;
264 	long longval;
265 	unsigned long ulongval;
266 	int64_t i64val;
267 	uint64_t u64val;
268 	size_t valsize;
269 	char *endptr = NULL;
270 
271 	errno = 0;
272 
273 	switch (kind & CTLTYPE) {
274 	case CTLTYPE_INT:
275 		if (strncmp(fmt, "IK", 2) == 0)
276 			intval = strIKtoi(newvalstr, &endptr, fmt);
277 		else
278 			intval = (int)strtol(newvalstr, &endptr, 0);
279 		newval = &intval;
280 		valsize = sizeof(intval);
281 		break;
282 	case CTLTYPE_UINT:
283 		uintval = (int) strtoul(newvalstr, &endptr, 0);
284 		newval = &uintval;
285 		valsize = sizeof(uintval);
286 		break;
287 	case CTLTYPE_LONG:
288 		longval = strtol(newvalstr, &endptr, 0);
289 		newval = &longval;
290 		valsize = sizeof(longval);
291 		break;
292 	case CTLTYPE_ULONG:
293 		ulongval = strtoul(newvalstr, &endptr, 0);
294 		newval = &ulongval;
295 		valsize = sizeof(ulongval);
296 		break;
297 	case CTLTYPE_S8:
298 		i8val = (int8_t)strtol(newvalstr, &endptr, 0);
299 		newval = &i8val;
300 		valsize = sizeof(i8val);
301 		break;
302 	case CTLTYPE_S16:
303 		i16val = (int16_t)strtol(newvalstr, &endptr, 0);
304 		newval = &i16val;
305 		valsize = sizeof(i16val);
306 		break;
307 	case CTLTYPE_S32:
308 		i32val = (int32_t)strtol(newvalstr, &endptr, 0);
309 		newval = &i32val;
310 		valsize = sizeof(i32val);
311 		break;
312 	case CTLTYPE_S64:
313 		i64val = strtoimax(newvalstr, &endptr, 0);
314 		newval = &i64val;
315 		valsize = sizeof(i64val);
316 		break;
317 	case CTLTYPE_U8:
318 		u8val = (uint8_t)strtoul(newvalstr, &endptr, 0);
319 		newval = &u8val;
320 		valsize = sizeof(u8val);
321 		break;
322 	case CTLTYPE_U16:
323 		u16val = (uint16_t)strtoul(newvalstr, &endptr, 0);
324 		newval = &u16val;
325 		valsize = sizeof(u16val);
326 		break;
327 	case CTLTYPE_U32:
328 		u32val = (uint32_t)strtoul(newvalstr, &endptr, 0);
329 		newval = &u32val;
330 		valsize = sizeof(u32val);
331 		break;
332 	case CTLTYPE_U64:
333 		u64val = strtoumax(newvalstr, &endptr, 0);
334 		newval = &u64val;
335 		valsize = sizeof(u64val);
336 		break;
337 	default:
338 		/* NOTREACHED */
339 		abort();
340 	}
341 
342 	if (errno != 0 || endptr == newvalstr ||
343 	    (endptr != NULL && *endptr != '\0'))
344 		return (false);
345 
346 	newbuf = realloc(*newbufp, *newsizep + valsize);
347 	if (newbuf == NULL)
348 		err(1, "out of memory");
349 	memcpy((char *)newbuf + *newsizep, newval, valsize);
350 	*newbufp = newbuf;
351 	*newsizep += valsize;
352 
353 	return (true);
354 }
355 
356 /*
357  * Parse a name into a MIB entry.
358  * Lookup and print out the MIB entry if it exists.
359  * Set a new value if requested.
360  */
361 static int
362 parse(const char *string, int lineno)
363 {
364 	int len, i, j, save_errno;
365 	const void *newval;
366 	char *newvalstr = NULL;
367 	void *newbuf;
368 	size_t newsize = Bflag;
369 	int mib[CTL_MAXNAME];
370 	char *cp, *bufp, *buf, fmt[BUFSIZ], line[BUFSIZ];
371 	u_int kind;
372 
373 	if (lineno)
374 		snprintf(line, sizeof(line), " at line %d", lineno);
375 	else
376 		line[0] = '\0';
377 
378 	/*
379 	 * Split the string into name and value.
380 	 *
381 	 * Either = or : may be used as the delimiter.
382 	 * Whitespace surrounding the delimiter is trimmed.
383 	 * Quotes around the value are stripped.
384 	 */
385 	cp = buf = strdup(string);
386 	bufp = strsep(&cp, "=:");
387 	if (cp != NULL) {
388 		/* Tflag just lists tunables, do not allow assignment */
389 		if (Tflag || Wflag) {
390 			warnx("Can't set variables when using -T or -W");
391 			usage();
392 		}
393 		/* Trim whitespace before the value. */
394 		while (isspace(*cp))
395 			cp++;
396 		/* Strip a pair of " or ' if any. */
397 		switch (*cp) {
398 		case '\"':
399 		case '\'':
400 			if (cp[strlen(cp) - 1] == *cp)
401 				cp[strlen(cp) - 1] = '\0';
402 			cp++;
403 		}
404 		newvalstr = cp;
405 		newsize = strlen(cp);
406 	}
407 	/* Trim whitespace after the name. */
408 	cp = bufp + strlen(bufp) - 1;
409 	while (cp >= bufp && isspace((int)*cp)) {
410 		*cp = '\0';
411 		cp--;
412 	}
413 
414 	/*
415 	 * Check the name is a useable oid.
416 	 */
417 	len = name2oid(bufp, mib);
418 	if (len < 0) {
419 		if (iflag) {
420 			free(buf);
421 			return (0);
422 		}
423 		if (!qflag) {
424 			if (errno == ENOENT) {
425 				warnx("unknown oid '%s'%s", bufp, line);
426 			} else {
427 				warn("unknown oid '%s'%s", bufp, line);
428 			}
429 		}
430 		free(buf);
431 		return (1);
432 	}
433 
434 	if (oidfmt(mib, len, fmt, &kind)) {
435 		warn("couldn't find format of oid '%s'%s", bufp, line);
436 		free(buf);
437 		if (iflag)
438 			return (1);
439 		else
440 			exit(1);
441 	}
442 
443 	/*
444 	 * We have a useable oid to work with.  If there is no value given,
445 	 * show the node and its children.  Otherwise, set the new value.
446 	 */
447 	if (newvalstr == NULL || dflag) {
448 		free(buf);
449 		if ((kind & CTLTYPE) == CTLTYPE_NODE) {
450 			if (dflag) {
451 				i = show_var(mib, len, false);
452 				if (!i && !bflag)
453 					putchar('\n');
454 			}
455 			sysctl_all(mib, len);
456 		} else {
457 			i = show_var(mib, len, false);
458 			if (!i && !bflag)
459 				putchar('\n');
460 		}
461 		return (0);
462 	}
463 
464 	/*
465 	 * We have a new value to set.  Check its validity and parse if numeric.
466 	 */
467 	if ((kind & CTLTYPE) == CTLTYPE_NODE) {
468 		warnx("oid '%s' isn't a leaf node%s", bufp, line);
469 		free(buf);
470 		return (1);
471 	}
472 
473 	if (!(kind & CTLFLAG_WR)) {
474 		if (kind & CTLFLAG_TUN) {
475 			warnx("oid '%s' is a read only tunable%s", bufp, line);
476 			warnx("Tunable values are set in /boot/loader.conf");
477 		} else
478 			warnx("oid '%s' is read only%s", bufp, line);
479 		free(buf);
480 		return (1);
481 	}
482 
483 	switch (kind & CTLTYPE) {
484 	case CTLTYPE_INT:
485 	case CTLTYPE_UINT:
486 	case CTLTYPE_LONG:
487 	case CTLTYPE_ULONG:
488 	case CTLTYPE_S8:
489 	case CTLTYPE_S16:
490 	case CTLTYPE_S32:
491 	case CTLTYPE_S64:
492 	case CTLTYPE_U8:
493 	case CTLTYPE_U16:
494 	case CTLTYPE_U32:
495 	case CTLTYPE_U64:
496 		if (strlen(newvalstr) == 0) {
497 			warnx("empty numeric value");
498 			free(buf);
499 			return (1);
500 		}
501 		/* FALLTHROUGH */
502 	case CTLTYPE_STRING:
503 		break;
504 	default:
505 		warnx("oid '%s' is type %d, cannot set that%s",
506 		    bufp, kind & CTLTYPE, line);
507 		free(buf);
508 		return (1);
509 	}
510 
511 	newbuf = NULL;
512 
513 	switch (kind & CTLTYPE) {
514 	case CTLTYPE_STRING:
515 		newval = newvalstr;
516 		break;
517 	default:
518 		newsize = 0;
519 		while ((cp = strsep(&newvalstr, " ,")) != NULL) {
520 			if (*cp == '\0')
521 				continue;
522 			if (!parse_numeric(cp, fmt, kind, &newbuf, &newsize)) {
523 				warnx("invalid %s '%s'%s",
524 				    ctl_typename[kind & CTLTYPE], cp, line);
525 				free(newbuf);
526 				free(buf);
527 				return (1);
528 			}
529 		}
530 		newval = newbuf;
531 		break;
532 	}
533 
534 	/*
535 	 * Show the current value, then set and show the new value.
536 	 */
537 	i = show_var(mib, len, false);
538 	if (sysctl(mib, len, 0, 0, newval, newsize) == -1) {
539 		save_errno = errno;
540 		free(newbuf);
541 		free(buf);
542 		if (!i && !bflag)
543 			putchar('\n');
544 		switch (save_errno) {
545 		case EOPNOTSUPP:
546 			warnx("%s: value is not available%s",
547 			    string, line);
548 			return (1);
549 		case ENOTDIR:
550 			warnx("%s: specification is incomplete%s",
551 			    string, line);
552 			return (1);
553 		case ENOMEM:
554 			warnx("%s: type is unknown to this program%s",
555 			    string, line);
556 			return (1);
557 		default:
558 			warnc(save_errno, "%s%s", string, line);
559 			return (1);
560 		}
561 	}
562 	free(newbuf);
563 	free(buf);
564 	if (!bflag)
565 		printf(" -> ");
566 	i = nflag;
567 	nflag = 1;
568 	j = show_var(mib, len, false);
569 	if (!j && !bflag)
570 		putchar('\n');
571 	nflag = i;
572 
573 	return (0);
574 }
575 
576 static int
577 parsefile(FILE *file)
578 {
579 	char line[BUFSIZ], *p, *pq, *pdq;
580 	int warncount = 0, lineno = 0;
581 
582 	while (fgets(line, sizeof(line), file) != NULL) {
583 		lineno++;
584 		p = line;
585 		pq = strchr(line, '\'');
586 		pdq = strchr(line, '\"');
587 		/* Replace the first # with \0. */
588 		while((p = strchr(p, '#')) != NULL) {
589 			if (pq != NULL && p > pq) {
590 				if ((p = strchr(pq+1, '\'')) != NULL)
591 					*(++p) = '\0';
592 				break;
593 			} else if (pdq != NULL && p > pdq) {
594 				if ((p = strchr(pdq+1, '\"')) != NULL)
595 					*(++p) = '\0';
596 				break;
597 			} else if (p == line || *(p-1) != '\\') {
598 				*p = '\0';
599 				break;
600 			}
601 			p++;
602 		}
603 		/* Trim spaces */
604 		p = line + strlen(line) - 1;
605 		while (p >= line && isspace((int)*p)) {
606 			*p = '\0';
607 			p--;
608 		}
609 		p = line;
610 		while (isspace((int)*p))
611 			p++;
612 		if (*p == '\0')
613 			continue;
614 		else
615 			warncount += parse(p, lineno);
616 	}
617 
618 	return (warncount);
619 }
620 
621 /* These functions will dump out various interesting structures. */
622 
623 static int
624 S_clockinfo(size_t l2, void *p)
625 {
626 	struct clockinfo *ci = (struct clockinfo*)p;
627 
628 	if (l2 != sizeof(*ci)) {
629 		warnx("S_clockinfo %zu != %zu", l2, sizeof(*ci));
630 		return (1);
631 	}
632 	printf(hflag ? "{ hz = %'d, tick = %'d, profhz = %'d, stathz = %'d }" :
633 		"{ hz = %d, tick = %d, profhz = %d, stathz = %d }",
634 		ci->hz, ci->tick, ci->profhz, ci->stathz);
635 	return (0);
636 }
637 
638 static int
639 S_loadavg(size_t l2, void *p)
640 {
641 	struct loadavg *tv = (struct loadavg*)p;
642 
643 	if (l2 != sizeof(*tv)) {
644 		warnx("S_loadavg %zu != %zu", l2, sizeof(*tv));
645 		return (1);
646 	}
647 	printf(hflag ? "{ %'.2f %'.2f %'.2f }" : "{ %.2f %.2f %.2f }",
648 		(double)tv->ldavg[0]/(double)tv->fscale,
649 		(double)tv->ldavg[1]/(double)tv->fscale,
650 		(double)tv->ldavg[2]/(double)tv->fscale);
651 	return (0);
652 }
653 
654 static int
655 S_timeval(size_t l2, void *p)
656 {
657 	struct timeval *tv = (struct timeval*)p;
658 	time_t tv_sec;
659 	char *p1, *p2;
660 
661 	if (l2 != sizeof(*tv)) {
662 		warnx("S_timeval %zu != %zu", l2, sizeof(*tv));
663 		return (1);
664 	}
665 	printf(hflag ? "{ sec = %'jd, usec = %'ld } " :
666 		"{ sec = %jd, usec = %ld } ",
667 		(intmax_t)tv->tv_sec, tv->tv_usec);
668 	tv_sec = tv->tv_sec;
669 	p1 = strdup(ctime(&tv_sec));
670 	for (p2=p1; *p2 ; p2++)
671 		if (*p2 == '\n')
672 			*p2 = '\0';
673 	fputs(p1, stdout);
674 	free(p1);
675 	return (0);
676 }
677 
678 static int
679 S_vmtotal(size_t l2, void *p)
680 {
681 	struct vmtotal *v;
682 	int pageKilo;
683 
684 	if (l2 != sizeof(*v)) {
685 		warnx("S_vmtotal %zu != %zu", l2, sizeof(*v));
686 		return (1);
687 	}
688 
689 	v = p;
690 	pageKilo = getpagesize() / 1024;
691 
692 #define	pg2k(a)	((uintmax_t)(a) * pageKilo)
693 	printf("\nSystem wide totals computed every five seconds:"
694 	    " (values in kilobytes)\n");
695 	printf("===============================================\n");
696 	printf("Processes:\t\t(RUNQ: %d Disk Wait: %d Page Wait: "
697 	    "%d Sleep: %d)\n",
698 	    v->t_rq, v->t_dw, v->t_pw, v->t_sl);
699 	printf("Virtual Memory:\t\t(Total: %juK Active: %juK)\n",
700 	    pg2k(v->t_vm), pg2k(v->t_avm));
701 	printf("Real Memory:\t\t(Total: %juK Active: %juK)\n",
702 	    pg2k(v->t_rm), pg2k(v->t_arm));
703 	printf("Shared Virtual Memory:\t(Total: %juK Active: %juK)\n",
704 	    pg2k(v->t_vmshr), pg2k(v->t_avmshr));
705 	printf("Shared Real Memory:\t(Total: %juK Active: %juK)\n",
706 	    pg2k(v->t_rmshr), pg2k(v->t_armshr));
707 	printf("Free Memory:\t%juK", pg2k(v->t_free));
708 	return (0);
709 }
710 
711 static int
712 S_input_id(size_t l2, void *p)
713 {
714 	struct input_id *id = p;
715 
716 	if (l2 != sizeof(*id)) {
717 		warnx("S_input_id %zu != %zu", l2, sizeof(*id));
718 		return (1);
719 	}
720 
721 	printf("{ bustype = 0x%04x, vendor = 0x%04x, "
722 	    "product = 0x%04x, version = 0x%04x }",
723 	    id->bustype, id->vendor, id->product, id->version);
724 	return (0);
725 }
726 
727 static int
728 S_pagesizes(size_t l2, void *p)
729 {
730 	char buf[256];
731 	u_long *ps;
732 	size_t l;
733 	int i;
734 
735 	l = snprintf(buf, sizeof(buf), "{ ");
736 	ps = p;
737 	for (i = 0; i * sizeof(*ps) < l2 && ps[i] != 0 && l < sizeof(buf);
738 	    i++) {
739 		l += snprintf(&buf[l], sizeof(buf) - l,
740 		    "%s%lu", i == 0 ? "" : ", ", ps[i]);
741 	}
742 	if (l < sizeof(buf))
743 		(void)snprintf(&buf[l], sizeof(buf) - l, " }");
744 
745 	printf("%s", buf);
746 
747 	return (0);
748 }
749 
750 #ifdef __amd64__
751 static int
752 S_efi_map(size_t l2, void *p)
753 {
754 	struct efi_map_header *efihdr;
755 	struct efi_md *map;
756 	const char *type;
757 	size_t efisz;
758 	int ndesc, i;
759 
760 	static const char * const types[] = {
761 		[EFI_MD_TYPE_NULL] =	"Reserved",
762 		[EFI_MD_TYPE_CODE] =	"LoaderCode",
763 		[EFI_MD_TYPE_DATA] =	"LoaderData",
764 		[EFI_MD_TYPE_BS_CODE] =	"BootServicesCode",
765 		[EFI_MD_TYPE_BS_DATA] =	"BootServicesData",
766 		[EFI_MD_TYPE_RT_CODE] =	"RuntimeServicesCode",
767 		[EFI_MD_TYPE_RT_DATA] =	"RuntimeServicesData",
768 		[EFI_MD_TYPE_FREE] =	"ConventionalMemory",
769 		[EFI_MD_TYPE_BAD] =	"UnusableMemory",
770 		[EFI_MD_TYPE_RECLAIM] =	"ACPIReclaimMemory",
771 		[EFI_MD_TYPE_FIRMWARE] = "ACPIMemoryNVS",
772 		[EFI_MD_TYPE_IOMEM] =	"MemoryMappedIO",
773 		[EFI_MD_TYPE_IOPORT] =	"MemoryMappedIOPortSpace",
774 		[EFI_MD_TYPE_PALCODE] =	"PalCode",
775 		[EFI_MD_TYPE_PERSISTENT] = "PersistentMemory",
776 	};
777 
778 	/*
779 	 * Memory map data provided by UEFI via the GetMemoryMap
780 	 * Boot Services API.
781 	 */
782 	if (l2 < sizeof(*efihdr)) {
783 		warnx("S_efi_map length less than header");
784 		return (1);
785 	}
786 	efihdr = p;
787 	efisz = (sizeof(struct efi_map_header) + 0xf) & ~0xf;
788 	map = (struct efi_md *)((uint8_t *)efihdr + efisz);
789 
790 	if (efihdr->descriptor_size == 0)
791 		return (0);
792 	if (l2 != efisz + efihdr->memory_size) {
793 		warnx("S_efi_map length mismatch %zu vs %zu", l2, efisz +
794 		    efihdr->memory_size);
795 		return (1);
796 	}
797 	ndesc = efihdr->memory_size / efihdr->descriptor_size;
798 
799 	printf("\n%23s %12s %12s %8s %4s",
800 	    "Type", "Physical", "Virtual", "#Pages", "Attr");
801 
802 	for (i = 0; i < ndesc; i++,
803 	    map = efi_next_descriptor(map, efihdr->descriptor_size)) {
804 		type = NULL;
805 		if (map->md_type < nitems(types))
806 			type = types[map->md_type];
807 		if (type == NULL)
808 			type = "<INVALID>";
809 		printf("\n%23s %012jx %012jx %08jx ", type,
810 		    (uintmax_t)map->md_phys, (uintmax_t)map->md_virt,
811 		    (uintmax_t)map->md_pages);
812 		if (map->md_attr & EFI_MD_ATTR_UC)
813 			printf("UC ");
814 		if (map->md_attr & EFI_MD_ATTR_WC)
815 			printf("WC ");
816 		if (map->md_attr & EFI_MD_ATTR_WT)
817 			printf("WT ");
818 		if (map->md_attr & EFI_MD_ATTR_WB)
819 			printf("WB ");
820 		if (map->md_attr & EFI_MD_ATTR_UCE)
821 			printf("UCE ");
822 		if (map->md_attr & EFI_MD_ATTR_WP)
823 			printf("WP ");
824 		if (map->md_attr & EFI_MD_ATTR_RP)
825 			printf("RP ");
826 		if (map->md_attr & EFI_MD_ATTR_XP)
827 			printf("XP ");
828 		if (map->md_attr & EFI_MD_ATTR_RT)
829 			printf("RUNTIME");
830 	}
831 	return (0);
832 }
833 #endif
834 
835 #if defined(__amd64__) || defined(__i386__)
836 static int
837 S_bios_smap_xattr(size_t l2, void *p)
838 {
839 	struct bios_smap_xattr *smap, *end;
840 
841 	if (l2 % sizeof(*smap) != 0) {
842 		warnx("S_bios_smap_xattr %zu is not a multiple of %zu", l2,
843 		    sizeof(*smap));
844 		return (1);
845 	}
846 
847 	end = (struct bios_smap_xattr *)((char *)p + l2);
848 	for (smap = p; smap < end; smap++)
849 		printf("\nSMAP type=%02x, xattr=%02x, base=%016jx, len=%016jx",
850 		    smap->type, smap->xattr, (uintmax_t)smap->base,
851 		    (uintmax_t)smap->length);
852 	return (0);
853 }
854 #endif
855 
856 static int
857 strIKtoi(const char *str, char **endptrp, const char *fmt)
858 {
859 	int kelv;
860 	float temp;
861 	size_t len;
862 	const char *p;
863 	int prec, i;
864 
865 	assert(errno == 0);
866 
867 	len = strlen(str);
868 	/* caller already checked this */
869 	assert(len > 0);
870 
871 	/*
872 	 * A format of "IK" is in deciKelvin. A format of "IK3" is in
873 	 * milliKelvin. The single digit following IK is log10 of the
874 	 * multiplying factor to convert Kelvin into the untis of this sysctl,
875 	 * or the dividing factor to convert the sysctl value to Kelvin. Numbers
876 	 * larger than 6 will run into precision issues with 32-bit integers.
877 	 * Characters that aren't ASCII digits after the 'K' are ignored. No
878 	 * localization is present because this is an interface from the kernel
879 	 * to this program (eg not an end-user interface), so isdigit() isn't
880 	 * used here.
881 	 */
882 	if (fmt[2] != '\0' && fmt[2] >= '0' && fmt[2] <= '9')
883 		prec = fmt[2] - '0';
884 	else
885 		prec = 1;
886 	p = &str[len - 1];
887 	if (*p == 'C' || *p == 'F' || *p == 'K') {
888 		temp = strtof(str, endptrp);
889 		if (*endptrp != str && *endptrp == p && errno == 0) {
890 			if (*p == 'F')
891 				temp = (temp - 32) * 5 / 9;
892 			*endptrp = NULL;
893 			if (*p != 'K')
894 				temp += 273.15;
895 			for (i = 0; i < prec; i++)
896 				temp *= 10.0;
897 			return ((int)(temp + 0.5));
898 		}
899 	} else {
900 		/* No unit specified -> treat it as a raw number */
901 		kelv = (int)strtol(str, endptrp, 10);
902 		if (*endptrp != str && *endptrp == p && errno == 0) {
903 			*endptrp = NULL;
904 			return (kelv);
905 		}
906 	}
907 
908 	errno = ERANGE;
909 	return (0);
910 }
911 
912 /*
913  * These functions uses a presently undocumented interface to the kernel
914  * to walk the tree and get the type so it can print the value.
915  * This interface is under work and consideration, and should probably
916  * be killed with a big axe by the first person who can find the time.
917  * (be aware though, that the proper interface isn't as obvious as it
918  * may seem, there are various conflicting requirements.
919  */
920 
921 static int
922 name2oid(const char *name, int *oidp)
923 {
924 	int oid[2];
925 	int i;
926 	size_t j;
927 
928 	oid[0] = CTL_SYSCTL;
929 	oid[1] = CTL_SYSCTL_NAME2OID;
930 
931 	j = CTL_MAXNAME * sizeof(int);
932 	i = sysctl(oid, 2, oidp, &j, name, strlen(name));
933 	if (i < 0)
934 		return (i);
935 	j /= sizeof(int);
936 	return (j);
937 }
938 
939 static int
940 oidfmt(int *oid, int len, char *fmt, u_int *kind)
941 {
942 	int qoid[CTL_MAXNAME+2];
943 	u_char buf[BUFSIZ];
944 	int i;
945 	size_t j;
946 
947 	qoid[0] = CTL_SYSCTL;
948 	qoid[1] = CTL_SYSCTL_OIDFMT;
949 	memcpy(qoid + 2, oid, len * sizeof(int));
950 
951 	j = sizeof(buf);
952 	i = sysctl(qoid, len + 2, buf, &j, 0, 0);
953 	if (i)
954 		err(1, "sysctl fmt %d %zu %d", i, j, errno);
955 
956 	if (kind)
957 		*kind = *(u_int *)buf;
958 
959 	if (fmt)
960 		strcpy(fmt, (char *)(buf + sizeof(u_int)));
961 	return (0);
962 }
963 
964 /*
965  * This displays a combination of name, type, format, and/or description.
966  *
967  * Returns zero if anything was actually output.
968  * Returns one if there is an error.
969  */
970 static int
971 show_info(char *name, const char *sep, int ctltype, char *fmt, int *qoid, int nlen)
972 {
973 	u_char buf[BUFSIZ];
974 	const char *prntype;
975 	int error = 0, i;
976 	size_t j;
977 
978 	if (!nflag)
979 		printf("%s%s", name, sep);
980 	if (tflag) {
981 		if (ctl_typename[ctltype] != NULL)
982 			prntype = ctl_typename[ctltype];
983 		else {
984 			prntype = "unknown";
985 			error++;
986 		}
987 		if (Fflag || dflag)
988 			printf("%s%s", prntype, sep);
989 		else
990 			fputs(prntype, stdout);
991 	}
992 	if (Fflag) {
993 		if (!isprint(fmt[0])) /* Few codes doesn't have formats */
994 			fmt = "";
995 		if (dflag)
996 			printf("%s%s", fmt, sep);
997 		else
998 			fputs(fmt, stdout);
999 	}
1000 	if (!dflag)
1001 		return (error);
1002 
1003 	qoid[1] = CTL_SYSCTL_OIDDESCR;
1004 	bzero(buf, BUFSIZ);
1005 	j = sizeof(buf);
1006 	i = sysctl(qoid, nlen + 2, buf, &j, 0, 0);
1007 	if (i < 0) {
1008 		putchar('\n');
1009 		return (1);
1010 	}
1011 	fputs(buf, stdout);
1012 	return (error);
1013 }
1014 
1015 /*
1016  * This formats and outputs the value of one variable
1017  *
1018  * Returns zero if anything was actually output.
1019  * Returns one if didn't know what to do with this.
1020  * Return minus one if we had errors.
1021  */
1022 static int
1023 show_var(int *oid, int nlen, bool honor_skip)
1024 {
1025 	static int skip_len = 0, skip_oid[CTL_MAXNAME];
1026 	u_char *val, *oval, *p;
1027 	char name[BUFSIZ], fmt[BUFSIZ];
1028 	const char *sep, *sep1;
1029 	int qoid[CTL_MAXNAME+2];
1030 	uintmax_t umv;
1031 	intmax_t mv;
1032 	int i, hexlen, sign, ctltype;
1033 	size_t intlen;
1034 	size_t j, len;
1035 	u_int kind;
1036 	float base;
1037 	int (*func)(size_t, void *);
1038 	int prec;
1039 
1040 	/* Silence GCC. */
1041 	umv = mv = intlen = 0;
1042 
1043 	bzero(fmt, BUFSIZ);
1044 	bzero(name, BUFSIZ);
1045 	qoid[0] = CTL_SYSCTL;
1046 	qoid[1] = CTL_SYSCTL_NAME;
1047 	memcpy(qoid + 2, oid, nlen * sizeof(int));
1048 	j = sizeof(name);
1049 	i = sysctl(qoid, nlen + 2, name, &j, 0, 0);
1050 	if (i || !j)
1051 		err(1, "sysctl name %d %zu %d", i, j, errno);
1052 
1053 	oidfmt(oid, nlen, fmt, &kind);
1054 	/* if Wflag then only list sysctls that are writeable and not stats. */
1055 	if (Wflag && ((kind & CTLFLAG_WR) == 0 || (kind & CTLFLAG_STATS) != 0))
1056 		return (1);
1057 
1058 	/* if Jflag then only list sysctls that are prison variables. */
1059 	if (Jflag && (kind & CTLFLAG_PRISON) == 0)
1060 		return (1);
1061 
1062 	/* if Tflag then only list sysctls that are tuneables. */
1063 	if (Tflag && (kind & CTLFLAG_TUN) == 0)
1064 		return (1);
1065 
1066 	/* if Vflag then only list sysctls that are vnet variables. */
1067 	if (Vflag && (kind & CTLFLAG_VNET) == 0)
1068 		return (1);
1069 
1070 	if (Nflag) {
1071 		printf("%s", name);
1072 		return (0);
1073 	}
1074 
1075 	if (eflag)
1076 		sep = "=";
1077 	else
1078 		sep = ": ";
1079 
1080 	ctltype = (kind & CTLTYPE);
1081 	if (tflag || Fflag || dflag)
1082 		return show_info(name, sep, ctltype, fmt, qoid, nlen);
1083 
1084 	/* keep track of encountered skip nodes, ignoring descendants */
1085 	if ((skip_len == 0 || skip_len >= nlen * (int)sizeof(int)) &&
1086 	    (kind & CTLFLAG_SKIP) != 0) {
1087 		/* Save this oid so we can skip descendants. */
1088 		skip_len = nlen * sizeof(int);
1089 		memcpy(skip_oid, oid, skip_len);
1090 	}
1091 
1092 	/* bail before fetching the value if we're honoring skip */
1093 	if (honor_skip) {
1094 		if (0 < skip_len && skip_len <= nlen * (int)sizeof(int) &&
1095 		    memcmp(skip_oid, oid, skip_len) == 0)
1096 			return (1);
1097 		/* Not a skip node or descendant of a skip node. */
1098 		skip_len = 0;
1099 	}
1100 
1101 	/* don't fetch opaques that we don't know how to print */
1102 	if (ctltype == CTLTYPE_OPAQUE) {
1103 		if (strcmp(fmt, "S,clockinfo") == 0)
1104 			func = S_clockinfo;
1105 		else if (strcmp(fmt, "S,timeval") == 0)
1106 			func = S_timeval;
1107 		else if (strcmp(fmt, "S,loadavg") == 0)
1108 			func = S_loadavg;
1109 		else if (strcmp(fmt, "S,vmtotal") == 0)
1110 			func = S_vmtotal;
1111 		else if (strcmp(fmt, "S,input_id") == 0)
1112 			func = S_input_id;
1113 		else if (strcmp(fmt, "S,pagesizes") == 0)
1114 			func = S_pagesizes;
1115 #ifdef __amd64__
1116 		else if (strcmp(fmt, "S,efi_map_header") == 0)
1117 			func = S_efi_map;
1118 #endif
1119 #if defined(__amd64__) || defined(__i386__)
1120 		else if (strcmp(fmt, "S,bios_smap_xattr") == 0)
1121 			func = S_bios_smap_xattr;
1122 #endif
1123 		else {
1124 			func = NULL;
1125 			if (!bflag && !oflag && !xflag)
1126 				return (1);
1127 		}
1128 	}
1129 
1130 	/* find an estimate of how much we need for this var */
1131 	if (Bflag)
1132 		j = Bflag;
1133 	else {
1134 		j = 0;
1135 		i = sysctl(oid, nlen, 0, &j, 0, 0);
1136 		j += j; /* we want to be sure :-) */
1137 	}
1138 
1139 	val = oval = malloc(j + 1);
1140 	if (val == NULL) {
1141 		warnx("malloc failed");
1142 		return (1);
1143 	}
1144 	len = j;
1145 	i = sysctl(oid, nlen, val, &len, 0, 0);
1146 	if (i != 0 || (len == 0 && ctltype != CTLTYPE_STRING)) {
1147 		free(oval);
1148 		return (1);
1149 	}
1150 
1151 	if (bflag) {
1152 		fwrite(val, 1, len, stdout);
1153 		free(oval);
1154 		return (0);
1155 	}
1156 	val[len] = '\0';
1157 	p = val;
1158 	sign = ctl_sign[ctltype];
1159 	intlen = ctl_size[ctltype];
1160 
1161 	switch (ctltype) {
1162 	case CTLTYPE_STRING:
1163 		if (!nflag)
1164 			printf("%s%s", name, sep);
1165 		if (lflag)
1166 			printf("%zd%s", len, sep);
1167 		printf("%.*s", (int)len, p);
1168 		free(oval);
1169 		return (0);
1170 
1171 	case CTLTYPE_INT:
1172 	case CTLTYPE_UINT:
1173 	case CTLTYPE_LONG:
1174 	case CTLTYPE_ULONG:
1175 	case CTLTYPE_S8:
1176 	case CTLTYPE_S16:
1177 	case CTLTYPE_S32:
1178 	case CTLTYPE_S64:
1179 	case CTLTYPE_U8:
1180 	case CTLTYPE_U16:
1181 	case CTLTYPE_U32:
1182 	case CTLTYPE_U64:
1183 		if (!nflag)
1184 			printf("%s%s", name, sep);
1185 		if (lflag)
1186 			printf("%zd%s", len, sep);
1187 		hexlen = 2 + (intlen * CHAR_BIT + 3) / 4;
1188 		sep1 = "";
1189 		while (len >= intlen) {
1190 			switch (kind & CTLTYPE) {
1191 			case CTLTYPE_INT:
1192 			case CTLTYPE_UINT:
1193 				umv = *(u_int *)p;
1194 				mv = *(int *)p;
1195 				break;
1196 			case CTLTYPE_LONG:
1197 			case CTLTYPE_ULONG:
1198 				umv = *(u_long *)p;
1199 				mv = *(long *)p;
1200 				break;
1201 			case CTLTYPE_S8:
1202 			case CTLTYPE_U8:
1203 				umv = *(uint8_t *)p;
1204 				mv = *(int8_t *)p;
1205 				break;
1206 			case CTLTYPE_S16:
1207 			case CTLTYPE_U16:
1208 				umv = *(uint16_t *)p;
1209 				mv = *(int16_t *)p;
1210 				break;
1211 			case CTLTYPE_S32:
1212 			case CTLTYPE_U32:
1213 				umv = *(uint32_t *)p;
1214 				mv = *(int32_t *)p;
1215 				break;
1216 			case CTLTYPE_S64:
1217 			case CTLTYPE_U64:
1218 				umv = *(uint64_t *)p;
1219 				mv = *(int64_t *)p;
1220 				break;
1221 			}
1222 			fputs(sep1, stdout);
1223 			if (xflag)
1224 				printf("%#0*jx", hexlen, umv);
1225 			else if (!sign)
1226 				printf(hflag ? "%'ju" : "%ju", umv);
1227 			else if (fmt[1] == 'K') {
1228 				if (mv < 0)
1229 					printf("%jd", mv);
1230 				else {
1231 					/*
1232 					 * See strIKtoi for details on fmt.
1233 					 */
1234 					prec = 1;
1235 					if (fmt[2] != '\0')
1236 						prec = fmt[2] - '0';
1237 					base = 1.0;
1238 					for (int i = 0; i < prec; i++)
1239 						base *= 10.0;
1240 					printf("%.*fC", prec,
1241 					    (float)mv / base - 273.15);
1242 				}
1243 			} else
1244 				printf(hflag ? "%'jd" : "%jd", mv);
1245 			sep1 = " ";
1246 			len -= intlen;
1247 			p += intlen;
1248 		}
1249 		free(oval);
1250 		return (0);
1251 
1252 	case CTLTYPE_OPAQUE:
1253 		i = 0;
1254 		if (func) {
1255 			if (!nflag)
1256 				printf("%s%s", name, sep);
1257 			if (lflag)
1258 				printf("%zd%s", len, sep);
1259 			i = (*func)(len, p);
1260 			free(oval);
1261 			return (i);
1262 		}
1263 		/* FALLTHROUGH */
1264 	default:
1265 		if (!oflag && !xflag) {
1266 			free(oval);
1267 			return (1);
1268 		}
1269 		if (!nflag)
1270 			printf("%s%s", name, sep);
1271 		if (lflag)
1272 			printf("%zd%s", len, sep);
1273 		printf("Format:%s Length:%zu Dump:0x", fmt, len);
1274 		while (len-- && (xflag || p < val + 16))
1275 			printf("%02x", *p++);
1276 		if (!xflag && len > 16)
1277 			printf("...");
1278 		free(oval);
1279 		return (0);
1280 	}
1281 	free(oval);
1282 	return (1);
1283 }
1284 
1285 static int
1286 sysctl_all(int *oid, int len)
1287 {
1288 	int name1[22], name2[22];
1289 	int i, j;
1290 	size_t l1, l2;
1291 
1292 	name1[0] = CTL_SYSCTL;
1293 	name1[1] = (oid != NULL || Nflag || dflag || tflag) ?
1294 	    CTL_SYSCTL_NEXTNOSKIP : CTL_SYSCTL_NEXT;
1295 	l1 = 2;
1296 	if (len) {
1297 		memcpy(name1 + 2, oid, len * sizeof(int));
1298 		l1 += len;
1299 	} else {
1300 		name1[2] = CTL_KERN;
1301 		l1++;
1302 	}
1303 	for (;;) {
1304 		l2 = sizeof(name2);
1305 		j = sysctl(name1, l1, name2, &l2, 0, 0);
1306 		if (j < 0) {
1307 			if (errno == ENOENT)
1308 				return (0);
1309 			else
1310 				err(1, "sysctl(getnext) %d %zu", j, l2);
1311 		}
1312 
1313 		l2 /= sizeof(int);
1314 
1315 		if (len < 0 || l2 < (unsigned int)len)
1316 			return (0);
1317 
1318 		if (memcmp(name2, oid, len * sizeof(int)) != 0)
1319 			return (0);
1320 
1321 		i = show_var(name2, l2, true);
1322 		if (!i && !bflag)
1323 			putchar('\n');
1324 
1325 		memcpy(name1 + 2, name2, l2 * sizeof(int));
1326 		l1 = 2 + l2;
1327 	}
1328 }
1329