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