xref: /freebsd/sys/kern/kern_sysctl.c (revision b0d29bc47dba79f6f38e67eabadfb4b32ffd9390)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Mike Karels at Berkeley Software Design, Inc.
9  *
10  * Quite extensively rewritten by Poul-Henning Kamp of the FreeBSD
11  * project, to make these variables more userfriendly.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	@(#)kern_sysctl.c	8.4 (Berkeley) 4/14/94
38  */
39 
40 #include <sys/cdefs.h>
41 __FBSDID("$FreeBSD$");
42 
43 #include "opt_capsicum.h"
44 #include "opt_ddb.h"
45 #include "opt_ktrace.h"
46 #include "opt_sysctl.h"
47 
48 #include <sys/param.h>
49 #include <sys/fail.h>
50 #include <sys/systm.h>
51 #include <sys/capsicum.h>
52 #include <sys/kernel.h>
53 #include <sys/limits.h>
54 #include <sys/sysctl.h>
55 #include <sys/malloc.h>
56 #include <sys/priv.h>
57 #include <sys/proc.h>
58 #include <sys/jail.h>
59 #include <sys/kdb.h>
60 #include <sys/lock.h>
61 #include <sys/mutex.h>
62 #include <sys/rmlock.h>
63 #include <sys/sbuf.h>
64 #include <sys/sx.h>
65 #include <sys/sysproto.h>
66 #include <sys/uio.h>
67 #ifdef KTRACE
68 #include <sys/ktrace.h>
69 #endif
70 
71 #ifdef DDB
72 #include <ddb/ddb.h>
73 #include <ddb/db_lex.h>
74 #endif
75 
76 #include <net/vnet.h>
77 
78 #include <security/mac/mac_framework.h>
79 
80 #include <vm/vm.h>
81 #include <vm/vm_extern.h>
82 
83 static MALLOC_DEFINE(M_SYSCTL, "sysctl", "sysctl internal magic");
84 static MALLOC_DEFINE(M_SYSCTLOID, "sysctloid", "sysctl dynamic oids");
85 static MALLOC_DEFINE(M_SYSCTLTMP, "sysctltmp", "sysctl temp output buffer");
86 
87 /*
88  * The sysctllock protects the MIB tree.  It also protects sysctl
89  * contexts used with dynamic sysctls.  The sysctl_register_oid() and
90  * sysctl_unregister_oid() routines require the sysctllock to already
91  * be held, so the sysctl_wlock() and sysctl_wunlock() routines are
92  * provided for the few places in the kernel which need to use that
93  * API rather than using the dynamic API.  Use of the dynamic API is
94  * strongly encouraged for most code.
95  *
96  * The sysctlmemlock is used to limit the amount of user memory wired for
97  * sysctl requests.  This is implemented by serializing any userland
98  * sysctl requests larger than a single page via an exclusive lock.
99  *
100  * The sysctlstringlock is used to protect concurrent access to writable
101  * string nodes in sysctl_handle_string().
102  */
103 static struct rmlock sysctllock;
104 static struct sx __exclusive_cache_line sysctlmemlock;
105 static struct sx sysctlstringlock;
106 
107 #define	SYSCTL_WLOCK()		rm_wlock(&sysctllock)
108 #define	SYSCTL_WUNLOCK()	rm_wunlock(&sysctllock)
109 #define	SYSCTL_RLOCK(tracker)	rm_rlock(&sysctllock, (tracker))
110 #define	SYSCTL_RUNLOCK(tracker)	rm_runlock(&sysctllock, (tracker))
111 #define	SYSCTL_WLOCKED()	rm_wowned(&sysctllock)
112 #define	SYSCTL_ASSERT_LOCKED()	rm_assert(&sysctllock, RA_LOCKED)
113 #define	SYSCTL_ASSERT_WLOCKED()	rm_assert(&sysctllock, RA_WLOCKED)
114 #define	SYSCTL_ASSERT_RLOCKED()	rm_assert(&sysctllock, RA_RLOCKED)
115 #define	SYSCTL_INIT()		rm_init_flags(&sysctllock, "sysctl lock", \
116 				    RM_SLEEPABLE)
117 #define	SYSCTL_SLEEP(ch, wmesg, timo)					\
118 				rm_sleep(ch, &sysctllock, 0, wmesg, timo)
119 
120 static int sysctl_root(SYSCTL_HANDLER_ARGS);
121 
122 /* Root list */
123 struct sysctl_oid_list sysctl__children = SLIST_HEAD_INITIALIZER(&sysctl__children);
124 
125 static int	sysctl_remove_oid_locked(struct sysctl_oid *oidp, int del,
126 		    int recurse);
127 static int	sysctl_old_kernel(struct sysctl_req *, const void *, size_t);
128 static int	sysctl_new_kernel(struct sysctl_req *, void *, size_t);
129 
130 static struct sysctl_oid *
131 sysctl_find_oidname(const char *name, struct sysctl_oid_list *list)
132 {
133 	struct sysctl_oid *oidp;
134 
135 	SYSCTL_ASSERT_LOCKED();
136 	SLIST_FOREACH(oidp, list, oid_link) {
137 		if (strcmp(oidp->oid_name, name) == 0) {
138 			return (oidp);
139 		}
140 	}
141 	return (NULL);
142 }
143 
144 /*
145  * Initialization of the MIB tree.
146  *
147  * Order by number in each list.
148  */
149 void
150 sysctl_wlock(void)
151 {
152 
153 	SYSCTL_WLOCK();
154 }
155 
156 void
157 sysctl_wunlock(void)
158 {
159 
160 	SYSCTL_WUNLOCK();
161 }
162 
163 static int
164 sysctl_root_handler_locked(struct sysctl_oid *oid, void *arg1, intmax_t arg2,
165     struct sysctl_req *req, struct rm_priotracker *tracker)
166 {
167 	int error;
168 
169 	if (oid->oid_kind & CTLFLAG_DYN)
170 		atomic_add_int(&oid->oid_running, 1);
171 
172 	if (tracker != NULL)
173 		SYSCTL_RUNLOCK(tracker);
174 	else
175 		SYSCTL_WUNLOCK();
176 
177 	/*
178 	 * Treat set CTLFLAG_NEEDGIANT and unset CTLFLAG_MPSAFE flags the same,
179 	 * untill we're ready to remove all traces of Giant from sysctl(9).
180 	 */
181 	if ((oid->oid_kind & CTLFLAG_NEEDGIANT) ||
182 	    (!(oid->oid_kind & CTLFLAG_MPSAFE)))
183 		mtx_lock(&Giant);
184 	error = oid->oid_handler(oid, arg1, arg2, req);
185 	if ((oid->oid_kind & CTLFLAG_NEEDGIANT) ||
186 	    (!(oid->oid_kind & CTLFLAG_MPSAFE)))
187 		mtx_unlock(&Giant);
188 
189 	KFAIL_POINT_ERROR(_debug_fail_point, sysctl_running, error);
190 
191 	if (tracker != NULL)
192 		SYSCTL_RLOCK(tracker);
193 	else
194 		SYSCTL_WLOCK();
195 
196 	if (oid->oid_kind & CTLFLAG_DYN) {
197 		if (atomic_fetchadd_int(&oid->oid_running, -1) == 1 &&
198 		    (oid->oid_kind & CTLFLAG_DYING) != 0)
199 			wakeup(&oid->oid_running);
200 	}
201 
202 	return (error);
203 }
204 
205 static void
206 sysctl_load_tunable_by_oid_locked(struct sysctl_oid *oidp)
207 {
208 	struct sysctl_req req;
209 	struct sysctl_oid *curr;
210 	char *penv = NULL;
211 	char path[96];
212 	ssize_t rem = sizeof(path);
213 	ssize_t len;
214 	uint8_t data[512] __aligned(sizeof(uint64_t));
215 	int size;
216 	int error;
217 
218 	path[--rem] = 0;
219 
220 	for (curr = oidp; curr != NULL; curr = SYSCTL_PARENT(curr)) {
221 		len = strlen(curr->oid_name);
222 		rem -= len;
223 		if (curr != oidp)
224 			rem -= 1;
225 		if (rem < 0) {
226 			printf("OID path exceeds %d bytes\n", (int)sizeof(path));
227 			return;
228 		}
229 		memcpy(path + rem, curr->oid_name, len);
230 		if (curr != oidp)
231 			path[rem + len] = '.';
232 	}
233 
234 	memset(&req, 0, sizeof(req));
235 
236 	req.td = curthread;
237 	req.oldfunc = sysctl_old_kernel;
238 	req.newfunc = sysctl_new_kernel;
239 	req.lock = REQ_UNWIRED;
240 
241 	switch (oidp->oid_kind & CTLTYPE) {
242 	case CTLTYPE_INT:
243 		if (getenv_array(path + rem, data, sizeof(data), &size,
244 		    sizeof(int), GETENV_SIGNED) == 0)
245 			return;
246 		req.newlen = size;
247 		req.newptr = data;
248 		break;
249 	case CTLTYPE_UINT:
250 		if (getenv_array(path + rem, data, sizeof(data), &size,
251 		    sizeof(int), GETENV_UNSIGNED) == 0)
252 			return;
253 		req.newlen = size;
254 		req.newptr = data;
255 		break;
256 	case CTLTYPE_LONG:
257 		if (getenv_array(path + rem, data, sizeof(data), &size,
258 		    sizeof(long), GETENV_SIGNED) == 0)
259 			return;
260 		req.newlen = size;
261 		req.newptr = data;
262 		break;
263 	case CTLTYPE_ULONG:
264 		if (getenv_array(path + rem, data, sizeof(data), &size,
265 		    sizeof(long), GETENV_UNSIGNED) == 0)
266 			return;
267 		req.newlen = size;
268 		req.newptr = data;
269 		break;
270 	case CTLTYPE_S8:
271 		if (getenv_array(path + rem, data, sizeof(data), &size,
272 		    sizeof(int8_t), GETENV_SIGNED) == 0)
273 			return;
274 		req.newlen = size;
275 		req.newptr = data;
276 		break;
277 	case CTLTYPE_S16:
278 		if (getenv_array(path + rem, data, sizeof(data), &size,
279 		    sizeof(int16_t), GETENV_SIGNED) == 0)
280 			return;
281 		req.newlen = size;
282 		req.newptr = data;
283 		break;
284 	case CTLTYPE_S32:
285 		if (getenv_array(path + rem, data, sizeof(data), &size,
286 		    sizeof(int32_t), GETENV_SIGNED) == 0)
287 			return;
288 		req.newlen = size;
289 		req.newptr = data;
290 		break;
291 	case CTLTYPE_S64:
292 		if (getenv_array(path + rem, data, sizeof(data), &size,
293 		    sizeof(int64_t), GETENV_SIGNED) == 0)
294 			return;
295 		req.newlen = size;
296 		req.newptr = data;
297 		break;
298 	case CTLTYPE_U8:
299 		if (getenv_array(path + rem, data, sizeof(data), &size,
300 		    sizeof(uint8_t), GETENV_UNSIGNED) == 0)
301 			return;
302 		req.newlen = size;
303 		req.newptr = data;
304 		break;
305 	case CTLTYPE_U16:
306 		if (getenv_array(path + rem, data, sizeof(data), &size,
307 		    sizeof(uint16_t), GETENV_UNSIGNED) == 0)
308 			return;
309 		req.newlen = size;
310 		req.newptr = data;
311 		break;
312 	case CTLTYPE_U32:
313 		if (getenv_array(path + rem, data, sizeof(data), &size,
314 		    sizeof(uint32_t), GETENV_UNSIGNED) == 0)
315 			return;
316 		req.newlen = size;
317 		req.newptr = data;
318 		break;
319 	case CTLTYPE_U64:
320 		if (getenv_array(path + rem, data, sizeof(data), &size,
321 		    sizeof(uint64_t), GETENV_UNSIGNED) == 0)
322 			return;
323 		req.newlen = size;
324 		req.newptr = data;
325 		break;
326 	case CTLTYPE_STRING:
327 		penv = kern_getenv(path + rem);
328 		if (penv == NULL)
329 			return;
330 		req.newlen = strlen(penv);
331 		req.newptr = penv;
332 		break;
333 	default:
334 		return;
335 	}
336 	error = sysctl_root_handler_locked(oidp, oidp->oid_arg1,
337 	    oidp->oid_arg2, &req, NULL);
338 	if (error != 0)
339 		printf("Setting sysctl %s failed: %d\n", path + rem, error);
340 	if (penv != NULL)
341 		freeenv(penv);
342 }
343 
344 /*
345  * Locate the path to a given oid.  Returns the length of the resulting path,
346  * or -1 if the oid was not found.  nodes must have room for CTL_MAXNAME
347  * elements and be NULL initialized.
348  */
349 static int
350 sysctl_search_oid(struct sysctl_oid **nodes, struct sysctl_oid *needle)
351 {
352 	int indx;
353 
354 	SYSCTL_ASSERT_LOCKED();
355 	indx = 0;
356 	while (indx < CTL_MAXNAME && indx >= 0) {
357 		if (nodes[indx] == NULL && indx == 0)
358 			nodes[indx] = SLIST_FIRST(&sysctl__children);
359 		else if (nodes[indx] == NULL)
360 			nodes[indx] = SLIST_FIRST(&nodes[indx - 1]->oid_children);
361 		else
362 			nodes[indx] = SLIST_NEXT(nodes[indx], oid_link);
363 
364 		if (nodes[indx] == needle)
365 			return (indx + 1);
366 
367 		if (nodes[indx] == NULL) {
368 			indx--;
369 			continue;
370 		}
371 
372 		if ((nodes[indx]->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
373 			indx++;
374 			continue;
375 		}
376 	}
377 	return (-1);
378 }
379 
380 static void
381 sysctl_warn_reuse(const char *func, struct sysctl_oid *leaf)
382 {
383 	struct sysctl_oid *nodes[CTL_MAXNAME];
384 	char buf[128];
385 	struct sbuf sb;
386 	int rc, i;
387 
388 	(void)sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN | SBUF_INCLUDENUL);
389 	sbuf_set_drain(&sb, sbuf_printf_drain, NULL);
390 
391 	sbuf_printf(&sb, "%s: can't re-use a leaf (", __func__);
392 
393 	memset(nodes, 0, sizeof(nodes));
394 	rc = sysctl_search_oid(nodes, leaf);
395 	if (rc > 0) {
396 		for (i = 0; i < rc; i++)
397 			sbuf_printf(&sb, "%s%.*s", nodes[i]->oid_name,
398 			    i != (rc - 1), ".");
399 	} else {
400 		sbuf_printf(&sb, "%s", leaf->oid_name);
401 	}
402 	sbuf_printf(&sb, ")!\n");
403 
404 	(void)sbuf_finish(&sb);
405 }
406 
407 #ifdef SYSCTL_DEBUG
408 static int
409 sysctl_reuse_test(SYSCTL_HANDLER_ARGS)
410 {
411 	struct rm_priotracker tracker;
412 
413 	SYSCTL_RLOCK(&tracker);
414 	sysctl_warn_reuse(__func__, oidp);
415 	SYSCTL_RUNLOCK(&tracker);
416 	return (0);
417 }
418 SYSCTL_PROC(_sysctl, OID_AUTO, reuse_test,
419     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, 0, 0, sysctl_reuse_test, "-",
420     "");
421 #endif
422 
423 void
424 sysctl_register_oid(struct sysctl_oid *oidp)
425 {
426 	struct sysctl_oid_list *parent = oidp->oid_parent;
427 	struct sysctl_oid *p;
428 	struct sysctl_oid *q;
429 	int oid_number;
430 	int timeout = 2;
431 
432 	/*
433 	 * First check if another oid with the same name already
434 	 * exists in the parent's list.
435 	 */
436 	SYSCTL_ASSERT_WLOCKED();
437 	p = sysctl_find_oidname(oidp->oid_name, parent);
438 	if (p != NULL) {
439 		if ((p->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
440 			p->oid_refcnt++;
441 			return;
442 		} else {
443 			sysctl_warn_reuse(__func__, p);
444 			return;
445 		}
446 	}
447 	/* get current OID number */
448 	oid_number = oidp->oid_number;
449 
450 #if (OID_AUTO >= 0)
451 #error "OID_AUTO is expected to be a negative value"
452 #endif
453 	/*
454 	 * Any negative OID number qualifies as OID_AUTO. Valid OID
455 	 * numbers should always be positive.
456 	 *
457 	 * NOTE: DO NOT change the starting value here, change it in
458 	 * <sys/sysctl.h>, and make sure it is at least 256 to
459 	 * accommodate e.g. net.inet.raw as a static sysctl node.
460 	 */
461 	if (oid_number < 0) {
462 		static int newoid;
463 
464 		/*
465 		 * By decrementing the next OID number we spend less
466 		 * time inserting the OIDs into a sorted list.
467 		 */
468 		if (--newoid < CTL_AUTO_START)
469 			newoid = 0x7fffffff;
470 
471 		oid_number = newoid;
472 	}
473 
474 	/*
475 	 * Insert the OID into the parent's list sorted by OID number.
476 	 */
477 retry:
478 	q = NULL;
479 	SLIST_FOREACH(p, parent, oid_link) {
480 		/* check if the current OID number is in use */
481 		if (oid_number == p->oid_number) {
482 			/* get the next valid OID number */
483 			if (oid_number < CTL_AUTO_START ||
484 			    oid_number == 0x7fffffff) {
485 				/* wraparound - restart */
486 				oid_number = CTL_AUTO_START;
487 				/* don't loop forever */
488 				if (!timeout--)
489 					panic("sysctl: Out of OID numbers\n");
490 				goto retry;
491 			} else {
492 				oid_number++;
493 			}
494 		} else if (oid_number < p->oid_number)
495 			break;
496 		q = p;
497 	}
498 	/* check for non-auto OID number collision */
499 	if (oidp->oid_number >= 0 && oidp->oid_number < CTL_AUTO_START &&
500 	    oid_number >= CTL_AUTO_START) {
501 		printf("sysctl: OID number(%d) is already in use for '%s'\n",
502 		    oidp->oid_number, oidp->oid_name);
503 	}
504 	/* update the OID number, if any */
505 	oidp->oid_number = oid_number;
506 	if (q != NULL)
507 		SLIST_INSERT_AFTER(q, oidp, oid_link);
508 	else
509 		SLIST_INSERT_HEAD(parent, oidp, oid_link);
510 
511 	if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE &&
512 #ifdef VIMAGE
513 	    (oidp->oid_kind & CTLFLAG_VNET) == 0 &&
514 #endif
515 	    (oidp->oid_kind & CTLFLAG_TUN) != 0 &&
516 	    (oidp->oid_kind & CTLFLAG_NOFETCH) == 0) {
517 		/* only fetch value once */
518 		oidp->oid_kind |= CTLFLAG_NOFETCH;
519 		/* try to fetch value from kernel environment */
520 		sysctl_load_tunable_by_oid_locked(oidp);
521 	}
522 }
523 
524 void
525 sysctl_register_disabled_oid(struct sysctl_oid *oidp)
526 {
527 
528 	/*
529 	 * Mark the leaf as dormant if it's not to be immediately enabled.
530 	 * We do not disable nodes as they can be shared between modules
531 	 * and it is always safe to access a node.
532 	 */
533 	KASSERT((oidp->oid_kind & CTLFLAG_DORMANT) == 0,
534 	    ("internal flag is set in oid_kind"));
535 	if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
536 		oidp->oid_kind |= CTLFLAG_DORMANT;
537 	sysctl_register_oid(oidp);
538 }
539 
540 void
541 sysctl_enable_oid(struct sysctl_oid *oidp)
542 {
543 
544 	SYSCTL_ASSERT_WLOCKED();
545 	if ((oidp->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
546 		KASSERT((oidp->oid_kind & CTLFLAG_DORMANT) == 0,
547 		    ("sysctl node is marked as dormant"));
548 		return;
549 	}
550 	KASSERT((oidp->oid_kind & CTLFLAG_DORMANT) != 0,
551 	    ("enabling already enabled sysctl oid"));
552 	oidp->oid_kind &= ~CTLFLAG_DORMANT;
553 }
554 
555 void
556 sysctl_unregister_oid(struct sysctl_oid *oidp)
557 {
558 	struct sysctl_oid *p;
559 	int error;
560 
561 	SYSCTL_ASSERT_WLOCKED();
562 	if (oidp->oid_number == OID_AUTO) {
563 		error = EINVAL;
564 	} else {
565 		error = ENOENT;
566 		SLIST_FOREACH(p, oidp->oid_parent, oid_link) {
567 			if (p == oidp) {
568 				SLIST_REMOVE(oidp->oid_parent, oidp,
569 				    sysctl_oid, oid_link);
570 				error = 0;
571 				break;
572 			}
573 		}
574 	}
575 
576 	/*
577 	 * This can happen when a module fails to register and is
578 	 * being unloaded afterwards.  It should not be a panic()
579 	 * for normal use.
580 	 */
581 	if (error) {
582 		printf("%s: failed(%d) to unregister sysctl(%s)\n",
583 		    __func__, error, oidp->oid_name);
584 	}
585 }
586 
587 /* Initialize a new context to keep track of dynamically added sysctls. */
588 int
589 sysctl_ctx_init(struct sysctl_ctx_list *c)
590 {
591 
592 	if (c == NULL) {
593 		return (EINVAL);
594 	}
595 
596 	/*
597 	 * No locking here, the caller is responsible for not adding
598 	 * new nodes to a context until after this function has
599 	 * returned.
600 	 */
601 	TAILQ_INIT(c);
602 	return (0);
603 }
604 
605 /* Free the context, and destroy all dynamic oids registered in this context */
606 int
607 sysctl_ctx_free(struct sysctl_ctx_list *clist)
608 {
609 	struct sysctl_ctx_entry *e, *e1;
610 	int error;
611 
612 	error = 0;
613 	/*
614 	 * First perform a "dry run" to check if it's ok to remove oids.
615 	 * XXX FIXME
616 	 * XXX This algorithm is a hack. But I don't know any
617 	 * XXX better solution for now...
618 	 */
619 	SYSCTL_WLOCK();
620 	TAILQ_FOREACH(e, clist, link) {
621 		error = sysctl_remove_oid_locked(e->entry, 0, 0);
622 		if (error)
623 			break;
624 	}
625 	/*
626 	 * Restore deregistered entries, either from the end,
627 	 * or from the place where error occurred.
628 	 * e contains the entry that was not unregistered
629 	 */
630 	if (error)
631 		e1 = TAILQ_PREV(e, sysctl_ctx_list, link);
632 	else
633 		e1 = TAILQ_LAST(clist, sysctl_ctx_list);
634 	while (e1 != NULL) {
635 		sysctl_register_oid(e1->entry);
636 		e1 = TAILQ_PREV(e1, sysctl_ctx_list, link);
637 	}
638 	if (error) {
639 		SYSCTL_WUNLOCK();
640 		return(EBUSY);
641 	}
642 	/* Now really delete the entries */
643 	e = TAILQ_FIRST(clist);
644 	while (e != NULL) {
645 		e1 = TAILQ_NEXT(e, link);
646 		error = sysctl_remove_oid_locked(e->entry, 1, 0);
647 		if (error)
648 			panic("sysctl_remove_oid: corrupt tree, entry: %s",
649 			    e->entry->oid_name);
650 		free(e, M_SYSCTLOID);
651 		e = e1;
652 	}
653 	SYSCTL_WUNLOCK();
654 	return (error);
655 }
656 
657 /* Add an entry to the context */
658 struct sysctl_ctx_entry *
659 sysctl_ctx_entry_add(struct sysctl_ctx_list *clist, struct sysctl_oid *oidp)
660 {
661 	struct sysctl_ctx_entry *e;
662 
663 	SYSCTL_ASSERT_WLOCKED();
664 	if (clist == NULL || oidp == NULL)
665 		return(NULL);
666 	e = malloc(sizeof(struct sysctl_ctx_entry), M_SYSCTLOID, M_WAITOK);
667 	e->entry = oidp;
668 	TAILQ_INSERT_HEAD(clist, e, link);
669 	return (e);
670 }
671 
672 /* Find an entry in the context */
673 struct sysctl_ctx_entry *
674 sysctl_ctx_entry_find(struct sysctl_ctx_list *clist, struct sysctl_oid *oidp)
675 {
676 	struct sysctl_ctx_entry *e;
677 
678 	SYSCTL_ASSERT_WLOCKED();
679 	if (clist == NULL || oidp == NULL)
680 		return(NULL);
681 	TAILQ_FOREACH(e, clist, link) {
682 		if(e->entry == oidp)
683 			return(e);
684 	}
685 	return (e);
686 }
687 
688 /*
689  * Delete an entry from the context.
690  * NOTE: this function doesn't free oidp! You have to remove it
691  * with sysctl_remove_oid().
692  */
693 int
694 sysctl_ctx_entry_del(struct sysctl_ctx_list *clist, struct sysctl_oid *oidp)
695 {
696 	struct sysctl_ctx_entry *e;
697 
698 	if (clist == NULL || oidp == NULL)
699 		return (EINVAL);
700 	SYSCTL_WLOCK();
701 	e = sysctl_ctx_entry_find(clist, oidp);
702 	if (e != NULL) {
703 		TAILQ_REMOVE(clist, e, link);
704 		SYSCTL_WUNLOCK();
705 		free(e, M_SYSCTLOID);
706 		return (0);
707 	} else {
708 		SYSCTL_WUNLOCK();
709 		return (ENOENT);
710 	}
711 }
712 
713 /*
714  * Remove dynamically created sysctl trees.
715  * oidp - top of the tree to be removed
716  * del - if 0 - just deregister, otherwise free up entries as well
717  * recurse - if != 0 traverse the subtree to be deleted
718  */
719 int
720 sysctl_remove_oid(struct sysctl_oid *oidp, int del, int recurse)
721 {
722 	int error;
723 
724 	SYSCTL_WLOCK();
725 	error = sysctl_remove_oid_locked(oidp, del, recurse);
726 	SYSCTL_WUNLOCK();
727 	return (error);
728 }
729 
730 int
731 sysctl_remove_name(struct sysctl_oid *parent, const char *name,
732     int del, int recurse)
733 {
734 	struct sysctl_oid *p, *tmp;
735 	int error;
736 
737 	error = ENOENT;
738 	SYSCTL_WLOCK();
739 	SLIST_FOREACH_SAFE(p, SYSCTL_CHILDREN(parent), oid_link, tmp) {
740 		if (strcmp(p->oid_name, name) == 0) {
741 			error = sysctl_remove_oid_locked(p, del, recurse);
742 			break;
743 		}
744 	}
745 	SYSCTL_WUNLOCK();
746 
747 	return (error);
748 }
749 
750 static int
751 sysctl_remove_oid_locked(struct sysctl_oid *oidp, int del, int recurse)
752 {
753 	struct sysctl_oid *p, *tmp;
754 	int error;
755 
756 	SYSCTL_ASSERT_WLOCKED();
757 	if (oidp == NULL)
758 		return(EINVAL);
759 	if ((oidp->oid_kind & CTLFLAG_DYN) == 0) {
760 		printf("Warning: can't remove non-dynamic nodes (%s)!\n",
761 		    oidp->oid_name);
762 		return (EINVAL);
763 	}
764 	/*
765 	 * WARNING: normal method to do this should be through
766 	 * sysctl_ctx_free(). Use recursing as the last resort
767 	 * method to purge your sysctl tree of leftovers...
768 	 * However, if some other code still references these nodes,
769 	 * it will panic.
770 	 */
771 	if ((oidp->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
772 		if (oidp->oid_refcnt == 1) {
773 			SLIST_FOREACH_SAFE(p,
774 			    SYSCTL_CHILDREN(oidp), oid_link, tmp) {
775 				if (!recurse) {
776 					printf("Warning: failed attempt to "
777 					    "remove oid %s with child %s\n",
778 					    oidp->oid_name, p->oid_name);
779 					return (ENOTEMPTY);
780 				}
781 				error = sysctl_remove_oid_locked(p, del,
782 				    recurse);
783 				if (error)
784 					return (error);
785 			}
786 		}
787 	}
788 	if (oidp->oid_refcnt > 1 ) {
789 		oidp->oid_refcnt--;
790 	} else {
791 		if (oidp->oid_refcnt == 0) {
792 			printf("Warning: bad oid_refcnt=%u (%s)!\n",
793 				oidp->oid_refcnt, oidp->oid_name);
794 			return (EINVAL);
795 		}
796 		sysctl_unregister_oid(oidp);
797 		if (del) {
798 			/*
799 			 * Wait for all threads running the handler to drain.
800 			 * This preserves the previous behavior when the
801 			 * sysctl lock was held across a handler invocation,
802 			 * and is necessary for module unload correctness.
803 			 */
804 			while (oidp->oid_running > 0) {
805 				oidp->oid_kind |= CTLFLAG_DYING;
806 				SYSCTL_SLEEP(&oidp->oid_running, "oidrm", 0);
807 			}
808 			if (oidp->oid_descr)
809 				free(__DECONST(char *, oidp->oid_descr),
810 				    M_SYSCTLOID);
811 			if (oidp->oid_label)
812 				free(__DECONST(char *, oidp->oid_label),
813 				    M_SYSCTLOID);
814 			free(__DECONST(char *, oidp->oid_name), M_SYSCTLOID);
815 			free(oidp, M_SYSCTLOID);
816 		}
817 	}
818 	return (0);
819 }
820 /*
821  * Create new sysctls at run time.
822  * clist may point to a valid context initialized with sysctl_ctx_init().
823  */
824 struct sysctl_oid *
825 sysctl_add_oid(struct sysctl_ctx_list *clist, struct sysctl_oid_list *parent,
826 	int number, const char *name, int kind, void *arg1, intmax_t arg2,
827 	int (*handler)(SYSCTL_HANDLER_ARGS), const char *fmt, const char *descr,
828 	const char *label)
829 {
830 	struct sysctl_oid *oidp;
831 
832 	/* You have to hook up somewhere.. */
833 	if (parent == NULL)
834 		return(NULL);
835 	/* Check if the node already exists, otherwise create it */
836 	SYSCTL_WLOCK();
837 	oidp = sysctl_find_oidname(name, parent);
838 	if (oidp != NULL) {
839 		if ((oidp->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
840 			oidp->oid_refcnt++;
841 			/* Update the context */
842 			if (clist != NULL)
843 				sysctl_ctx_entry_add(clist, oidp);
844 			SYSCTL_WUNLOCK();
845 			return (oidp);
846 		} else {
847 			sysctl_warn_reuse(__func__, oidp);
848 			SYSCTL_WUNLOCK();
849 			return (NULL);
850 		}
851 	}
852 	oidp = malloc(sizeof(struct sysctl_oid), M_SYSCTLOID, M_WAITOK|M_ZERO);
853 	oidp->oid_parent = parent;
854 	SLIST_INIT(&oidp->oid_children);
855 	oidp->oid_number = number;
856 	oidp->oid_refcnt = 1;
857 	oidp->oid_name = strdup(name, M_SYSCTLOID);
858 	oidp->oid_handler = handler;
859 	oidp->oid_kind = CTLFLAG_DYN | kind;
860 	oidp->oid_arg1 = arg1;
861 	oidp->oid_arg2 = arg2;
862 	oidp->oid_fmt = fmt;
863 	if (descr != NULL)
864 		oidp->oid_descr = strdup(descr, M_SYSCTLOID);
865 	if (label != NULL)
866 		oidp->oid_label = strdup(label, M_SYSCTLOID);
867 	/* Update the context, if used */
868 	if (clist != NULL)
869 		sysctl_ctx_entry_add(clist, oidp);
870 	/* Register this oid */
871 	sysctl_register_oid(oidp);
872 	SYSCTL_WUNLOCK();
873 	return (oidp);
874 }
875 
876 /*
877  * Rename an existing oid.
878  */
879 void
880 sysctl_rename_oid(struct sysctl_oid *oidp, const char *name)
881 {
882 	char *newname;
883 	char *oldname;
884 
885 	newname = strdup(name, M_SYSCTLOID);
886 	SYSCTL_WLOCK();
887 	oldname = __DECONST(char *, oidp->oid_name);
888 	oidp->oid_name = newname;
889 	SYSCTL_WUNLOCK();
890 	free(oldname, M_SYSCTLOID);
891 }
892 
893 /*
894  * Reparent an existing oid.
895  */
896 int
897 sysctl_move_oid(struct sysctl_oid *oid, struct sysctl_oid_list *parent)
898 {
899 	struct sysctl_oid *oidp;
900 
901 	SYSCTL_WLOCK();
902 	if (oid->oid_parent == parent) {
903 		SYSCTL_WUNLOCK();
904 		return (0);
905 	}
906 	oidp = sysctl_find_oidname(oid->oid_name, parent);
907 	if (oidp != NULL) {
908 		SYSCTL_WUNLOCK();
909 		return (EEXIST);
910 	}
911 	sysctl_unregister_oid(oid);
912 	oid->oid_parent = parent;
913 	oid->oid_number = OID_AUTO;
914 	sysctl_register_oid(oid);
915 	SYSCTL_WUNLOCK();
916 	return (0);
917 }
918 
919 /*
920  * Register the kernel's oids on startup.
921  */
922 SET_DECLARE(sysctl_set, struct sysctl_oid);
923 
924 static void
925 sysctl_register_all(void *arg)
926 {
927 	struct sysctl_oid **oidp;
928 
929 	sx_init(&sysctlmemlock, "sysctl mem");
930 	sx_init(&sysctlstringlock, "sysctl string handler");
931 	SYSCTL_INIT();
932 	SYSCTL_WLOCK();
933 	SET_FOREACH(oidp, sysctl_set)
934 		sysctl_register_oid(*oidp);
935 	SYSCTL_WUNLOCK();
936 }
937 SYSINIT(sysctl, SI_SUB_KMEM, SI_ORDER_FIRST, sysctl_register_all, NULL);
938 
939 /*
940  * "Staff-functions"
941  *
942  * These functions implement a presently undocumented interface
943  * used by the sysctl program to walk the tree, and get the type
944  * so it can print the value.
945  * This interface is under work and consideration, and should probably
946  * be killed with a big axe by the first person who can find the time.
947  * (be aware though, that the proper interface isn't as obvious as it
948  * may seem, there are various conflicting requirements.
949  *
950  * {CTL_SYSCTL, CTL_SYSCTL_DEBUG}		printf the entire MIB-tree.
951  * {CTL_SYSCTL, CTL_SYSCTL_NAME, ...}		return the name of the "..."
952  *						OID.
953  * {CTL_SYSCTL, CTL_SYSCTL_NEXT, ...}		return the next OID.
954  * {CTL_SYSCTL, CTL_SYSCTL_NAME2OID}		return the OID of the name in
955  *						"new"
956  * {CTL_SYSCTL, CTL_SYSCTL_OIDFMT, ...}		return the kind & format info
957  *						for the "..." OID.
958  * {CTL_SYSCTL, CTL_SYSCTL_OIDDESCR, ...}	return the description of the
959  *						"..." OID.
960  * {CTL_SYSCTL, CTL_SYSCTL_OIDLABEL, ...}	return the aggregation label of
961  *						the "..." OID.
962  */
963 
964 #ifdef SYSCTL_DEBUG
965 static void
966 sysctl_sysctl_debug_dump_node(struct sysctl_oid_list *l, int i)
967 {
968 	int k;
969 	struct sysctl_oid *oidp;
970 
971 	SYSCTL_ASSERT_LOCKED();
972 	SLIST_FOREACH(oidp, l, oid_link) {
973 
974 		for (k=0; k<i; k++)
975 			printf(" ");
976 
977 		printf("%d %s ", oidp->oid_number, oidp->oid_name);
978 
979 		printf("%c%c",
980 			oidp->oid_kind & CTLFLAG_RD ? 'R':' ',
981 			oidp->oid_kind & CTLFLAG_WR ? 'W':' ');
982 
983 		if (oidp->oid_handler)
984 			printf(" *Handler");
985 
986 		switch (oidp->oid_kind & CTLTYPE) {
987 			case CTLTYPE_NODE:
988 				printf(" Node\n");
989 				if (!oidp->oid_handler) {
990 					sysctl_sysctl_debug_dump_node(
991 					    SYSCTL_CHILDREN(oidp), i + 2);
992 				}
993 				break;
994 			case CTLTYPE_INT:    printf(" Int\n"); break;
995 			case CTLTYPE_UINT:   printf(" u_int\n"); break;
996 			case CTLTYPE_LONG:   printf(" Long\n"); break;
997 			case CTLTYPE_ULONG:  printf(" u_long\n"); break;
998 			case CTLTYPE_STRING: printf(" String\n"); break;
999 			case CTLTYPE_S8:     printf(" int8_t\n"); break;
1000 			case CTLTYPE_S16:    printf(" int16_t\n"); break;
1001 			case CTLTYPE_S32:    printf(" int32_t\n"); break;
1002 			case CTLTYPE_S64:    printf(" int64_t\n"); break;
1003 			case CTLTYPE_U8:     printf(" uint8_t\n"); break;
1004 			case CTLTYPE_U16:    printf(" uint16_t\n"); break;
1005 			case CTLTYPE_U32:    printf(" uint32_t\n"); break;
1006 			case CTLTYPE_U64:    printf(" uint64_t\n"); break;
1007 			case CTLTYPE_OPAQUE: printf(" Opaque/struct\n"); break;
1008 			default:	     printf("\n");
1009 		}
1010 
1011 	}
1012 }
1013 
1014 static int
1015 sysctl_sysctl_debug(SYSCTL_HANDLER_ARGS)
1016 {
1017 	struct rm_priotracker tracker;
1018 	int error;
1019 
1020 	error = priv_check(req->td, PRIV_SYSCTL_DEBUG);
1021 	if (error)
1022 		return (error);
1023 	SYSCTL_RLOCK(&tracker);
1024 	sysctl_sysctl_debug_dump_node(&sysctl__children, 0);
1025 	SYSCTL_RUNLOCK(&tracker);
1026 	return (ENOENT);
1027 }
1028 
1029 SYSCTL_PROC(_sysctl, CTL_SYSCTL_DEBUG, debug, CTLTYPE_STRING | CTLFLAG_RD |
1030     CTLFLAG_MPSAFE, 0, 0, sysctl_sysctl_debug, "-", "");
1031 #endif
1032 
1033 static int
1034 sysctl_sysctl_name(SYSCTL_HANDLER_ARGS)
1035 {
1036 	int *name = (int *) arg1;
1037 	u_int namelen = arg2;
1038 	int error;
1039 	struct sysctl_oid *oid;
1040 	struct sysctl_oid_list *lsp = &sysctl__children, *lsp2;
1041 	struct rm_priotracker tracker;
1042 	char buf[10];
1043 
1044 	error = sysctl_wire_old_buffer(req, 0);
1045 	if (error)
1046 		return (error);
1047 
1048 	SYSCTL_RLOCK(&tracker);
1049 	while (namelen) {
1050 		if (!lsp) {
1051 			snprintf(buf,sizeof(buf),"%d",*name);
1052 			if (req->oldidx)
1053 				error = SYSCTL_OUT(req, ".", 1);
1054 			if (!error)
1055 				error = SYSCTL_OUT(req, buf, strlen(buf));
1056 			if (error)
1057 				goto out;
1058 			namelen--;
1059 			name++;
1060 			continue;
1061 		}
1062 		lsp2 = NULL;
1063 		SLIST_FOREACH(oid, lsp, oid_link) {
1064 			if (oid->oid_number != *name)
1065 				continue;
1066 
1067 			if (req->oldidx)
1068 				error = SYSCTL_OUT(req, ".", 1);
1069 			if (!error)
1070 				error = SYSCTL_OUT(req, oid->oid_name,
1071 					strlen(oid->oid_name));
1072 			if (error)
1073 				goto out;
1074 
1075 			namelen--;
1076 			name++;
1077 
1078 			if ((oid->oid_kind & CTLTYPE) != CTLTYPE_NODE)
1079 				break;
1080 
1081 			if (oid->oid_handler)
1082 				break;
1083 
1084 			lsp2 = SYSCTL_CHILDREN(oid);
1085 			break;
1086 		}
1087 		lsp = lsp2;
1088 	}
1089 	error = SYSCTL_OUT(req, "", 1);
1090  out:
1091 	SYSCTL_RUNLOCK(&tracker);
1092 	return (error);
1093 }
1094 
1095 /*
1096  * XXXRW/JA: Shouldn't return name data for nodes that we don't permit in
1097  * capability mode.
1098  */
1099 static SYSCTL_NODE(_sysctl, CTL_SYSCTL_NAME, name, CTLFLAG_RD |
1100     CTLFLAG_MPSAFE | CTLFLAG_CAPRD, sysctl_sysctl_name, "");
1101 
1102 static int
1103 sysctl_sysctl_next_ls(struct sysctl_oid_list *lsp, int *name, u_int namelen,
1104 	int *next, int *len, int level, struct sysctl_oid **oidpp)
1105 {
1106 	struct sysctl_oid *oidp;
1107 
1108 	SYSCTL_ASSERT_LOCKED();
1109 	*len = level;
1110 	SLIST_FOREACH(oidp, lsp, oid_link) {
1111 		*next = oidp->oid_number;
1112 		*oidpp = oidp;
1113 
1114 		if ((oidp->oid_kind & (CTLFLAG_SKIP | CTLFLAG_DORMANT)) != 0)
1115 			continue;
1116 
1117 		if (!namelen) {
1118 			if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
1119 				return (0);
1120 			if (oidp->oid_handler)
1121 				/* We really should call the handler here...*/
1122 				return (0);
1123 			lsp = SYSCTL_CHILDREN(oidp);
1124 			if (!sysctl_sysctl_next_ls(lsp, 0, 0, next+1,
1125 				len, level+1, oidpp))
1126 				return (0);
1127 			goto emptynode;
1128 		}
1129 
1130 		if (oidp->oid_number < *name)
1131 			continue;
1132 
1133 		if (oidp->oid_number > *name) {
1134 			if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
1135 				return (0);
1136 			if (oidp->oid_handler)
1137 				return (0);
1138 			lsp = SYSCTL_CHILDREN(oidp);
1139 			if (!sysctl_sysctl_next_ls(lsp, name+1, namelen-1,
1140 				next+1, len, level+1, oidpp))
1141 				return (0);
1142 			goto next;
1143 		}
1144 		if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
1145 			continue;
1146 
1147 		if (oidp->oid_handler)
1148 			continue;
1149 
1150 		lsp = SYSCTL_CHILDREN(oidp);
1151 		if (!sysctl_sysctl_next_ls(lsp, name+1, namelen-1, next+1,
1152 			len, level+1, oidpp))
1153 			return (0);
1154 	next:
1155 		namelen = 1;
1156 	emptynode:
1157 		*len = level;
1158 	}
1159 	return (1);
1160 }
1161 
1162 static int
1163 sysctl_sysctl_next(SYSCTL_HANDLER_ARGS)
1164 {
1165 	int *name = (int *) arg1;
1166 	u_int namelen = arg2;
1167 	int i, j, error;
1168 	struct sysctl_oid *oid;
1169 	struct sysctl_oid_list *lsp = &sysctl__children;
1170 	struct rm_priotracker tracker;
1171 	int newoid[CTL_MAXNAME];
1172 
1173 	SYSCTL_RLOCK(&tracker);
1174 	i = sysctl_sysctl_next_ls(lsp, name, namelen, newoid, &j, 1, &oid);
1175 	SYSCTL_RUNLOCK(&tracker);
1176 	if (i)
1177 		return (ENOENT);
1178 	error = SYSCTL_OUT(req, newoid, j * sizeof (int));
1179 	return (error);
1180 }
1181 
1182 /*
1183  * XXXRW/JA: Shouldn't return next data for nodes that we don't permit in
1184  * capability mode.
1185  */
1186 static SYSCTL_NODE(_sysctl, CTL_SYSCTL_NEXT, next, CTLFLAG_RD |
1187     CTLFLAG_MPSAFE | CTLFLAG_CAPRD, sysctl_sysctl_next, "");
1188 
1189 static int
1190 name2oid(char *name, int *oid, int *len, struct sysctl_oid **oidpp)
1191 {
1192 	struct sysctl_oid *oidp;
1193 	struct sysctl_oid_list *lsp = &sysctl__children;
1194 	char *p;
1195 
1196 	SYSCTL_ASSERT_LOCKED();
1197 
1198 	for (*len = 0; *len < CTL_MAXNAME;) {
1199 		p = strsep(&name, ".");
1200 
1201 		oidp = SLIST_FIRST(lsp);
1202 		for (;; oidp = SLIST_NEXT(oidp, oid_link)) {
1203 			if (oidp == NULL)
1204 				return (ENOENT);
1205 			if (strcmp(p, oidp->oid_name) == 0)
1206 				break;
1207 		}
1208 		*oid++ = oidp->oid_number;
1209 		(*len)++;
1210 
1211 		if (name == NULL || *name == '\0') {
1212 			if (oidpp)
1213 				*oidpp = oidp;
1214 			return (0);
1215 		}
1216 
1217 		if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
1218 			break;
1219 
1220 		if (oidp->oid_handler)
1221 			break;
1222 
1223 		lsp = SYSCTL_CHILDREN(oidp);
1224 	}
1225 	return (ENOENT);
1226 }
1227 
1228 static int
1229 sysctl_sysctl_name2oid(SYSCTL_HANDLER_ARGS)
1230 {
1231 	char *p;
1232 	int error, oid[CTL_MAXNAME], len = 0;
1233 	struct sysctl_oid *op = NULL;
1234 	struct rm_priotracker tracker;
1235 	char buf[32];
1236 
1237 	if (!req->newlen)
1238 		return (ENOENT);
1239 	if (req->newlen >= MAXPATHLEN)	/* XXX arbitrary, undocumented */
1240 		return (ENAMETOOLONG);
1241 
1242 	p = buf;
1243 	if (req->newlen >= sizeof(buf))
1244 		p = malloc(req->newlen+1, M_SYSCTL, M_WAITOK);
1245 
1246 	error = SYSCTL_IN(req, p, req->newlen);
1247 	if (error) {
1248 		if (p != buf)
1249 			free(p, M_SYSCTL);
1250 		return (error);
1251 	}
1252 
1253 	p [req->newlen] = '\0';
1254 
1255 	SYSCTL_RLOCK(&tracker);
1256 	error = name2oid(p, oid, &len, &op);
1257 	SYSCTL_RUNLOCK(&tracker);
1258 
1259 	if (p != buf)
1260 		free(p, M_SYSCTL);
1261 
1262 	if (error)
1263 		return (error);
1264 
1265 	error = SYSCTL_OUT(req, oid, len * sizeof *oid);
1266 	return (error);
1267 }
1268 
1269 /*
1270  * XXXRW/JA: Shouldn't return name2oid data for nodes that we don't permit in
1271  * capability mode.
1272  */
1273 SYSCTL_PROC(_sysctl, CTL_SYSCTL_NAME2OID, name2oid, CTLTYPE_INT | CTLFLAG_RW |
1274     CTLFLAG_ANYBODY | CTLFLAG_MPSAFE | CTLFLAG_CAPRW, 0, 0,
1275     sysctl_sysctl_name2oid, "I", "");
1276 
1277 static int
1278 sysctl_sysctl_oidfmt(SYSCTL_HANDLER_ARGS)
1279 {
1280 	struct sysctl_oid *oid;
1281 	struct rm_priotracker tracker;
1282 	int error;
1283 
1284 	error = sysctl_wire_old_buffer(req, 0);
1285 	if (error)
1286 		return (error);
1287 
1288 	SYSCTL_RLOCK(&tracker);
1289 	error = sysctl_find_oid(arg1, arg2, &oid, NULL, req);
1290 	if (error)
1291 		goto out;
1292 
1293 	if (oid->oid_fmt == NULL) {
1294 		error = ENOENT;
1295 		goto out;
1296 	}
1297 	error = SYSCTL_OUT(req, &oid->oid_kind, sizeof(oid->oid_kind));
1298 	if (error)
1299 		goto out;
1300 	error = SYSCTL_OUT(req, oid->oid_fmt, strlen(oid->oid_fmt) + 1);
1301  out:
1302 	SYSCTL_RUNLOCK(&tracker);
1303 	return (error);
1304 }
1305 
1306 static SYSCTL_NODE(_sysctl, CTL_SYSCTL_OIDFMT, oidfmt, CTLFLAG_RD |
1307     CTLFLAG_MPSAFE | CTLFLAG_CAPRD, sysctl_sysctl_oidfmt, "");
1308 
1309 static int
1310 sysctl_sysctl_oiddescr(SYSCTL_HANDLER_ARGS)
1311 {
1312 	struct sysctl_oid *oid;
1313 	struct rm_priotracker tracker;
1314 	int error;
1315 
1316 	error = sysctl_wire_old_buffer(req, 0);
1317 	if (error)
1318 		return (error);
1319 
1320 	SYSCTL_RLOCK(&tracker);
1321 	error = sysctl_find_oid(arg1, arg2, &oid, NULL, req);
1322 	if (error)
1323 		goto out;
1324 
1325 	if (oid->oid_descr == NULL) {
1326 		error = ENOENT;
1327 		goto out;
1328 	}
1329 	error = SYSCTL_OUT(req, oid->oid_descr, strlen(oid->oid_descr) + 1);
1330  out:
1331 	SYSCTL_RUNLOCK(&tracker);
1332 	return (error);
1333 }
1334 
1335 static SYSCTL_NODE(_sysctl, CTL_SYSCTL_OIDDESCR, oiddescr, CTLFLAG_RD |
1336     CTLFLAG_MPSAFE|CTLFLAG_CAPRD, sysctl_sysctl_oiddescr, "");
1337 
1338 static int
1339 sysctl_sysctl_oidlabel(SYSCTL_HANDLER_ARGS)
1340 {
1341 	struct sysctl_oid *oid;
1342 	struct rm_priotracker tracker;
1343 	int error;
1344 
1345 	error = sysctl_wire_old_buffer(req, 0);
1346 	if (error)
1347 		return (error);
1348 
1349 	SYSCTL_RLOCK(&tracker);
1350 	error = sysctl_find_oid(arg1, arg2, &oid, NULL, req);
1351 	if (error)
1352 		goto out;
1353 
1354 	if (oid->oid_label == NULL) {
1355 		error = ENOENT;
1356 		goto out;
1357 	}
1358 	error = SYSCTL_OUT(req, oid->oid_label, strlen(oid->oid_label) + 1);
1359  out:
1360 	SYSCTL_RUNLOCK(&tracker);
1361 	return (error);
1362 }
1363 
1364 static SYSCTL_NODE(_sysctl, CTL_SYSCTL_OIDLABEL, oidlabel, CTLFLAG_RD |
1365     CTLFLAG_MPSAFE | CTLFLAG_CAPRD, sysctl_sysctl_oidlabel, "");
1366 
1367 /*
1368  * Default "handler" functions.
1369  */
1370 
1371 /*
1372  * Handle a bool.
1373  * Two cases:
1374  *     a variable:  point arg1 at it.
1375  *     a constant:  pass it in arg2.
1376  */
1377 
1378 int
1379 sysctl_handle_bool(SYSCTL_HANDLER_ARGS)
1380 {
1381 	uint8_t temp;
1382 	int error;
1383 
1384 	/*
1385 	 * Attempt to get a coherent snapshot by making a copy of the data.
1386 	 */
1387 	if (arg1)
1388 		temp = *(bool *)arg1 ? 1 : 0;
1389 	else
1390 		temp = arg2 ? 1 : 0;
1391 
1392 	error = SYSCTL_OUT(req, &temp, sizeof(temp));
1393 	if (error || !req->newptr)
1394 		return (error);
1395 
1396 	if (!arg1)
1397 		error = EPERM;
1398 	else {
1399 		error = SYSCTL_IN(req, &temp, sizeof(temp));
1400 		if (!error)
1401 			*(bool *)arg1 = temp ? 1 : 0;
1402 	}
1403 	return (error);
1404 }
1405 
1406 /*
1407  * Handle an int8_t, signed or unsigned.
1408  * Two cases:
1409  *     a variable:  point arg1 at it.
1410  *     a constant:  pass it in arg2.
1411  */
1412 
1413 int
1414 sysctl_handle_8(SYSCTL_HANDLER_ARGS)
1415 {
1416 	int8_t tmpout;
1417 	int error = 0;
1418 
1419 	/*
1420 	 * Attempt to get a coherent snapshot by making a copy of the data.
1421 	 */
1422 	if (arg1)
1423 		tmpout = *(int8_t *)arg1;
1424 	else
1425 		tmpout = arg2;
1426 	error = SYSCTL_OUT(req, &tmpout, sizeof(tmpout));
1427 
1428 	if (error || !req->newptr)
1429 		return (error);
1430 
1431 	if (!arg1)
1432 		error = EPERM;
1433 	else
1434 		error = SYSCTL_IN(req, arg1, sizeof(tmpout));
1435 	return (error);
1436 }
1437 
1438 /*
1439  * Handle an int16_t, signed or unsigned.
1440  * Two cases:
1441  *     a variable:  point arg1 at it.
1442  *     a constant:  pass it in arg2.
1443  */
1444 
1445 int
1446 sysctl_handle_16(SYSCTL_HANDLER_ARGS)
1447 {
1448 	int16_t tmpout;
1449 	int error = 0;
1450 
1451 	/*
1452 	 * Attempt to get a coherent snapshot by making a copy of the data.
1453 	 */
1454 	if (arg1)
1455 		tmpout = *(int16_t *)arg1;
1456 	else
1457 		tmpout = arg2;
1458 	error = SYSCTL_OUT(req, &tmpout, sizeof(tmpout));
1459 
1460 	if (error || !req->newptr)
1461 		return (error);
1462 
1463 	if (!arg1)
1464 		error = EPERM;
1465 	else
1466 		error = SYSCTL_IN(req, arg1, sizeof(tmpout));
1467 	return (error);
1468 }
1469 
1470 /*
1471  * Handle an int32_t, signed or unsigned.
1472  * Two cases:
1473  *     a variable:  point arg1 at it.
1474  *     a constant:  pass it in arg2.
1475  */
1476 
1477 int
1478 sysctl_handle_32(SYSCTL_HANDLER_ARGS)
1479 {
1480 	int32_t tmpout;
1481 	int error = 0;
1482 
1483 	/*
1484 	 * Attempt to get a coherent snapshot by making a copy of the data.
1485 	 */
1486 	if (arg1)
1487 		tmpout = *(int32_t *)arg1;
1488 	else
1489 		tmpout = arg2;
1490 	error = SYSCTL_OUT(req, &tmpout, sizeof(tmpout));
1491 
1492 	if (error || !req->newptr)
1493 		return (error);
1494 
1495 	if (!arg1)
1496 		error = EPERM;
1497 	else
1498 		error = SYSCTL_IN(req, arg1, sizeof(tmpout));
1499 	return (error);
1500 }
1501 
1502 /*
1503  * Handle an int, signed or unsigned.
1504  * Two cases:
1505  *     a variable:  point arg1 at it.
1506  *     a constant:  pass it in arg2.
1507  */
1508 
1509 int
1510 sysctl_handle_int(SYSCTL_HANDLER_ARGS)
1511 {
1512 	int tmpout, error = 0;
1513 
1514 	/*
1515 	 * Attempt to get a coherent snapshot by making a copy of the data.
1516 	 */
1517 	if (arg1)
1518 		tmpout = *(int *)arg1;
1519 	else
1520 		tmpout = arg2;
1521 	error = SYSCTL_OUT(req, &tmpout, sizeof(int));
1522 
1523 	if (error || !req->newptr)
1524 		return (error);
1525 
1526 	if (!arg1)
1527 		error = EPERM;
1528 	else
1529 		error = SYSCTL_IN(req, arg1, sizeof(int));
1530 	return (error);
1531 }
1532 
1533 /*
1534  * Based on on sysctl_handle_int() convert milliseconds into ticks.
1535  * Note: this is used by TCP.
1536  */
1537 
1538 int
1539 sysctl_msec_to_ticks(SYSCTL_HANDLER_ARGS)
1540 {
1541 	int error, s, tt;
1542 
1543 	tt = *(int *)arg1;
1544 	s = (int)((int64_t)tt * 1000 / hz);
1545 
1546 	error = sysctl_handle_int(oidp, &s, 0, req);
1547 	if (error || !req->newptr)
1548 		return (error);
1549 
1550 	tt = (int)((int64_t)s * hz / 1000);
1551 	if (tt < 1)
1552 		return (EINVAL);
1553 
1554 	*(int *)arg1 = tt;
1555 	return (0);
1556 }
1557 
1558 /*
1559  * Handle a long, signed or unsigned.
1560  * Two cases:
1561  *     a variable:  point arg1 at it.
1562  *     a constant:  pass it in arg2.
1563  */
1564 
1565 int
1566 sysctl_handle_long(SYSCTL_HANDLER_ARGS)
1567 {
1568 	int error = 0;
1569 	long tmplong;
1570 #ifdef SCTL_MASK32
1571 	int tmpint;
1572 #endif
1573 
1574 	/*
1575 	 * Attempt to get a coherent snapshot by making a copy of the data.
1576 	 */
1577 	if (arg1)
1578 		tmplong = *(long *)arg1;
1579 	else
1580 		tmplong = arg2;
1581 #ifdef SCTL_MASK32
1582 	if (req->flags & SCTL_MASK32) {
1583 		tmpint = tmplong;
1584 		error = SYSCTL_OUT(req, &tmpint, sizeof(int));
1585 	} else
1586 #endif
1587 		error = SYSCTL_OUT(req, &tmplong, sizeof(long));
1588 
1589 	if (error || !req->newptr)
1590 		return (error);
1591 
1592 	if (!arg1)
1593 		error = EPERM;
1594 #ifdef SCTL_MASK32
1595 	else if (req->flags & SCTL_MASK32) {
1596 		error = SYSCTL_IN(req, &tmpint, sizeof(int));
1597 		*(long *)arg1 = (long)tmpint;
1598 	}
1599 #endif
1600 	else
1601 		error = SYSCTL_IN(req, arg1, sizeof(long));
1602 	return (error);
1603 }
1604 
1605 /*
1606  * Handle a 64 bit int, signed or unsigned.
1607  * Two cases:
1608  *     a variable:  point arg1 at it.
1609  *     a constant:  pass it in arg2.
1610  */
1611 int
1612 sysctl_handle_64(SYSCTL_HANDLER_ARGS)
1613 {
1614 	int error = 0;
1615 	uint64_t tmpout;
1616 
1617 	/*
1618 	 * Attempt to get a coherent snapshot by making a copy of the data.
1619 	 */
1620 	if (arg1)
1621 		tmpout = *(uint64_t *)arg1;
1622 	else
1623 		tmpout = arg2;
1624 	error = SYSCTL_OUT(req, &tmpout, sizeof(uint64_t));
1625 
1626 	if (error || !req->newptr)
1627 		return (error);
1628 
1629 	if (!arg1)
1630 		error = EPERM;
1631 	else
1632 		error = SYSCTL_IN(req, arg1, sizeof(uint64_t));
1633 	return (error);
1634 }
1635 
1636 /*
1637  * Handle our generic '\0' terminated 'C' string.
1638  * Two cases:
1639  * 	a variable string:  point arg1 at it, arg2 is max length.
1640  * 	a constant string:  point arg1 at it, arg2 is zero.
1641  */
1642 
1643 int
1644 sysctl_handle_string(SYSCTL_HANDLER_ARGS)
1645 {
1646 	char *tmparg;
1647 	size_t outlen;
1648 	int error = 0, ro_string = 0;
1649 
1650 	/*
1651 	 * If the sysctl isn't writable, microoptimise and treat it as a
1652 	 * const string.
1653 	 * A zero-length buffer indicates a fixed size read-only
1654 	 * string.  In ddb, don't worry about trying to make a malloced
1655 	 * snapshot.
1656 	 */
1657 	if (!(oidp->oid_kind & CTLFLAG_WR) || arg2 == 0 || kdb_active) {
1658 		arg2 = strlen((char *)arg1) + 1;
1659 		ro_string = 1;
1660 	}
1661 
1662 	if (req->oldptr != NULL) {
1663 		if (ro_string) {
1664 			tmparg = arg1;
1665 			outlen = strlen(tmparg) + 1;
1666 		} else {
1667 			tmparg = malloc(arg2, M_SYSCTLTMP, M_WAITOK);
1668 			sx_slock(&sysctlstringlock);
1669 			memcpy(tmparg, arg1, arg2);
1670 			sx_sunlock(&sysctlstringlock);
1671 			outlen = strlen(tmparg) + 1;
1672 		}
1673 
1674 		error = SYSCTL_OUT(req, tmparg, outlen);
1675 
1676 		if (!ro_string)
1677 			free(tmparg, M_SYSCTLTMP);
1678 	} else {
1679 		if (!ro_string)
1680 			sx_slock(&sysctlstringlock);
1681 		outlen = strlen((char *)arg1) + 1;
1682 		if (!ro_string)
1683 			sx_sunlock(&sysctlstringlock);
1684 		error = SYSCTL_OUT(req, NULL, outlen);
1685 	}
1686 	if (error || !req->newptr)
1687 		return (error);
1688 
1689 	if (req->newlen - req->newidx >= arg2 ||
1690 	    req->newlen - req->newidx < 0) {
1691 		error = EINVAL;
1692 	} else if (req->newlen - req->newidx == 0) {
1693 		sx_xlock(&sysctlstringlock);
1694 		((char *)arg1)[0] = '\0';
1695 		sx_xunlock(&sysctlstringlock);
1696 	} else {
1697 		arg2 = req->newlen - req->newidx;
1698 		tmparg = malloc(arg2, M_SYSCTLTMP, M_WAITOK);
1699 
1700 		error = copyin((const char *)req->newptr + req->newidx,
1701 		    tmparg, arg2);
1702 		if (error) {
1703 			free(tmparg, M_SYSCTLTMP);
1704 			return (error);
1705 		}
1706 
1707 		sx_xlock(&sysctlstringlock);
1708 		memcpy(arg1, tmparg, arg2);
1709 		((char *)arg1)[arg2] = '\0';
1710 		sx_xunlock(&sysctlstringlock);
1711 		free(tmparg, M_SYSCTLTMP);
1712 		req->newidx += arg2;
1713 	}
1714 	return (error);
1715 }
1716 
1717 /*
1718  * Handle any kind of opaque data.
1719  * arg1 points to it, arg2 is the size.
1720  */
1721 
1722 int
1723 sysctl_handle_opaque(SYSCTL_HANDLER_ARGS)
1724 {
1725 	int error, tries;
1726 	u_int generation;
1727 	struct sysctl_req req2;
1728 
1729 	/*
1730 	 * Attempt to get a coherent snapshot, by using the thread
1731 	 * pre-emption counter updated from within mi_switch() to
1732 	 * determine if we were pre-empted during a bcopy() or
1733 	 * copyout(). Make 3 attempts at doing this before giving up.
1734 	 * If we encounter an error, stop immediately.
1735 	 */
1736 	tries = 0;
1737 	req2 = *req;
1738 retry:
1739 	generation = curthread->td_generation;
1740 	error = SYSCTL_OUT(req, arg1, arg2);
1741 	if (error)
1742 		return (error);
1743 	tries++;
1744 	if (generation != curthread->td_generation && tries < 3) {
1745 		*req = req2;
1746 		goto retry;
1747 	}
1748 
1749 	error = SYSCTL_IN(req, arg1, arg2);
1750 
1751 	return (error);
1752 }
1753 
1754 /*
1755  * Based on on sysctl_handle_int() convert microseconds to a sbintime.
1756  */
1757 int
1758 sysctl_usec_to_sbintime(SYSCTL_HANDLER_ARGS)
1759 {
1760 	int error;
1761 	int64_t tt;
1762 	sbintime_t sb;
1763 
1764 	tt = *(int64_t *)arg1;
1765 	sb = sbttous(tt);
1766 
1767 	error = sysctl_handle_64(oidp, &sb, 0, req);
1768 	if (error || !req->newptr)
1769 		return (error);
1770 
1771 	tt = ustosbt(sb);
1772 	*(int64_t *)arg1 = tt;
1773 
1774 	return (0);
1775 }
1776 
1777 /*
1778  * Based on on sysctl_handle_int() convert milliseconds to a sbintime.
1779  */
1780 int
1781 sysctl_msec_to_sbintime(SYSCTL_HANDLER_ARGS)
1782 {
1783 	int error;
1784 	int64_t tt;
1785 	sbintime_t sb;
1786 
1787 	tt = *(int64_t *)arg1;
1788 	sb = sbttoms(tt);
1789 
1790 	error = sysctl_handle_64(oidp, &sb, 0, req);
1791 	if (error || !req->newptr)
1792 		return (error);
1793 
1794 	tt = mstosbt(sb);
1795 	*(int64_t *)arg1 = tt;
1796 
1797 	return (0);
1798 }
1799 
1800 /*
1801  * Convert seconds to a struct timeval.  Intended for use with
1802  * intervals and thus does not permit negative seconds.
1803  */
1804 int
1805 sysctl_sec_to_timeval(SYSCTL_HANDLER_ARGS)
1806 {
1807 	struct timeval *tv;
1808 	int error, secs;
1809 
1810 	tv = arg1;
1811 	secs = tv->tv_sec;
1812 
1813 	error = sysctl_handle_int(oidp, &secs, 0, req);
1814 	if (error || req->newptr == NULL)
1815 		return (error);
1816 
1817 	if (secs < 0)
1818 		return (EINVAL);
1819 	tv->tv_sec = secs;
1820 
1821 	return (0);
1822 }
1823 
1824 /*
1825  * Transfer functions to/from kernel space.
1826  * XXX: rather untested at this point
1827  */
1828 static int
1829 sysctl_old_kernel(struct sysctl_req *req, const void *p, size_t l)
1830 {
1831 	size_t i = 0;
1832 
1833 	if (req->oldptr) {
1834 		i = l;
1835 		if (req->oldlen <= req->oldidx)
1836 			i = 0;
1837 		else
1838 			if (i > req->oldlen - req->oldidx)
1839 				i = req->oldlen - req->oldidx;
1840 		if (i > 0)
1841 			bcopy(p, (char *)req->oldptr + req->oldidx, i);
1842 	}
1843 	req->oldidx += l;
1844 	if (req->oldptr && i != l)
1845 		return (ENOMEM);
1846 	return (0);
1847 }
1848 
1849 static int
1850 sysctl_new_kernel(struct sysctl_req *req, void *p, size_t l)
1851 {
1852 	if (!req->newptr)
1853 		return (0);
1854 	if (req->newlen - req->newidx < l)
1855 		return (EINVAL);
1856 	bcopy((const char *)req->newptr + req->newidx, p, l);
1857 	req->newidx += l;
1858 	return (0);
1859 }
1860 
1861 int
1862 kernel_sysctl(struct thread *td, int *name, u_int namelen, void *old,
1863     size_t *oldlenp, void *new, size_t newlen, size_t *retval, int flags)
1864 {
1865 	int error = 0;
1866 	struct sysctl_req req;
1867 
1868 	bzero(&req, sizeof req);
1869 
1870 	req.td = td;
1871 	req.flags = flags;
1872 
1873 	if (oldlenp) {
1874 		req.oldlen = *oldlenp;
1875 	}
1876 	req.validlen = req.oldlen;
1877 
1878 	if (old) {
1879 		req.oldptr= old;
1880 	}
1881 
1882 	if (new != NULL) {
1883 		req.newlen = newlen;
1884 		req.newptr = new;
1885 	}
1886 
1887 	req.oldfunc = sysctl_old_kernel;
1888 	req.newfunc = sysctl_new_kernel;
1889 	req.lock = REQ_UNWIRED;
1890 
1891 	error = sysctl_root(0, name, namelen, &req);
1892 
1893 	if (req.lock == REQ_WIRED && req.validlen > 0)
1894 		vsunlock(req.oldptr, req.validlen);
1895 
1896 	if (error && error != ENOMEM)
1897 		return (error);
1898 
1899 	if (retval) {
1900 		if (req.oldptr && req.oldidx > req.validlen)
1901 			*retval = req.validlen;
1902 		else
1903 			*retval = req.oldidx;
1904 	}
1905 	return (error);
1906 }
1907 
1908 int
1909 kernel_sysctlbyname(struct thread *td, char *name, void *old, size_t *oldlenp,
1910     void *new, size_t newlen, size_t *retval, int flags)
1911 {
1912         int oid[CTL_MAXNAME];
1913         size_t oidlen, plen;
1914 	int error;
1915 
1916 	oid[0] = CTL_SYSCTL;
1917 	oid[1] = CTL_SYSCTL_NAME2OID;
1918 	oidlen = sizeof(oid);
1919 
1920 	error = kernel_sysctl(td, oid, 2, oid, &oidlen,
1921 	    (void *)name, strlen(name), &plen, flags);
1922 	if (error)
1923 		return (error);
1924 
1925 	error = kernel_sysctl(td, oid, plen / sizeof(int), old, oldlenp,
1926 	    new, newlen, retval, flags);
1927 	return (error);
1928 }
1929 
1930 /*
1931  * Transfer function to/from user space.
1932  */
1933 static int
1934 sysctl_old_user(struct sysctl_req *req, const void *p, size_t l)
1935 {
1936 	size_t i, len, origidx;
1937 	int error;
1938 
1939 	origidx = req->oldidx;
1940 	req->oldidx += l;
1941 	if (req->oldptr == NULL)
1942 		return (0);
1943 	/*
1944 	 * If we have not wired the user supplied buffer and we are currently
1945 	 * holding locks, drop a witness warning, as it's possible that
1946 	 * write operations to the user page can sleep.
1947 	 */
1948 	if (req->lock != REQ_WIRED)
1949 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1950 		    "sysctl_old_user()");
1951 	i = l;
1952 	len = req->validlen;
1953 	if (len <= origidx)
1954 		i = 0;
1955 	else {
1956 		if (i > len - origidx)
1957 			i = len - origidx;
1958 		if (req->lock == REQ_WIRED) {
1959 			error = copyout_nofault(p, (char *)req->oldptr +
1960 			    origidx, i);
1961 		} else
1962 			error = copyout(p, (char *)req->oldptr + origidx, i);
1963 		if (error != 0)
1964 			return (error);
1965 	}
1966 	if (i < l)
1967 		return (ENOMEM);
1968 	return (0);
1969 }
1970 
1971 static int
1972 sysctl_new_user(struct sysctl_req *req, void *p, size_t l)
1973 {
1974 	int error;
1975 
1976 	if (!req->newptr)
1977 		return (0);
1978 	if (req->newlen - req->newidx < l)
1979 		return (EINVAL);
1980 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1981 	    "sysctl_new_user()");
1982 	error = copyin((const char *)req->newptr + req->newidx, p, l);
1983 	req->newidx += l;
1984 	return (error);
1985 }
1986 
1987 /*
1988  * Wire the user space destination buffer.  If set to a value greater than
1989  * zero, the len parameter limits the maximum amount of wired memory.
1990  */
1991 int
1992 sysctl_wire_old_buffer(struct sysctl_req *req, size_t len)
1993 {
1994 	int ret;
1995 	size_t wiredlen;
1996 
1997 	wiredlen = (len > 0 && len < req->oldlen) ? len : req->oldlen;
1998 	ret = 0;
1999 	if (req->lock != REQ_WIRED && req->oldptr &&
2000 	    req->oldfunc == sysctl_old_user) {
2001 		if (wiredlen != 0) {
2002 			ret = vslock(req->oldptr, wiredlen);
2003 			if (ret != 0) {
2004 				if (ret != ENOMEM)
2005 					return (ret);
2006 				wiredlen = 0;
2007 			}
2008 		}
2009 		req->lock = REQ_WIRED;
2010 		req->validlen = wiredlen;
2011 	}
2012 	return (0);
2013 }
2014 
2015 int
2016 sysctl_find_oid(int *name, u_int namelen, struct sysctl_oid **noid,
2017     int *nindx, struct sysctl_req *req)
2018 {
2019 	struct sysctl_oid_list *lsp;
2020 	struct sysctl_oid *oid;
2021 	int indx;
2022 
2023 	SYSCTL_ASSERT_LOCKED();
2024 	lsp = &sysctl__children;
2025 	indx = 0;
2026 	while (indx < CTL_MAXNAME) {
2027 		SLIST_FOREACH(oid, lsp, oid_link) {
2028 			if (oid->oid_number == name[indx])
2029 				break;
2030 		}
2031 		if (oid == NULL)
2032 			return (ENOENT);
2033 
2034 		indx++;
2035 		if ((oid->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
2036 			if (oid->oid_handler != NULL || indx == namelen) {
2037 				*noid = oid;
2038 				if (nindx != NULL)
2039 					*nindx = indx;
2040 				KASSERT((oid->oid_kind & CTLFLAG_DYING) == 0,
2041 				    ("%s found DYING node %p", __func__, oid));
2042 				return (0);
2043 			}
2044 			lsp = SYSCTL_CHILDREN(oid);
2045 		} else if (indx == namelen) {
2046 			if ((oid->oid_kind & CTLFLAG_DORMANT) != 0)
2047 				return (ENOENT);
2048 			*noid = oid;
2049 			if (nindx != NULL)
2050 				*nindx = indx;
2051 			KASSERT((oid->oid_kind & CTLFLAG_DYING) == 0,
2052 			    ("%s found DYING node %p", __func__, oid));
2053 			return (0);
2054 		} else {
2055 			return (ENOTDIR);
2056 		}
2057 	}
2058 	return (ENOENT);
2059 }
2060 
2061 /*
2062  * Traverse our tree, and find the right node, execute whatever it points
2063  * to, and return the resulting error code.
2064  */
2065 
2066 static int
2067 sysctl_root(SYSCTL_HANDLER_ARGS)
2068 {
2069 	struct sysctl_oid *oid;
2070 	struct rm_priotracker tracker;
2071 	int error, indx, lvl;
2072 
2073 	SYSCTL_RLOCK(&tracker);
2074 
2075 	error = sysctl_find_oid(arg1, arg2, &oid, &indx, req);
2076 	if (error)
2077 		goto out;
2078 
2079 	if ((oid->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
2080 		/*
2081 		 * You can't call a sysctl when it's a node, but has
2082 		 * no handler.  Inform the user that it's a node.
2083 		 * The indx may or may not be the same as namelen.
2084 		 */
2085 		if (oid->oid_handler == NULL) {
2086 			error = EISDIR;
2087 			goto out;
2088 		}
2089 	}
2090 
2091 	/* Is this sysctl writable? */
2092 	if (req->newptr && !(oid->oid_kind & CTLFLAG_WR)) {
2093 		error = EPERM;
2094 		goto out;
2095 	}
2096 
2097 	KASSERT(req->td != NULL, ("sysctl_root(): req->td == NULL"));
2098 
2099 #ifdef CAPABILITY_MODE
2100 	/*
2101 	 * If the process is in capability mode, then don't permit reading or
2102 	 * writing unless specifically granted for the node.
2103 	 */
2104 	if (IN_CAPABILITY_MODE(req->td)) {
2105 		if ((req->oldptr && !(oid->oid_kind & CTLFLAG_CAPRD)) ||
2106 		    (req->newptr && !(oid->oid_kind & CTLFLAG_CAPWR))) {
2107 			error = EPERM;
2108 			goto out;
2109 		}
2110 	}
2111 #endif
2112 
2113 	/* Is this sysctl sensitive to securelevels? */
2114 	if (req->newptr && (oid->oid_kind & CTLFLAG_SECURE)) {
2115 		lvl = (oid->oid_kind & CTLMASK_SECURE) >> CTLSHIFT_SECURE;
2116 		error = securelevel_gt(req->td->td_ucred, lvl);
2117 		if (error)
2118 			goto out;
2119 	}
2120 
2121 	/* Is this sysctl writable by only privileged users? */
2122 	if (req->newptr && !(oid->oid_kind & CTLFLAG_ANYBODY)) {
2123 		int priv;
2124 
2125 		if (oid->oid_kind & CTLFLAG_PRISON)
2126 			priv = PRIV_SYSCTL_WRITEJAIL;
2127 #ifdef VIMAGE
2128 		else if ((oid->oid_kind & CTLFLAG_VNET) &&
2129 		     prison_owns_vnet(req->td->td_ucred))
2130 			priv = PRIV_SYSCTL_WRITEJAIL;
2131 #endif
2132 		else
2133 			priv = PRIV_SYSCTL_WRITE;
2134 		error = priv_check(req->td, priv);
2135 		if (error)
2136 			goto out;
2137 	}
2138 
2139 	if (!oid->oid_handler) {
2140 		error = EINVAL;
2141 		goto out;
2142 	}
2143 
2144 	if ((oid->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
2145 		arg1 = (int *)arg1 + indx;
2146 		arg2 -= indx;
2147 	} else {
2148 		arg1 = oid->oid_arg1;
2149 		arg2 = oid->oid_arg2;
2150 	}
2151 #ifdef MAC
2152 	error = mac_system_check_sysctl(req->td->td_ucred, oid, arg1, arg2,
2153 	    req);
2154 	if (error != 0)
2155 		goto out;
2156 #endif
2157 #ifdef VIMAGE
2158 	if ((oid->oid_kind & CTLFLAG_VNET) && arg1 != NULL)
2159 		arg1 = (void *)(curvnet->vnet_data_base + (uintptr_t)arg1);
2160 #endif
2161 	error = sysctl_root_handler_locked(oid, arg1, arg2, req, &tracker);
2162 
2163 out:
2164 	SYSCTL_RUNLOCK(&tracker);
2165 	return (error);
2166 }
2167 
2168 #ifndef _SYS_SYSPROTO_H_
2169 struct sysctl_args {
2170 	int	*name;
2171 	u_int	namelen;
2172 	void	*old;
2173 	size_t	*oldlenp;
2174 	void	*new;
2175 	size_t	newlen;
2176 };
2177 #endif
2178 int
2179 sys___sysctl(struct thread *td, struct sysctl_args *uap)
2180 {
2181 	int error, i, name[CTL_MAXNAME];
2182 	size_t j;
2183 
2184 	if (uap->namelen > CTL_MAXNAME || uap->namelen < 2)
2185 		return (EINVAL);
2186 
2187  	error = copyin(uap->name, &name, uap->namelen * sizeof(int));
2188  	if (error)
2189 		return (error);
2190 
2191 	error = userland_sysctl(td, name, uap->namelen,
2192 		uap->old, uap->oldlenp, 0,
2193 		uap->new, uap->newlen, &j, 0);
2194 	if (error && error != ENOMEM)
2195 		return (error);
2196 	if (uap->oldlenp) {
2197 		i = copyout(&j, uap->oldlenp, sizeof(j));
2198 		if (i)
2199 			return (i);
2200 	}
2201 	return (error);
2202 }
2203 
2204 int
2205 kern___sysctlbyname(struct thread *td, const char *oname, size_t namelen,
2206     void *old, size_t *oldlenp, void *new, size_t newlen, size_t *retval,
2207     int flags, bool inkernel)
2208 {
2209 	int oid[CTL_MAXNAME];
2210 	char namebuf[16];
2211 	char *name;
2212 	size_t oidlen;
2213 	int error;
2214 
2215 	if (namelen > MAXPATHLEN || namelen == 0)
2216 		return (EINVAL);
2217 	name = namebuf;
2218 	if (namelen > sizeof(namebuf))
2219 		name = malloc(namelen, M_SYSCTL, M_WAITOK);
2220 	error = copyin(oname, name, namelen);
2221 	if (error != 0)
2222 		goto out;
2223 
2224 	oid[0] = CTL_SYSCTL;
2225 	oid[1] = CTL_SYSCTL_NAME2OID;
2226 	oidlen = sizeof(oid);
2227 	error = kernel_sysctl(td, oid, 2, oid, &oidlen, (void *)name, namelen,
2228 	    retval, flags);
2229 	if (error != 0)
2230 		goto out;
2231 	error = userland_sysctl(td, oid, *retval / sizeof(int), old, oldlenp,
2232 	    inkernel, new, newlen, retval, flags);
2233 
2234 out:
2235 	if (namelen > sizeof(namebuf))
2236 		free(name, M_SYSCTL);
2237 	return (error);
2238 }
2239 
2240 #ifndef	_SYS_SYSPROTO_H_
2241 struct __sysctlbyname_args {
2242 	const char	*name;
2243 	size_t	namelen;
2244 	void	*old;
2245 	size_t	*oldlenp;
2246 	void	*new;
2247 	size_t	newlen;
2248 };
2249 #endif
2250 int
2251 sys___sysctlbyname(struct thread *td, struct __sysctlbyname_args *uap)
2252 {
2253 	size_t rv;
2254 	int error;
2255 
2256 	error = kern___sysctlbyname(td, uap->name, uap->namelen, uap->old,
2257 	    uap->oldlenp, uap->new, uap->newlen, &rv, 0, 0);
2258 	if (error != 0)
2259 		return (error);
2260 	if (uap->oldlenp != NULL)
2261 		error = copyout(&rv, uap->oldlenp, sizeof(rv));
2262 
2263 	return (error);
2264 }
2265 
2266 /*
2267  * This is used from various compatibility syscalls too.  That's why name
2268  * must be in kernel space.
2269  */
2270 int
2271 userland_sysctl(struct thread *td, int *name, u_int namelen, void *old,
2272     size_t *oldlenp, int inkernel, const void *new, size_t newlen,
2273     size_t *retval, int flags)
2274 {
2275 	int error = 0, memlocked;
2276 	struct sysctl_req req;
2277 
2278 	bzero(&req, sizeof req);
2279 
2280 	req.td = td;
2281 	req.flags = flags;
2282 
2283 	if (oldlenp) {
2284 		if (inkernel) {
2285 			req.oldlen = *oldlenp;
2286 		} else {
2287 			error = copyin(oldlenp, &req.oldlen, sizeof(*oldlenp));
2288 			if (error)
2289 				return (error);
2290 		}
2291 	}
2292 	req.validlen = req.oldlen;
2293 	req.oldptr = old;
2294 
2295 	if (new != NULL) {
2296 		req.newlen = newlen;
2297 		req.newptr = new;
2298 	}
2299 
2300 	req.oldfunc = sysctl_old_user;
2301 	req.newfunc = sysctl_new_user;
2302 	req.lock = REQ_UNWIRED;
2303 
2304 #ifdef KTRACE
2305 	if (KTRPOINT(curthread, KTR_SYSCTL))
2306 		ktrsysctl(name, namelen);
2307 #endif
2308 	memlocked = 0;
2309 	if (req.oldptr && req.oldlen > 4 * PAGE_SIZE) {
2310 		memlocked = 1;
2311 		sx_xlock(&sysctlmemlock);
2312 	}
2313 	CURVNET_SET(TD_TO_VNET(td));
2314 
2315 	for (;;) {
2316 		req.oldidx = 0;
2317 		req.newidx = 0;
2318 		error = sysctl_root(0, name, namelen, &req);
2319 		if (error != EAGAIN)
2320 			break;
2321 		kern_yield(PRI_USER);
2322 	}
2323 
2324 	CURVNET_RESTORE();
2325 
2326 	if (req.lock == REQ_WIRED && req.validlen > 0)
2327 		vsunlock(req.oldptr, req.validlen);
2328 	if (memlocked)
2329 		sx_xunlock(&sysctlmemlock);
2330 
2331 	if (error && error != ENOMEM)
2332 		return (error);
2333 
2334 	if (retval) {
2335 		if (req.oldptr && req.oldidx > req.validlen)
2336 			*retval = req.validlen;
2337 		else
2338 			*retval = req.oldidx;
2339 	}
2340 	return (error);
2341 }
2342 
2343 /*
2344  * Drain into a sysctl struct.  The user buffer should be wired if a page
2345  * fault would cause issue.
2346  */
2347 static int
2348 sbuf_sysctl_drain(void *arg, const char *data, int len)
2349 {
2350 	struct sysctl_req *req = arg;
2351 	int error;
2352 
2353 	error = SYSCTL_OUT(req, data, len);
2354 	KASSERT(error >= 0, ("Got unexpected negative value %d", error));
2355 	return (error == 0 ? len : -error);
2356 }
2357 
2358 struct sbuf *
2359 sbuf_new_for_sysctl(struct sbuf *s, char *buf, int length,
2360     struct sysctl_req *req)
2361 {
2362 
2363 	/* Supply a default buffer size if none given. */
2364 	if (buf == NULL && length == 0)
2365 		length = 64;
2366 	s = sbuf_new(s, buf, length, SBUF_FIXEDLEN | SBUF_INCLUDENUL);
2367 	sbuf_set_drain(s, sbuf_sysctl_drain, req);
2368 	return (s);
2369 }
2370 
2371 #ifdef DDB
2372 
2373 /* The current OID the debugger is working with */
2374 static struct sysctl_oid *g_ddb_oid;
2375 
2376 /* The current flags specified by the user */
2377 static int g_ddb_sysctl_flags;
2378 
2379 /* Check to see if the last sysctl printed */
2380 static int g_ddb_sysctl_printed;
2381 
2382 static const int ctl_sign[CTLTYPE+1] = {
2383 	[CTLTYPE_INT] = 1,
2384 	[CTLTYPE_LONG] = 1,
2385 	[CTLTYPE_S8] = 1,
2386 	[CTLTYPE_S16] = 1,
2387 	[CTLTYPE_S32] = 1,
2388 	[CTLTYPE_S64] = 1,
2389 };
2390 
2391 static const int ctl_size[CTLTYPE+1] = {
2392 	[CTLTYPE_INT] = sizeof(int),
2393 	[CTLTYPE_UINT] = sizeof(u_int),
2394 	[CTLTYPE_LONG] = sizeof(long),
2395 	[CTLTYPE_ULONG] = sizeof(u_long),
2396 	[CTLTYPE_S8] = sizeof(int8_t),
2397 	[CTLTYPE_S16] = sizeof(int16_t),
2398 	[CTLTYPE_S32] = sizeof(int32_t),
2399 	[CTLTYPE_S64] = sizeof(int64_t),
2400 	[CTLTYPE_U8] = sizeof(uint8_t),
2401 	[CTLTYPE_U16] = sizeof(uint16_t),
2402 	[CTLTYPE_U32] = sizeof(uint32_t),
2403 	[CTLTYPE_U64] = sizeof(uint64_t),
2404 };
2405 
2406 #define DB_SYSCTL_NAME_ONLY	0x001	/* Compare with -N */
2407 #define DB_SYSCTL_VALUE_ONLY	0x002	/* Compare with -n */
2408 #define DB_SYSCTL_OPAQUE	0x004	/* Compare with -o */
2409 #define DB_SYSCTL_HEX		0x008	/* Compare with -x */
2410 
2411 #define DB_SYSCTL_SAFE_ONLY	0x100	/* Only simple types */
2412 
2413 static const char db_sysctl_modifs[] = {
2414 	'N', 'n', 'o', 'x',
2415 };
2416 
2417 static const int db_sysctl_modif_values[] = {
2418 	DB_SYSCTL_NAME_ONLY, DB_SYSCTL_VALUE_ONLY,
2419 	DB_SYSCTL_OPAQUE, DB_SYSCTL_HEX,
2420 };
2421 
2422 /* Handlers considered safe to print while recursing */
2423 static int (* const db_safe_handlers[])(SYSCTL_HANDLER_ARGS) = {
2424 	sysctl_handle_bool,
2425 	sysctl_handle_8,
2426 	sysctl_handle_16,
2427 	sysctl_handle_32,
2428 	sysctl_handle_64,
2429 	sysctl_handle_int,
2430 	sysctl_handle_long,
2431 	sysctl_handle_string,
2432 	sysctl_handle_opaque,
2433 };
2434 
2435 /*
2436  * Use in place of sysctl_old_kernel to print sysctl values.
2437  *
2438  * Compare to the output handling in show_var from sbin/sysctl/sysctl.c
2439  */
2440 static int
2441 sysctl_old_ddb(struct sysctl_req *req, const void *ptr, size_t len)
2442 {
2443 	const u_char *val, *p;
2444 	const char *sep1;
2445 	size_t intlen, slen;
2446 	uintmax_t umv;
2447 	intmax_t mv;
2448 	int sign, ctltype, hexlen, xflag, error;
2449 
2450 	/* Suppress false-positive GCC uninitialized variable warnings */
2451 	mv = 0;
2452 	umv = 0;
2453 
2454 	slen = len;
2455 	val = p = ptr;
2456 
2457 	if (ptr == NULL) {
2458 		error = 0;
2459 		goto out;
2460 	}
2461 
2462 	/* We are going to print */
2463 	g_ddb_sysctl_printed = 1;
2464 
2465 	xflag = g_ddb_sysctl_flags & DB_SYSCTL_HEX;
2466 
2467 	ctltype = (g_ddb_oid->oid_kind & CTLTYPE);
2468 	sign = ctl_sign[ctltype];
2469 	intlen = ctl_size[ctltype];
2470 
2471 	switch (ctltype) {
2472 	case CTLTYPE_NODE:
2473 	case CTLTYPE_STRING:
2474 		db_printf("%.*s", (int) len, (const char *) p);
2475 		error = 0;
2476 		goto out;
2477 
2478 	case CTLTYPE_INT:
2479 	case CTLTYPE_UINT:
2480 	case CTLTYPE_LONG:
2481 	case CTLTYPE_ULONG:
2482 	case CTLTYPE_S8:
2483 	case CTLTYPE_S16:
2484 	case CTLTYPE_S32:
2485 	case CTLTYPE_S64:
2486 	case CTLTYPE_U8:
2487 	case CTLTYPE_U16:
2488 	case CTLTYPE_U32:
2489 	case CTLTYPE_U64:
2490 		hexlen = 2 + (intlen * CHAR_BIT + 3) / 4;
2491 		sep1 = "";
2492 		while (len >= intlen) {
2493 			switch (ctltype) {
2494 			case CTLTYPE_INT:
2495 			case CTLTYPE_UINT:
2496 				umv = *(const u_int *)p;
2497 				mv = *(const int *)p;
2498 				break;
2499 			case CTLTYPE_LONG:
2500 			case CTLTYPE_ULONG:
2501 				umv = *(const u_long *)p;
2502 				mv = *(const long *)p;
2503 				break;
2504 			case CTLTYPE_S8:
2505 			case CTLTYPE_U8:
2506 				umv = *(const uint8_t *)p;
2507 				mv = *(const int8_t *)p;
2508 				break;
2509 			case CTLTYPE_S16:
2510 			case CTLTYPE_U16:
2511 				umv = *(const uint16_t *)p;
2512 				mv = *(const int16_t *)p;
2513 				break;
2514 			case CTLTYPE_S32:
2515 			case CTLTYPE_U32:
2516 				umv = *(const uint32_t *)p;
2517 				mv = *(const int32_t *)p;
2518 				break;
2519 			case CTLTYPE_S64:
2520 			case CTLTYPE_U64:
2521 				umv = *(const uint64_t *)p;
2522 				mv = *(const int64_t *)p;
2523 				break;
2524 			}
2525 
2526 			db_printf("%s", sep1);
2527 			if (xflag)
2528 				db_printf("%#0*jx", hexlen, umv);
2529 			else if (!sign)
2530 				db_printf("%ju", umv);
2531 			else if (g_ddb_oid->oid_fmt[1] == 'K') {
2532 				/* Kelvins are currently unsupported. */
2533 				error = EOPNOTSUPP;
2534 				goto out;
2535 			} else
2536 				db_printf("%jd", mv);
2537 
2538 			sep1 = " ";
2539 			len -= intlen;
2540 			p += intlen;
2541 		}
2542 		error = 0;
2543 		goto out;
2544 
2545 	case CTLTYPE_OPAQUE:
2546 		/* TODO: Support struct functions. */
2547 
2548 		/* FALLTHROUGH */
2549 	default:
2550 		db_printf("Format:%s Length:%zu Dump:0x",
2551 		    g_ddb_oid->oid_fmt, len);
2552 		while (len-- && (xflag || p < val + 16))
2553 			db_printf("%02x", *p++);
2554 		if (!xflag && len > 16)
2555 			db_printf("...");
2556 		error = 0;
2557 		goto out;
2558 	}
2559 
2560 out:
2561 	req->oldidx += slen;
2562 	return (error);
2563 }
2564 
2565 /*
2566  * Avoid setting new sysctl values from the debugger
2567  */
2568 static int
2569 sysctl_new_ddb(struct sysctl_req *req, void *p, size_t l)
2570 {
2571 
2572 	if (!req->newptr)
2573 		return (0);
2574 
2575 	/* Changing sysctls from the debugger is currently unsupported */
2576 	return (EPERM);
2577 }
2578 
2579 /*
2580  * Run a sysctl handler with the DDB oldfunc and newfunc attached.
2581  * Instead of copying any output to a buffer we'll dump it right to
2582  * the console.
2583  */
2584 static int
2585 db_sysctl(struct sysctl_oid *oidp, int *name, u_int namelen,
2586     void *old, size_t *oldlenp, size_t *retval, int flags)
2587 {
2588 	struct sysctl_req req;
2589 	int error;
2590 
2591 	/* Setup the request */
2592 	bzero(&req, sizeof req);
2593 	req.td = kdb_thread;
2594 	req.oldfunc = sysctl_old_ddb;
2595 	req.newfunc = sysctl_new_ddb;
2596 	req.lock = REQ_UNWIRED;
2597 	if (oldlenp) {
2598 		req.oldlen = *oldlenp;
2599 	}
2600 	req.validlen = req.oldlen;
2601 	if (old) {
2602 		req.oldptr = old;
2603 	}
2604 
2605 	/* Setup our globals for sysctl_old_ddb */
2606 	g_ddb_oid = oidp;
2607 	g_ddb_sysctl_flags = flags;
2608 	g_ddb_sysctl_printed = 0;
2609 
2610 	error = sysctl_root(0, name, namelen, &req);
2611 
2612 	/* Reset globals */
2613 	g_ddb_oid = NULL;
2614 	g_ddb_sysctl_flags = 0;
2615 
2616 	if (retval) {
2617 		if (req.oldptr && req.oldidx > req.validlen)
2618 			*retval = req.validlen;
2619 		else
2620 			*retval = req.oldidx;
2621 	}
2622 	return (error);
2623 }
2624 
2625 /*
2626  * Show a sysctl's name
2627  */
2628 static void
2629 db_show_oid_name(int *oid, size_t nlen)
2630 {
2631 	struct sysctl_oid *oidp;
2632 	int qoid[CTL_MAXNAME+2];
2633 	int error;
2634 
2635 	qoid[0] = 0;
2636 	memcpy(qoid + 2, oid, nlen * sizeof(int));
2637 	qoid[1] = 1;
2638 
2639 	error = sysctl_find_oid(qoid, nlen + 2, &oidp, NULL, NULL);
2640 	if (error)
2641 		db_error("sysctl name oid");
2642 
2643 	error = db_sysctl(oidp, qoid, nlen + 2, NULL, NULL, NULL, 0);
2644 	if (error)
2645 		db_error("sysctl name");
2646 }
2647 
2648 /*
2649  * Check to see if an OID is safe to print from ddb.
2650  */
2651 static bool
2652 db_oid_safe(const struct sysctl_oid *oidp)
2653 {
2654 	for (unsigned int i = 0; i < nitems(db_safe_handlers); ++i) {
2655 		if (oidp->oid_handler == db_safe_handlers[i])
2656 			return (true);
2657 	}
2658 
2659 	return (false);
2660 }
2661 
2662 /*
2663  * Show a sysctl at a specific OID
2664  * Compare to the input handling in show_var from sbin/sysctl/sysctl.c
2665  */
2666 static int
2667 db_show_oid(struct sysctl_oid *oidp, int *oid, size_t nlen, int flags)
2668 {
2669 	int error, xflag, oflag, Nflag, nflag;
2670 	size_t len;
2671 
2672 	xflag = flags & DB_SYSCTL_HEX;
2673 	oflag = flags & DB_SYSCTL_OPAQUE;
2674 	nflag = flags & DB_SYSCTL_VALUE_ONLY;
2675 	Nflag = flags & DB_SYSCTL_NAME_ONLY;
2676 
2677 	if ((oidp->oid_kind & CTLTYPE) == CTLTYPE_OPAQUE &&
2678 	    (!xflag && !oflag))
2679 		return (0);
2680 
2681 	if (Nflag) {
2682 		db_show_oid_name(oid, nlen);
2683 		error = 0;
2684 		goto out;
2685 	}
2686 
2687 	if (!nflag) {
2688 		db_show_oid_name(oid, nlen);
2689 		db_printf(": ");
2690 	}
2691 
2692 	if ((flags & DB_SYSCTL_SAFE_ONLY) && !db_oid_safe(oidp)) {
2693 		db_printf("Skipping, unsafe to print while recursing.");
2694 		error = 0;
2695 		goto out;
2696 	}
2697 
2698 	/* Try once, and ask about the size */
2699 	len = 0;
2700 	error = db_sysctl(oidp, oid, nlen,
2701 	    NULL, NULL, &len, flags);
2702 	if (error)
2703 		goto out;
2704 
2705 	if (!g_ddb_sysctl_printed)
2706 		/* Lie about the size */
2707 		error = db_sysctl(oidp, oid, nlen,
2708 		    (void *) 1, &len, NULL, flags);
2709 
2710 out:
2711 	db_printf("\n");
2712 	return (error);
2713 }
2714 
2715 /*
2716  * Show all sysctls under a specific OID
2717  * Compare to sysctl_all from sbin/sysctl/sysctl.c
2718  */
2719 static int
2720 db_show_sysctl_all(int *oid, size_t len, int flags)
2721 {
2722 	struct sysctl_oid *oidp;
2723 	int name1[CTL_MAXNAME + 2], name2[CTL_MAXNAME + 2];
2724 	size_t l1, l2;
2725 
2726 	name1[0] = CTL_SYSCTL;
2727 	name1[1] = CTL_SYSCTL_NEXT;
2728 	l1 = 2;
2729 	if (len) {
2730 		memcpy(name1+2, oid, len * sizeof(int));
2731 		l1 +=len;
2732 	} else {
2733 		name1[2] = 1;
2734 		l1++;
2735 	}
2736 	for (;;) {
2737 		int i, error;
2738 
2739 		l2 = sizeof(name2);
2740 		error = kernel_sysctl(kdb_thread, name1, l1,
2741 		    name2, &l2, NULL, 0, &l2, 0);
2742 		if (error != 0) {
2743 			if (error == ENOENT)
2744 				return (0);
2745 			else
2746 				db_error("sysctl(getnext)");
2747 		}
2748 
2749 		l2 /= sizeof(int);
2750 
2751 		if (l2 < (unsigned int)len)
2752 			return (0);
2753 
2754 		for (i = 0; i < len; i++)
2755 			if (name2[i] != oid[i])
2756 				return (0);
2757 
2758 		/* Find the OID in question */
2759 		error = sysctl_find_oid(name2, l2, &oidp, NULL, NULL);
2760 		if (error)
2761 			return (error);
2762 
2763 		i = db_show_oid(oidp, name2, l2, flags | DB_SYSCTL_SAFE_ONLY);
2764 
2765 		if (db_pager_quit)
2766 			return (0);
2767 
2768 		memcpy(name1+2, name2, l2 * sizeof(int));
2769 		l1 = 2 + l2;
2770 	}
2771 }
2772 
2773 /*
2774  * Show a sysctl by its user facing string
2775  */
2776 static int
2777 db_sysctlbyname(char *name, int flags)
2778 {
2779 	struct sysctl_oid *oidp;
2780 	int oid[CTL_MAXNAME];
2781 	int error, nlen;
2782 
2783 	error = name2oid(name, oid, &nlen, &oidp);
2784 	if (error) {
2785 		return (error);
2786 	}
2787 
2788 	if ((oidp->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
2789 		db_show_sysctl_all(oid, nlen, flags);
2790 	} else {
2791 		error = db_show_oid(oidp, oid, nlen, flags);
2792 	}
2793 
2794 	return (error);
2795 }
2796 
2797 static void
2798 db_sysctl_cmd_usage(void)
2799 {
2800 	db_printf(
2801 	    " sysctl [/Nnox] <sysctl>					    \n"
2802 	    "								    \n"
2803 	    " <sysctl> The name of the sysctl to show.			    \n"
2804 	    "								    \n"
2805 	    " Show a sysctl by hooking into SYSCTL_IN and SYSCTL_OUT.	    \n"
2806 	    " This will work for most sysctls, but should not be used	    \n"
2807 	    " with sysctls that are known to malloc.			    \n"
2808 	    "								    \n"
2809 	    " While recursing any \"unsafe\" sysctls will be skipped.	    \n"
2810 	    " Call sysctl directly on the sysctl to try printing the	    \n"
2811 	    " skipped sysctl. This is unsafe and may make the ddb	    \n"
2812 	    " session unusable.						    \n"
2813 	    "								    \n"
2814 	    " Arguments:						    \n"
2815 	    "	/N	Display only the name of the sysctl.		    \n"
2816 	    "	/n	Display only the value of the sysctl.		    \n"
2817 	    "	/o	Display opaque values.				    \n"
2818 	    "	/x	Display the sysctl in hex.			    \n"
2819 	    "								    \n"
2820 	    "For example:						    \n"
2821 	    "sysctl vm.v_free_min					    \n"
2822 	    "vn.v_free_min: 12669					    \n"
2823 	    );
2824 }
2825 
2826 /*
2827  * Show a specific sysctl similar to sysctl (8).
2828  */
2829 DB_FUNC(sysctl, db_sysctl_cmd, db_cmd_table, CS_OWN, NULL)
2830 {
2831 	char name[TOK_STRING_SIZE];
2832 	int error, i, t, flags;
2833 
2834 	/* Parse the modifiers */
2835 	t = db_read_token();
2836 	if (t == tSLASH || t == tMINUS) {
2837 		t = db_read_token();
2838 		if (t != tIDENT) {
2839 			db_printf("Bad modifier\n");
2840 			error = EINVAL;
2841 			goto out;
2842 		}
2843 		db_strcpy(modif, db_tok_string);
2844 	}
2845 	else {
2846 		db_unread_token(t);
2847 		modif[0] = '\0';
2848 	}
2849 
2850 	flags = 0;
2851 	for (i = 0; i < nitems(db_sysctl_modifs); i++) {
2852 		if (strchr(modif, db_sysctl_modifs[i])) {
2853 			flags |= db_sysctl_modif_values[i];
2854 		}
2855 	}
2856 
2857 	/* Parse the sysctl names */
2858 	t = db_read_token();
2859 	if (t != tIDENT) {
2860 		db_printf("Need sysctl name\n");
2861 		error = EINVAL;
2862 		goto out;
2863 	}
2864 
2865 	/* Copy the name into a temporary buffer */
2866 	db_strcpy(name, db_tok_string);
2867 
2868 	/* Ensure there is no trailing cruft */
2869 	t = db_read_token();
2870 	if (t != tEOL) {
2871 		db_printf("Unexpected sysctl argument\n");
2872 		error = EINVAL;
2873 		goto out;
2874 	}
2875 
2876 	error = db_sysctlbyname(name, flags);
2877 	if (error == ENOENT) {
2878 		db_printf("unknown oid: '%s'\n", db_tok_string);
2879 		goto out;
2880 	} else if (error) {
2881 		db_printf("%s: error: %d\n", db_tok_string, error);
2882 		goto out;
2883 	}
2884 
2885 out:
2886 	/* Ensure we eat all of our text */
2887 	db_flush_lex();
2888 
2889 	if (error == EINVAL) {
2890 		db_sysctl_cmd_usage();
2891 	}
2892 }
2893 
2894 #endif /* DDB */
2895