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