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