xref: /freebsd/sbin/sysctl/sysctl.c (revision 190cef3d52236565eb22e18b33e9e865ec634aa3)
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 * const types[] = {
694 		[EFI_MD_TYPE_NULL] =	"Reserved",
695 		[EFI_MD_TYPE_CODE] =	"LoaderCode",
696 		[EFI_MD_TYPE_DATA] =	"LoaderData",
697 		[EFI_MD_TYPE_BS_CODE] =	"BootServicesCode",
698 		[EFI_MD_TYPE_BS_DATA] =	"BootServicesData",
699 		[EFI_MD_TYPE_RT_CODE] =	"RuntimeServicesCode",
700 		[EFI_MD_TYPE_RT_DATA] =	"RuntimeServicesData",
701 		[EFI_MD_TYPE_FREE] =	"ConventionalMemory",
702 		[EFI_MD_TYPE_BAD] =	"UnusableMemory",
703 		[EFI_MD_TYPE_RECLAIM] =	"ACPIReclaimMemory",
704 		[EFI_MD_TYPE_FIRMWARE] = "ACPIMemoryNVS",
705 		[EFI_MD_TYPE_IOMEM] =	"MemoryMappedIO",
706 		[EFI_MD_TYPE_IOPORT] =	"MemoryMappedIOPortSpace",
707 		[EFI_MD_TYPE_PALCODE] =	"PalCode",
708 		[EFI_MD_TYPE_PERSISTENT] = "PersistentMemory",
709 	};
710 
711 	/*
712 	 * Memory map data provided by UEFI via the GetMemoryMap
713 	 * Boot Services API.
714 	 */
715 	if (l2 < sizeof(*efihdr)) {
716 		warnx("S_efi_map length less than header");
717 		return (1);
718 	}
719 	efihdr = p;
720 	efisz = (sizeof(struct efi_map_header) + 0xf) & ~0xf;
721 	map = (struct efi_md *)((uint8_t *)efihdr + efisz);
722 
723 	if (efihdr->descriptor_size == 0)
724 		return (0);
725 	if (l2 != efisz + efihdr->memory_size) {
726 		warnx("S_efi_map length mismatch %zu vs %zu", l2, efisz +
727 		    efihdr->memory_size);
728 		return (1);
729 	}
730 	ndesc = efihdr->memory_size / efihdr->descriptor_size;
731 
732 	printf("\n%23s %12s %12s %8s %4s",
733 	    "Type", "Physical", "Virtual", "#Pages", "Attr");
734 
735 	for (i = 0; i < ndesc; i++,
736 	    map = efi_next_descriptor(map, efihdr->descriptor_size)) {
737 		type = NULL;
738 		if (map->md_type < nitems(types))
739 			type = types[map->md_type];
740 		if (type == NULL)
741 			type = "<INVALID>";
742 		printf("\n%23s %012jx %12p %08jx ", type,
743 		    (uintmax_t)map->md_phys, map->md_virt,
744 		    (uintmax_t)map->md_pages);
745 		if (map->md_attr & EFI_MD_ATTR_UC)
746 			printf("UC ");
747 		if (map->md_attr & EFI_MD_ATTR_WC)
748 			printf("WC ");
749 		if (map->md_attr & EFI_MD_ATTR_WT)
750 			printf("WT ");
751 		if (map->md_attr & EFI_MD_ATTR_WB)
752 			printf("WB ");
753 		if (map->md_attr & EFI_MD_ATTR_UCE)
754 			printf("UCE ");
755 		if (map->md_attr & EFI_MD_ATTR_WP)
756 			printf("WP ");
757 		if (map->md_attr & EFI_MD_ATTR_RP)
758 			printf("RP ");
759 		if (map->md_attr & EFI_MD_ATTR_XP)
760 			printf("XP ");
761 		if (map->md_attr & EFI_MD_ATTR_RT)
762 			printf("RUNTIME");
763 	}
764 	return (0);
765 }
766 #endif
767 
768 #if defined(__amd64__) || defined(__i386__)
769 static int
770 S_bios_smap_xattr(size_t l2, void *p)
771 {
772 	struct bios_smap_xattr *smap, *end;
773 
774 	if (l2 % sizeof(*smap) != 0) {
775 		warnx("S_bios_smap_xattr %zu is not a multiple of %zu", l2,
776 		    sizeof(*smap));
777 		return (1);
778 	}
779 
780 	end = (struct bios_smap_xattr *)((char *)p + l2);
781 	for (smap = p; smap < end; smap++)
782 		printf("\nSMAP type=%02x, xattr=%02x, base=%016jx, len=%016jx",
783 		    smap->type, smap->xattr, (uintmax_t)smap->base,
784 		    (uintmax_t)smap->length);
785 	return (0);
786 }
787 #endif
788 
789 static int
790 strIKtoi(const char *str, char **endptrp, const char *fmt)
791 {
792 	int kelv;
793 	float temp;
794 	size_t len;
795 	const char *p;
796 	int prec, i;
797 
798 	assert(errno == 0);
799 
800 	len = strlen(str);
801 	/* caller already checked this */
802 	assert(len > 0);
803 
804 	/*
805 	 * A format of "IK" is in deciKelvin. A format of "IK3" is in
806 	 * milliKelvin. The single digit following IK is log10 of the
807 	 * multiplying factor to convert Kelvin into the untis of this sysctl,
808 	 * or the dividing factor to convert the sysctl value to Kelvin. Numbers
809 	 * larger than 6 will run into precision issues with 32-bit integers.
810 	 * Characters that aren't ASCII digits after the 'K' are ignored. No
811 	 * localization is present because this is an interface from the kernel
812 	 * to this program (eg not an end-user interface), so isdigit() isn't
813 	 * used here.
814 	 */
815 	if (fmt[2] != '\0' && fmt[2] >= '0' && fmt[2] <= '9')
816 		prec = fmt[2] - '0';
817 	else
818 		prec = 1;
819 	p = &str[len - 1];
820 	if (*p == 'C' || *p == 'F' || *p == 'K') {
821 		temp = strtof(str, endptrp);
822 		if (*endptrp != str && *endptrp == p && errno == 0) {
823 			if (*p == 'F')
824 				temp = (temp - 32) * 5 / 9;
825 			*endptrp = NULL;
826 			if (*p != 'K')
827 				temp += 273.15;
828 			for (i = 0; i < prec; i++)
829 				temp *= 10.0;
830 			return ((int)(temp + 0.5));
831 		}
832 	} else {
833 		/* No unit specified -> treat it as a raw number */
834 		kelv = (int)strtol(str, endptrp, 10);
835 		if (*endptrp != str && *endptrp == p && errno == 0) {
836 			*endptrp = NULL;
837 			return (kelv);
838 		}
839 	}
840 
841 	errno = ERANGE;
842 	return (0);
843 }
844 
845 /*
846  * These functions uses a presently undocumented interface to the kernel
847  * to walk the tree and get the type so it can print the value.
848  * This interface is under work and consideration, and should probably
849  * be killed with a big axe by the first person who can find the time.
850  * (be aware though, that the proper interface isn't as obvious as it
851  * may seem, there are various conflicting requirements.
852  */
853 
854 static int
855 name2oid(const char *name, int *oidp)
856 {
857 	int oid[2];
858 	int i;
859 	size_t j;
860 
861 	oid[0] = 0;
862 	oid[1] = 3;
863 
864 	j = CTL_MAXNAME * sizeof(int);
865 	i = sysctl(oid, 2, oidp, &j, name, strlen(name));
866 	if (i < 0)
867 		return (i);
868 	j /= sizeof(int);
869 	return (j);
870 }
871 
872 static int
873 oidfmt(int *oid, int len, char *fmt, u_int *kind)
874 {
875 	int qoid[CTL_MAXNAME+2];
876 	u_char buf[BUFSIZ];
877 	int i;
878 	size_t j;
879 
880 	qoid[0] = 0;
881 	qoid[1] = 4;
882 	memcpy(qoid + 2, oid, len * sizeof(int));
883 
884 	j = sizeof(buf);
885 	i = sysctl(qoid, len + 2, buf, &j, 0, 0);
886 	if (i)
887 		err(1, "sysctl fmt %d %zu %d", i, j, errno);
888 
889 	if (kind)
890 		*kind = *(u_int *)buf;
891 
892 	if (fmt)
893 		strcpy(fmt, (char *)(buf + sizeof(u_int)));
894 	return (0);
895 }
896 
897 /*
898  * This formats and outputs the value of one variable
899  *
900  * Returns zero if anything was actually output.
901  * Returns one if didn't know what to do with this.
902  * Return minus one if we had errors.
903  */
904 static int
905 show_var(int *oid, int nlen)
906 {
907 	u_char buf[BUFSIZ], *val, *oval, *p;
908 	char name[BUFSIZ], fmt[BUFSIZ];
909 	const char *sep, *sep1, *prntype;
910 	int qoid[CTL_MAXNAME+2];
911 	uintmax_t umv;
912 	intmax_t mv;
913 	int i, hexlen, sign, ctltype;
914 	size_t intlen;
915 	size_t j, len;
916 	u_int kind;
917 	float base;
918 	int (*func)(size_t, void *);
919 	int prec;
920 
921 	/* Silence GCC. */
922 	umv = mv = intlen = 0;
923 
924 	bzero(buf, BUFSIZ);
925 	bzero(fmt, BUFSIZ);
926 	bzero(name, BUFSIZ);
927 	qoid[0] = 0;
928 	memcpy(qoid + 2, oid, nlen * sizeof(int));
929 
930 	qoid[1] = 1;
931 	j = sizeof(name);
932 	i = sysctl(qoid, nlen + 2, name, &j, 0, 0);
933 	if (i || !j)
934 		err(1, "sysctl name %d %zu %d", i, j, errno);
935 
936 	oidfmt(oid, nlen, fmt, &kind);
937 	/* if Wflag then only list sysctls that are writeable and not stats. */
938 	if (Wflag && ((kind & CTLFLAG_WR) == 0 || (kind & CTLFLAG_STATS) != 0))
939 		return 1;
940 
941 	/* if Tflag then only list sysctls that are tuneables. */
942 	if (Tflag && (kind & CTLFLAG_TUN) == 0)
943 		return 1;
944 
945 	if (Nflag) {
946 		printf("%s", name);
947 		return (0);
948 	}
949 
950 	if (eflag)
951 		sep = "=";
952 	else
953 		sep = ": ";
954 
955 	ctltype = (kind & CTLTYPE);
956 	if (tflag || dflag) {
957 		if (!nflag)
958 			printf("%s%s", name, sep);
959         	if (ctl_typename[ctltype] != NULL)
960             		prntype = ctl_typename[ctltype];
961         	else
962             		prntype = "unknown";
963 		if (tflag && dflag)
964 			printf("%s%s", prntype, sep);
965 		else if (tflag) {
966 			printf("%s", prntype);
967 			return (0);
968 		}
969 		qoid[1] = 5;
970 		j = sizeof(buf);
971 		i = sysctl(qoid, nlen + 2, buf, &j, 0, 0);
972 		printf("%s", buf);
973 		return (0);
974 	}
975 
976 	/* don't fetch opaques that we don't know how to print */
977 	if (ctltype == CTLTYPE_OPAQUE) {
978 		if (strcmp(fmt, "S,clockinfo") == 0)
979 			func = S_clockinfo;
980 		else if (strcmp(fmt, "S,timeval") == 0)
981 			func = S_timeval;
982 		else if (strcmp(fmt, "S,loadavg") == 0)
983 			func = S_loadavg;
984 		else if (strcmp(fmt, "S,vmtotal") == 0)
985 			func = S_vmtotal;
986 #ifdef __amd64__
987 		else if (strcmp(fmt, "S,efi_map_header") == 0)
988 			func = S_efi_map;
989 #endif
990 #if defined(__amd64__) || defined(__i386__)
991 		else if (strcmp(fmt, "S,bios_smap_xattr") == 0)
992 			func = S_bios_smap_xattr;
993 #endif
994 		else {
995 			func = NULL;
996 			if (!bflag && !oflag && !xflag)
997 				return (1);
998 		}
999 	}
1000 
1001 	/* find an estimate of how much we need for this var */
1002 	if (Bflag)
1003 		j = Bflag;
1004 	else {
1005 		j = 0;
1006 		i = sysctl(oid, nlen, 0, &j, 0, 0);
1007 		j += j; /* we want to be sure :-) */
1008 	}
1009 
1010 	val = oval = malloc(j + 1);
1011 	if (val == NULL) {
1012 		warnx("malloc failed");
1013 		return (1);
1014 	}
1015 	len = j;
1016 	i = sysctl(oid, nlen, val, &len, 0, 0);
1017 	if (i != 0 || (len == 0 && ctltype != CTLTYPE_STRING)) {
1018 		free(oval);
1019 		return (1);
1020 	}
1021 
1022 	if (bflag) {
1023 		fwrite(val, 1, len, stdout);
1024 		free(oval);
1025 		return (0);
1026 	}
1027 	val[len] = '\0';
1028 	p = val;
1029 	sign = ctl_sign[ctltype];
1030 	intlen = ctl_size[ctltype];
1031 
1032 	switch (ctltype) {
1033 	case CTLTYPE_STRING:
1034 		if (!nflag)
1035 			printf("%s%s", name, sep);
1036 		printf("%.*s", (int)len, p);
1037 		free(oval);
1038 		return (0);
1039 
1040 	case CTLTYPE_INT:
1041 	case CTLTYPE_UINT:
1042 	case CTLTYPE_LONG:
1043 	case CTLTYPE_ULONG:
1044 	case CTLTYPE_S8:
1045 	case CTLTYPE_S16:
1046 	case CTLTYPE_S32:
1047 	case CTLTYPE_S64:
1048 	case CTLTYPE_U8:
1049 	case CTLTYPE_U16:
1050 	case CTLTYPE_U32:
1051 	case CTLTYPE_U64:
1052 		if (!nflag)
1053 			printf("%s%s", name, sep);
1054 		hexlen = 2 + (intlen * CHAR_BIT + 3) / 4;
1055 		sep1 = "";
1056 		while (len >= intlen) {
1057 			switch (kind & CTLTYPE) {
1058 			case CTLTYPE_INT:
1059 			case CTLTYPE_UINT:
1060 				umv = *(u_int *)p;
1061 				mv = *(int *)p;
1062 				break;
1063 			case CTLTYPE_LONG:
1064 			case CTLTYPE_ULONG:
1065 				umv = *(u_long *)p;
1066 				mv = *(long *)p;
1067 				break;
1068 			case CTLTYPE_S8:
1069 			case CTLTYPE_U8:
1070 				umv = *(uint8_t *)p;
1071 				mv = *(int8_t *)p;
1072 				break;
1073 			case CTLTYPE_S16:
1074 			case CTLTYPE_U16:
1075 				umv = *(uint16_t *)p;
1076 				mv = *(int16_t *)p;
1077 				break;
1078 			case CTLTYPE_S32:
1079 			case CTLTYPE_U32:
1080 				umv = *(uint32_t *)p;
1081 				mv = *(int32_t *)p;
1082 				break;
1083 			case CTLTYPE_S64:
1084 			case CTLTYPE_U64:
1085 				umv = *(uint64_t *)p;
1086 				mv = *(int64_t *)p;
1087 				break;
1088 			}
1089 			fputs(sep1, stdout);
1090 			if (xflag)
1091 				printf("%#0*jx", hexlen, umv);
1092 			else if (!sign)
1093 				printf(hflag ? "%'ju" : "%ju", umv);
1094 			else if (fmt[1] == 'K') {
1095 				if (mv < 0)
1096 					printf("%jd", mv);
1097 				else {
1098 					/*
1099 					 * See strIKtoi for details on fmt.
1100 					 */
1101 					prec = 1;
1102 					if (fmt[2] != '\0')
1103 						prec = fmt[2] - '0';
1104 					base = 1.0;
1105 					for (int i = 0; i < prec; i++)
1106 						base *= 10.0;
1107 					printf("%.*fC", prec,
1108 					    (float)mv / base - 273.15);
1109 				}
1110 			} else
1111 				printf(hflag ? "%'jd" : "%jd", mv);
1112 			sep1 = " ";
1113 			len -= intlen;
1114 			p += intlen;
1115 		}
1116 		free(oval);
1117 		return (0);
1118 
1119 	case CTLTYPE_OPAQUE:
1120 		i = 0;
1121 		if (func) {
1122 			if (!nflag)
1123 				printf("%s%s", name, sep);
1124 			i = (*func)(len, p);
1125 			free(oval);
1126 			return (i);
1127 		}
1128 		/* FALLTHROUGH */
1129 	default:
1130 		if (!oflag && !xflag) {
1131 			free(oval);
1132 			return (1);
1133 		}
1134 		if (!nflag)
1135 			printf("%s%s", name, sep);
1136 		printf("Format:%s Length:%zu Dump:0x", fmt, len);
1137 		while (len-- && (xflag || p < val + 16))
1138 			printf("%02x", *p++);
1139 		if (!xflag && len > 16)
1140 			printf("...");
1141 		free(oval);
1142 		return (0);
1143 	}
1144 	free(oval);
1145 	return (1);
1146 }
1147 
1148 static int
1149 sysctl_all(int *oid, int len)
1150 {
1151 	int name1[22], name2[22];
1152 	int i, j;
1153 	size_t l1, l2;
1154 
1155 	name1[0] = 0;
1156 	name1[1] = 2;
1157 	l1 = 2;
1158 	if (len) {
1159 		memcpy(name1+2, oid, len * sizeof(int));
1160 		l1 += len;
1161 	} else {
1162 		name1[2] = 1;
1163 		l1++;
1164 	}
1165 	for (;;) {
1166 		l2 = sizeof(name2);
1167 		j = sysctl(name1, l1, name2, &l2, 0, 0);
1168 		if (j < 0) {
1169 			if (errno == ENOENT)
1170 				return (0);
1171 			else
1172 				err(1, "sysctl(getnext) %d %zu", j, l2);
1173 		}
1174 
1175 		l2 /= sizeof(int);
1176 
1177 		if (len < 0 || l2 < (unsigned int)len)
1178 			return (0);
1179 
1180 		for (i = 0; i < len; i++)
1181 			if (name2[i] != oid[i])
1182 				return (0);
1183 
1184 		i = show_var(name2, l2);
1185 		if (!i && !bflag)
1186 			putchar('\n');
1187 
1188 		memcpy(name1+2, name2, l2 * sizeof(int));
1189 		l1 = 2 + l2;
1190 	}
1191 }
1192