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