xref: /freebsd/sys/kern/kern_sysctl.c (revision 243e928310d073338c5ec089f0dce238a80b9866)
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Mike Karels at Berkeley Software Design, Inc.
7  *
8  * Quite extensively rewritten by Poul-Henning Kamp of the FreeBSD
9  * project, to make these variables more userfriendly.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  *	@(#)kern_sysctl.c	8.4 (Berkeley) 4/14/94
36  */
37 
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40 
41 #include "opt_capsicum.h"
42 #include "opt_compat.h"
43 #include "opt_ktrace.h"
44 
45 #include <sys/param.h>
46 #include <sys/fail.h>
47 #include <sys/systm.h>
48 #include <sys/capsicum.h>
49 #include <sys/kernel.h>
50 #include <sys/sysctl.h>
51 #include <sys/malloc.h>
52 #include <sys/priv.h>
53 #include <sys/proc.h>
54 #include <sys/jail.h>
55 #include <sys/lock.h>
56 #include <sys/mutex.h>
57 #include <sys/rmlock.h>
58 #include <sys/sbuf.h>
59 #include <sys/sx.h>
60 #include <sys/sysproto.h>
61 #include <sys/uio.h>
62 #ifdef KTRACE
63 #include <sys/ktrace.h>
64 #endif
65 
66 #include <net/vnet.h>
67 
68 #include <security/mac/mac_framework.h>
69 
70 #include <vm/vm.h>
71 #include <vm/vm_extern.h>
72 
73 static MALLOC_DEFINE(M_SYSCTL, "sysctl", "sysctl internal magic");
74 static MALLOC_DEFINE(M_SYSCTLOID, "sysctloid", "sysctl dynamic oids");
75 static MALLOC_DEFINE(M_SYSCTLTMP, "sysctltmp", "sysctl temp output buffer");
76 
77 /*
78  * The sysctllock protects the MIB tree.  It also protects sysctl
79  * contexts used with dynamic sysctls.  The sysctl_register_oid() and
80  * sysctl_unregister_oid() routines require the sysctllock to already
81  * be held, so the sysctl_wlock() and sysctl_wunlock() routines are
82  * provided for the few places in the kernel which need to use that
83  * API rather than using the dynamic API.  Use of the dynamic API is
84  * strongly encouraged for most code.
85  *
86  * The sysctlmemlock is used to limit the amount of user memory wired for
87  * sysctl requests.  This is implemented by serializing any userland
88  * sysctl requests larger than a single page via an exclusive lock.
89  */
90 static struct rmlock sysctllock;
91 static struct sx sysctlmemlock;
92 
93 #define	SYSCTL_WLOCK()		rm_wlock(&sysctllock)
94 #define	SYSCTL_WUNLOCK()	rm_wunlock(&sysctllock)
95 #define	SYSCTL_RLOCK(tracker)	rm_rlock(&sysctllock, (tracker))
96 #define	SYSCTL_RUNLOCK(tracker)	rm_runlock(&sysctllock, (tracker))
97 #define	SYSCTL_WLOCKED()	rm_wowned(&sysctllock)
98 #define	SYSCTL_ASSERT_LOCKED()	rm_assert(&sysctllock, RA_LOCKED)
99 #define	SYSCTL_ASSERT_WLOCKED()	rm_assert(&sysctllock, RA_WLOCKED)
100 #define	SYSCTL_ASSERT_RLOCKED()	rm_assert(&sysctllock, RA_RLOCKED)
101 #define	SYSCTL_INIT()		rm_init_flags(&sysctllock, "sysctl lock", \
102 				    RM_SLEEPABLE)
103 #define	SYSCTL_SLEEP(ch, wmesg, timo)					\
104 				rm_sleep(ch, &sysctllock, 0, wmesg, timo)
105 
106 static int sysctl_root(SYSCTL_HANDLER_ARGS);
107 
108 /* Root list */
109 struct sysctl_oid_list sysctl__children = SLIST_HEAD_INITIALIZER(&sysctl__children);
110 
111 static int	sysctl_remove_oid_locked(struct sysctl_oid *oidp, int del,
112 		    int recurse);
113 static int	sysctl_old_kernel(struct sysctl_req *, const void *, size_t);
114 static int	sysctl_new_kernel(struct sysctl_req *, void *, size_t);
115 
116 static struct sysctl_oid *
117 sysctl_find_oidname(const char *name, struct sysctl_oid_list *list)
118 {
119 	struct sysctl_oid *oidp;
120 
121 	SYSCTL_ASSERT_LOCKED();
122 	SLIST_FOREACH(oidp, list, oid_link) {
123 		if (strcmp(oidp->oid_name, name) == 0) {
124 			return (oidp);
125 		}
126 	}
127 	return (NULL);
128 }
129 
130 /*
131  * Initialization of the MIB tree.
132  *
133  * Order by number in each list.
134  */
135 void
136 sysctl_wlock(void)
137 {
138 
139 	SYSCTL_WLOCK();
140 }
141 
142 void
143 sysctl_wunlock(void)
144 {
145 
146 	SYSCTL_WUNLOCK();
147 }
148 
149 static int
150 sysctl_root_handler_locked(struct sysctl_oid *oid, void *arg1, intmax_t arg2,
151     struct sysctl_req *req, struct rm_priotracker *tracker)
152 {
153 	int error;
154 
155 	if (oid->oid_kind & CTLFLAG_DYN)
156 		atomic_add_int(&oid->oid_running, 1);
157 
158 	if (tracker != NULL)
159 		SYSCTL_RUNLOCK(tracker);
160 	else
161 		SYSCTL_WUNLOCK();
162 
163 	if (!(oid->oid_kind & CTLFLAG_MPSAFE))
164 		mtx_lock(&Giant);
165 	error = oid->oid_handler(oid, arg1, arg2, req);
166 	if (!(oid->oid_kind & CTLFLAG_MPSAFE))
167 		mtx_unlock(&Giant);
168 
169 	KFAIL_POINT_ERROR(_debug_fail_point, sysctl_running, error);
170 
171 	if (tracker != NULL)
172 		SYSCTL_RLOCK(tracker);
173 	else
174 		SYSCTL_WLOCK();
175 
176 	if (oid->oid_kind & CTLFLAG_DYN) {
177 		if (atomic_fetchadd_int(&oid->oid_running, -1) == 1 &&
178 		    (oid->oid_kind & CTLFLAG_DYING) != 0)
179 			wakeup(&oid->oid_running);
180 	}
181 
182 	return (error);
183 }
184 
185 static void
186 sysctl_load_tunable_by_oid_locked(struct sysctl_oid *oidp)
187 {
188 	struct sysctl_req req;
189 	struct sysctl_oid *curr;
190 	char *penv = NULL;
191 	char path[64];
192 	ssize_t rem = sizeof(path);
193 	ssize_t len;
194 	uint8_t val_8;
195 	uint16_t val_16;
196 	uint32_t val_32;
197 	int val_int;
198 	long val_long;
199 	int64_t val_64;
200 	quad_t val_quad;
201 	int error;
202 
203 	path[--rem] = 0;
204 
205 	for (curr = oidp; curr != NULL; curr = SYSCTL_PARENT(curr)) {
206 		len = strlen(curr->oid_name);
207 		rem -= len;
208 		if (curr != oidp)
209 			rem -= 1;
210 		if (rem < 0) {
211 			printf("OID path exceeds %d bytes\n", (int)sizeof(path));
212 			return;
213 		}
214 		memcpy(path + rem, curr->oid_name, len);
215 		if (curr != oidp)
216 			path[rem + len] = '.';
217 	}
218 
219 	memset(&req, 0, sizeof(req));
220 
221 	req.td = curthread;
222 	req.oldfunc = sysctl_old_kernel;
223 	req.newfunc = sysctl_new_kernel;
224 	req.lock = REQ_UNWIRED;
225 
226 	switch (oidp->oid_kind & CTLTYPE) {
227 	case CTLTYPE_INT:
228 		if (getenv_int(path + rem, &val_int) == 0)
229 			return;
230 		req.newlen = sizeof(val_int);
231 		req.newptr = &val_int;
232 		break;
233 	case CTLTYPE_UINT:
234 		if (getenv_uint(path + rem, (unsigned int *)&val_int) == 0)
235 			return;
236 		req.newlen = sizeof(val_int);
237 		req.newptr = &val_int;
238 		break;
239 	case CTLTYPE_LONG:
240 		if (getenv_long(path + rem, &val_long) == 0)
241 			return;
242 		req.newlen = sizeof(val_long);
243 		req.newptr = &val_long;
244 		break;
245 	case CTLTYPE_ULONG:
246 		if (getenv_ulong(path + rem, (unsigned long *)&val_long) == 0)
247 			return;
248 		req.newlen = sizeof(val_long);
249 		req.newptr = &val_long;
250 		break;
251 	case CTLTYPE_S8:
252 		if (getenv_int(path + rem, &val_int) == 0)
253 			return;
254 		val_8 = val_int;
255 		req.newlen = sizeof(val_8);
256 		req.newptr = &val_8;
257 		break;
258 	case CTLTYPE_S16:
259 		if (getenv_int(path + rem, &val_int) == 0)
260 			return;
261 		val_16 = val_int;
262 		req.newlen = sizeof(val_16);
263 		req.newptr = &val_16;
264 		break;
265 	case CTLTYPE_S32:
266 		if (getenv_long(path + rem, &val_long) == 0)
267 			return;
268 		val_32 = val_long;
269 		req.newlen = sizeof(val_32);
270 		req.newptr = &val_32;
271 		break;
272 	case CTLTYPE_S64:
273 		if (getenv_quad(path + rem, &val_quad) == 0)
274 			return;
275 		val_64 = val_quad;
276 		req.newlen = sizeof(val_64);
277 		req.newptr = &val_64;
278 		break;
279 	case CTLTYPE_U8:
280 		if (getenv_uint(path + rem, (unsigned int *)&val_int) == 0)
281 			return;
282 		val_8 = val_int;
283 		req.newlen = sizeof(val_8);
284 		req.newptr = &val_8;
285 		break;
286 	case CTLTYPE_U16:
287 		if (getenv_uint(path + rem, (unsigned int *)&val_int) == 0)
288 			return;
289 		val_16 = val_int;
290 		req.newlen = sizeof(val_16);
291 		req.newptr = &val_16;
292 		break;
293 	case CTLTYPE_U32:
294 		if (getenv_ulong(path + rem, (unsigned long *)&val_long) == 0)
295 			return;
296 		val_32 = val_long;
297 		req.newlen = sizeof(val_32);
298 		req.newptr = &val_32;
299 		break;
300 	case CTLTYPE_U64:
301 		/* XXX there is no getenv_uquad() */
302 		if (getenv_quad(path + rem, &val_quad) == 0)
303 			return;
304 		val_64 = val_quad;
305 		req.newlen = sizeof(val_64);
306 		req.newptr = &val_64;
307 		break;
308 	case CTLTYPE_STRING:
309 		penv = kern_getenv(path + rem);
310 		if (penv == NULL)
311 			return;
312 		req.newlen = strlen(penv);
313 		req.newptr = penv;
314 		break;
315 	default:
316 		return;
317 	}
318 	error = sysctl_root_handler_locked(oidp, oidp->oid_arg1,
319 	    oidp->oid_arg2, &req, NULL);
320 	if (error != 0)
321 		printf("Setting sysctl %s failed: %d\n", path + rem, error);
322 	if (penv != NULL)
323 		freeenv(penv);
324 }
325 
326 void
327 sysctl_register_oid(struct sysctl_oid *oidp)
328 {
329 	struct sysctl_oid_list *parent = oidp->oid_parent;
330 	struct sysctl_oid *p;
331 	struct sysctl_oid *q;
332 	int oid_number;
333 	int timeout = 2;
334 
335 	/*
336 	 * First check if another oid with the same name already
337 	 * exists in the parent's list.
338 	 */
339 	SYSCTL_ASSERT_WLOCKED();
340 	p = sysctl_find_oidname(oidp->oid_name, parent);
341 	if (p != NULL) {
342 		if ((p->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
343 			p->oid_refcnt++;
344 			return;
345 		} else {
346 			printf("can't re-use a leaf (%s)!\n", p->oid_name);
347 			return;
348 		}
349 	}
350 	/* get current OID number */
351 	oid_number = oidp->oid_number;
352 
353 #if (OID_AUTO >= 0)
354 #error "OID_AUTO is expected to be a negative value"
355 #endif
356 	/*
357 	 * Any negative OID number qualifies as OID_AUTO. Valid OID
358 	 * numbers should always be positive.
359 	 *
360 	 * NOTE: DO NOT change the starting value here, change it in
361 	 * <sys/sysctl.h>, and make sure it is at least 256 to
362 	 * accommodate e.g. net.inet.raw as a static sysctl node.
363 	 */
364 	if (oid_number < 0) {
365 		static int newoid;
366 
367 		/*
368 		 * By decrementing the next OID number we spend less
369 		 * time inserting the OIDs into a sorted list.
370 		 */
371 		if (--newoid < CTL_AUTO_START)
372 			newoid = 0x7fffffff;
373 
374 		oid_number = newoid;
375 	}
376 
377 	/*
378 	 * Insert the OID into the parent's list sorted by OID number.
379 	 */
380 retry:
381 	q = NULL;
382 	SLIST_FOREACH(p, parent, oid_link) {
383 		/* check if the current OID number is in use */
384 		if (oid_number == p->oid_number) {
385 			/* get the next valid OID number */
386 			if (oid_number < CTL_AUTO_START ||
387 			    oid_number == 0x7fffffff) {
388 				/* wraparound - restart */
389 				oid_number = CTL_AUTO_START;
390 				/* don't loop forever */
391 				if (!timeout--)
392 					panic("sysctl: Out of OID numbers\n");
393 				goto retry;
394 			} else {
395 				oid_number++;
396 			}
397 		} else if (oid_number < p->oid_number)
398 			break;
399 		q = p;
400 	}
401 	/* check for non-auto OID number collision */
402 	if (oidp->oid_number >= 0 && oidp->oid_number < CTL_AUTO_START &&
403 	    oid_number >= CTL_AUTO_START) {
404 		printf("sysctl: OID number(%d) is already in use for '%s'\n",
405 		    oidp->oid_number, oidp->oid_name);
406 	}
407 	/* update the OID number, if any */
408 	oidp->oid_number = oid_number;
409 	if (q != NULL)
410 		SLIST_INSERT_AFTER(q, oidp, oid_link);
411 	else
412 		SLIST_INSERT_HEAD(parent, oidp, oid_link);
413 
414 	if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE &&
415 #ifdef VIMAGE
416 	    (oidp->oid_kind & CTLFLAG_VNET) == 0 &&
417 #endif
418 	    (oidp->oid_kind & CTLFLAG_TUN) != 0 &&
419 	    (oidp->oid_kind & CTLFLAG_NOFETCH) == 0) {
420 		/* only fetch value once */
421 		oidp->oid_kind |= CTLFLAG_NOFETCH;
422 		/* try to fetch value from kernel environment */
423 		sysctl_load_tunable_by_oid_locked(oidp);
424 	}
425 }
426 
427 void
428 sysctl_unregister_oid(struct sysctl_oid *oidp)
429 {
430 	struct sysctl_oid *p;
431 	int error;
432 
433 	SYSCTL_ASSERT_WLOCKED();
434 	error = ENOENT;
435 	if (oidp->oid_number == OID_AUTO) {
436 		error = EINVAL;
437 	} else {
438 		SLIST_FOREACH(p, oidp->oid_parent, oid_link) {
439 			if (p == oidp) {
440 				SLIST_REMOVE(oidp->oid_parent, oidp,
441 				    sysctl_oid, oid_link);
442 				error = 0;
443 				break;
444 			}
445 		}
446 	}
447 
448 	/*
449 	 * This can happen when a module fails to register and is
450 	 * being unloaded afterwards.  It should not be a panic()
451 	 * for normal use.
452 	 */
453 	if (error)
454 		printf("%s: failed to unregister sysctl\n", __func__);
455 }
456 
457 /* Initialize a new context to keep track of dynamically added sysctls. */
458 int
459 sysctl_ctx_init(struct sysctl_ctx_list *c)
460 {
461 
462 	if (c == NULL) {
463 		return (EINVAL);
464 	}
465 
466 	/*
467 	 * No locking here, the caller is responsible for not adding
468 	 * new nodes to a context until after this function has
469 	 * returned.
470 	 */
471 	TAILQ_INIT(c);
472 	return (0);
473 }
474 
475 /* Free the context, and destroy all dynamic oids registered in this context */
476 int
477 sysctl_ctx_free(struct sysctl_ctx_list *clist)
478 {
479 	struct sysctl_ctx_entry *e, *e1;
480 	int error;
481 
482 	error = 0;
483 	/*
484 	 * First perform a "dry run" to check if it's ok to remove oids.
485 	 * XXX FIXME
486 	 * XXX This algorithm is a hack. But I don't know any
487 	 * XXX better solution for now...
488 	 */
489 	SYSCTL_WLOCK();
490 	TAILQ_FOREACH(e, clist, link) {
491 		error = sysctl_remove_oid_locked(e->entry, 0, 0);
492 		if (error)
493 			break;
494 	}
495 	/*
496 	 * Restore deregistered entries, either from the end,
497 	 * or from the place where error occurred.
498 	 * e contains the entry that was not unregistered
499 	 */
500 	if (error)
501 		e1 = TAILQ_PREV(e, sysctl_ctx_list, link);
502 	else
503 		e1 = TAILQ_LAST(clist, sysctl_ctx_list);
504 	while (e1 != NULL) {
505 		sysctl_register_oid(e1->entry);
506 		e1 = TAILQ_PREV(e1, sysctl_ctx_list, link);
507 	}
508 	if (error) {
509 		SYSCTL_WUNLOCK();
510 		return(EBUSY);
511 	}
512 	/* Now really delete the entries */
513 	e = TAILQ_FIRST(clist);
514 	while (e != NULL) {
515 		e1 = TAILQ_NEXT(e, link);
516 		error = sysctl_remove_oid_locked(e->entry, 1, 0);
517 		if (error)
518 			panic("sysctl_remove_oid: corrupt tree, entry: %s",
519 			    e->entry->oid_name);
520 		free(e, M_SYSCTLOID);
521 		e = e1;
522 	}
523 	SYSCTL_WUNLOCK();
524 	return (error);
525 }
526 
527 /* Add an entry to the context */
528 struct sysctl_ctx_entry *
529 sysctl_ctx_entry_add(struct sysctl_ctx_list *clist, struct sysctl_oid *oidp)
530 {
531 	struct sysctl_ctx_entry *e;
532 
533 	SYSCTL_ASSERT_WLOCKED();
534 	if (clist == NULL || oidp == NULL)
535 		return(NULL);
536 	e = malloc(sizeof(struct sysctl_ctx_entry), M_SYSCTLOID, M_WAITOK);
537 	e->entry = oidp;
538 	TAILQ_INSERT_HEAD(clist, e, link);
539 	return (e);
540 }
541 
542 /* Find an entry in the context */
543 struct sysctl_ctx_entry *
544 sysctl_ctx_entry_find(struct sysctl_ctx_list *clist, struct sysctl_oid *oidp)
545 {
546 	struct sysctl_ctx_entry *e;
547 
548 	SYSCTL_ASSERT_WLOCKED();
549 	if (clist == NULL || oidp == NULL)
550 		return(NULL);
551 	TAILQ_FOREACH(e, clist, link) {
552 		if(e->entry == oidp)
553 			return(e);
554 	}
555 	return (e);
556 }
557 
558 /*
559  * Delete an entry from the context.
560  * NOTE: this function doesn't free oidp! You have to remove it
561  * with sysctl_remove_oid().
562  */
563 int
564 sysctl_ctx_entry_del(struct sysctl_ctx_list *clist, struct sysctl_oid *oidp)
565 {
566 	struct sysctl_ctx_entry *e;
567 
568 	if (clist == NULL || oidp == NULL)
569 		return (EINVAL);
570 	SYSCTL_WLOCK();
571 	e = sysctl_ctx_entry_find(clist, oidp);
572 	if (e != NULL) {
573 		TAILQ_REMOVE(clist, e, link);
574 		SYSCTL_WUNLOCK();
575 		free(e, M_SYSCTLOID);
576 		return (0);
577 	} else {
578 		SYSCTL_WUNLOCK();
579 		return (ENOENT);
580 	}
581 }
582 
583 /*
584  * Remove dynamically created sysctl trees.
585  * oidp - top of the tree to be removed
586  * del - if 0 - just deregister, otherwise free up entries as well
587  * recurse - if != 0 traverse the subtree to be deleted
588  */
589 int
590 sysctl_remove_oid(struct sysctl_oid *oidp, int del, int recurse)
591 {
592 	int error;
593 
594 	SYSCTL_WLOCK();
595 	error = sysctl_remove_oid_locked(oidp, del, recurse);
596 	SYSCTL_WUNLOCK();
597 	return (error);
598 }
599 
600 int
601 sysctl_remove_name(struct sysctl_oid *parent, const char *name,
602     int del, int recurse)
603 {
604 	struct sysctl_oid *p, *tmp;
605 	int error;
606 
607 	error = ENOENT;
608 	SYSCTL_WLOCK();
609 	SLIST_FOREACH_SAFE(p, SYSCTL_CHILDREN(parent), oid_link, tmp) {
610 		if (strcmp(p->oid_name, name) == 0) {
611 			error = sysctl_remove_oid_locked(p, del, recurse);
612 			break;
613 		}
614 	}
615 	SYSCTL_WUNLOCK();
616 
617 	return (error);
618 }
619 
620 
621 static int
622 sysctl_remove_oid_locked(struct sysctl_oid *oidp, int del, int recurse)
623 {
624 	struct sysctl_oid *p, *tmp;
625 	int error;
626 
627 	SYSCTL_ASSERT_WLOCKED();
628 	if (oidp == NULL)
629 		return(EINVAL);
630 	if ((oidp->oid_kind & CTLFLAG_DYN) == 0) {
631 		printf("can't remove non-dynamic nodes!\n");
632 		return (EINVAL);
633 	}
634 	/*
635 	 * WARNING: normal method to do this should be through
636 	 * sysctl_ctx_free(). Use recursing as the last resort
637 	 * method to purge your sysctl tree of leftovers...
638 	 * However, if some other code still references these nodes,
639 	 * it will panic.
640 	 */
641 	if ((oidp->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
642 		if (oidp->oid_refcnt == 1) {
643 			SLIST_FOREACH_SAFE(p,
644 			    SYSCTL_CHILDREN(oidp), oid_link, tmp) {
645 				if (!recurse) {
646 					printf("Warning: failed attempt to "
647 					    "remove oid %s with child %s\n",
648 					    oidp->oid_name, p->oid_name);
649 					return (ENOTEMPTY);
650 				}
651 				error = sysctl_remove_oid_locked(p, del,
652 				    recurse);
653 				if (error)
654 					return (error);
655 			}
656 		}
657 	}
658 	if (oidp->oid_refcnt > 1 ) {
659 		oidp->oid_refcnt--;
660 	} else {
661 		if (oidp->oid_refcnt == 0) {
662 			printf("Warning: bad oid_refcnt=%u (%s)!\n",
663 				oidp->oid_refcnt, oidp->oid_name);
664 			return (EINVAL);
665 		}
666 		sysctl_unregister_oid(oidp);
667 		if (del) {
668 			/*
669 			 * Wait for all threads running the handler to drain.
670 			 * This preserves the previous behavior when the
671 			 * sysctl lock was held across a handler invocation,
672 			 * and is necessary for module unload correctness.
673 			 */
674 			while (oidp->oid_running > 0) {
675 				oidp->oid_kind |= CTLFLAG_DYING;
676 				SYSCTL_SLEEP(&oidp->oid_running, "oidrm", 0);
677 			}
678 			if (oidp->oid_descr)
679 				free(__DECONST(char *, oidp->oid_descr),
680 				    M_SYSCTLOID);
681 			free(__DECONST(char *, oidp->oid_name), M_SYSCTLOID);
682 			free(oidp, M_SYSCTLOID);
683 		}
684 	}
685 	return (0);
686 }
687 /*
688  * Create new sysctls at run time.
689  * clist may point to a valid context initialized with sysctl_ctx_init().
690  */
691 struct sysctl_oid *
692 sysctl_add_oid(struct sysctl_ctx_list *clist, struct sysctl_oid_list *parent,
693 	int number, const char *name, int kind, void *arg1, intmax_t arg2,
694 	int (*handler)(SYSCTL_HANDLER_ARGS), const char *fmt, const char *descr)
695 {
696 	struct sysctl_oid *oidp;
697 
698 	/* You have to hook up somewhere.. */
699 	if (parent == NULL)
700 		return(NULL);
701 	/* Check if the node already exists, otherwise create it */
702 	SYSCTL_WLOCK();
703 	oidp = sysctl_find_oidname(name, parent);
704 	if (oidp != NULL) {
705 		if ((oidp->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
706 			oidp->oid_refcnt++;
707 			/* Update the context */
708 			if (clist != NULL)
709 				sysctl_ctx_entry_add(clist, oidp);
710 			SYSCTL_WUNLOCK();
711 			return (oidp);
712 		} else {
713 			SYSCTL_WUNLOCK();
714 			printf("can't re-use a leaf (%s)!\n", name);
715 			return (NULL);
716 		}
717 	}
718 	oidp = malloc(sizeof(struct sysctl_oid), M_SYSCTLOID, M_WAITOK|M_ZERO);
719 	oidp->oid_parent = parent;
720 	SLIST_INIT(&oidp->oid_children);
721 	oidp->oid_number = number;
722 	oidp->oid_refcnt = 1;
723 	oidp->oid_name = strdup(name, M_SYSCTLOID);
724 	oidp->oid_handler = handler;
725 	oidp->oid_kind = CTLFLAG_DYN | kind;
726 	oidp->oid_arg1 = arg1;
727 	oidp->oid_arg2 = arg2;
728 	oidp->oid_fmt = fmt;
729 	if (descr != NULL)
730 		oidp->oid_descr = strdup(descr, M_SYSCTLOID);
731 	/* Update the context, if used */
732 	if (clist != NULL)
733 		sysctl_ctx_entry_add(clist, oidp);
734 	/* Register this oid */
735 	sysctl_register_oid(oidp);
736 	SYSCTL_WUNLOCK();
737 	return (oidp);
738 }
739 
740 /*
741  * Rename an existing oid.
742  */
743 void
744 sysctl_rename_oid(struct sysctl_oid *oidp, const char *name)
745 {
746 	char *newname;
747 	char *oldname;
748 
749 	newname = strdup(name, M_SYSCTLOID);
750 	SYSCTL_WLOCK();
751 	oldname = __DECONST(char *, oidp->oid_name);
752 	oidp->oid_name = newname;
753 	SYSCTL_WUNLOCK();
754 	free(oldname, M_SYSCTLOID);
755 }
756 
757 /*
758  * Reparent an existing oid.
759  */
760 int
761 sysctl_move_oid(struct sysctl_oid *oid, struct sysctl_oid_list *parent)
762 {
763 	struct sysctl_oid *oidp;
764 
765 	SYSCTL_WLOCK();
766 	if (oid->oid_parent == parent) {
767 		SYSCTL_WUNLOCK();
768 		return (0);
769 	}
770 	oidp = sysctl_find_oidname(oid->oid_name, parent);
771 	if (oidp != NULL) {
772 		SYSCTL_WUNLOCK();
773 		return (EEXIST);
774 	}
775 	sysctl_unregister_oid(oid);
776 	oid->oid_parent = parent;
777 	oid->oid_number = OID_AUTO;
778 	sysctl_register_oid(oid);
779 	SYSCTL_WUNLOCK();
780 	return (0);
781 }
782 
783 /*
784  * Register the kernel's oids on startup.
785  */
786 SET_DECLARE(sysctl_set, struct sysctl_oid);
787 
788 static void
789 sysctl_register_all(void *arg)
790 {
791 	struct sysctl_oid **oidp;
792 
793 	sx_init(&sysctlmemlock, "sysctl mem");
794 	SYSCTL_INIT();
795 	SYSCTL_WLOCK();
796 	SET_FOREACH(oidp, sysctl_set)
797 		sysctl_register_oid(*oidp);
798 	SYSCTL_WUNLOCK();
799 }
800 SYSINIT(sysctl, SI_SUB_KMEM, SI_ORDER_FIRST, sysctl_register_all, 0);
801 
802 /*
803  * "Staff-functions"
804  *
805  * These functions implement a presently undocumented interface
806  * used by the sysctl program to walk the tree, and get the type
807  * so it can print the value.
808  * This interface is under work and consideration, and should probably
809  * be killed with a big axe by the first person who can find the time.
810  * (be aware though, that the proper interface isn't as obvious as it
811  * may seem, there are various conflicting requirements.
812  *
813  * {0,0}	printf the entire MIB-tree.
814  * {0,1,...}	return the name of the "..." OID.
815  * {0,2,...}	return the next OID.
816  * {0,3}	return the OID of the name in "new"
817  * {0,4,...}	return the kind & format info for the "..." OID.
818  * {0,5,...}	return the description the "..." OID.
819  */
820 
821 #ifdef SYSCTL_DEBUG
822 static void
823 sysctl_sysctl_debug_dump_node(struct sysctl_oid_list *l, int i)
824 {
825 	int k;
826 	struct sysctl_oid *oidp;
827 
828 	SYSCTL_ASSERT_LOCKED();
829 	SLIST_FOREACH(oidp, l, oid_link) {
830 
831 		for (k=0; k<i; k++)
832 			printf(" ");
833 
834 		printf("%d %s ", oidp->oid_number, oidp->oid_name);
835 
836 		printf("%c%c",
837 			oidp->oid_kind & CTLFLAG_RD ? 'R':' ',
838 			oidp->oid_kind & CTLFLAG_WR ? 'W':' ');
839 
840 		if (oidp->oid_handler)
841 			printf(" *Handler");
842 
843 		switch (oidp->oid_kind & CTLTYPE) {
844 			case CTLTYPE_NODE:
845 				printf(" Node\n");
846 				if (!oidp->oid_handler) {
847 					sysctl_sysctl_debug_dump_node(
848 					    SYSCTL_CHILDREN(oidp), i + 2);
849 				}
850 				break;
851 			case CTLTYPE_INT:    printf(" Int\n"); break;
852 			case CTLTYPE_UINT:   printf(" u_int\n"); break;
853 			case CTLTYPE_LONG:   printf(" Long\n"); break;
854 			case CTLTYPE_ULONG:  printf(" u_long\n"); break;
855 			case CTLTYPE_STRING: printf(" String\n"); break;
856 			case CTLTYPE_S8:     printf(" int8_t\n"); break;
857 			case CTLTYPE_S16:    printf(" int16_t\n"); break;
858 			case CTLTYPE_S32:    printf(" int32_t\n"); break;
859 			case CTLTYPE_S64:    printf(" int64_t\n"); break;
860 			case CTLTYPE_U8:     printf(" uint8_t\n"); break;
861 			case CTLTYPE_U16:    printf(" uint16_t\n"); break;
862 			case CTLTYPE_U32:    printf(" uint32_t\n"); break;
863 			case CTLTYPE_U64:    printf(" uint64_t\n"); break;
864 			case CTLTYPE_OPAQUE: printf(" Opaque/struct\n"); break;
865 			default:	     printf("\n");
866 		}
867 
868 	}
869 }
870 
871 static int
872 sysctl_sysctl_debug(SYSCTL_HANDLER_ARGS)
873 {
874 	struct rm_priotracker tracker;
875 	int error;
876 
877 	error = priv_check(req->td, PRIV_SYSCTL_DEBUG);
878 	if (error)
879 		return (error);
880 	SYSCTL_RLOCK(&tracker);
881 	sysctl_sysctl_debug_dump_node(&sysctl__children, 0);
882 	SYSCTL_RUNLOCK(&tracker);
883 	return (ENOENT);
884 }
885 
886 SYSCTL_PROC(_sysctl, 0, debug, CTLTYPE_STRING|CTLFLAG_RD|CTLFLAG_MPSAFE,
887 	0, 0, sysctl_sysctl_debug, "-", "");
888 #endif
889 
890 static int
891 sysctl_sysctl_name(SYSCTL_HANDLER_ARGS)
892 {
893 	int *name = (int *) arg1;
894 	u_int namelen = arg2;
895 	int error = 0;
896 	struct sysctl_oid *oid;
897 	struct sysctl_oid_list *lsp = &sysctl__children, *lsp2;
898 	struct rm_priotracker tracker;
899 	char buf[10];
900 
901 	SYSCTL_RLOCK(&tracker);
902 	while (namelen) {
903 		if (!lsp) {
904 			snprintf(buf,sizeof(buf),"%d",*name);
905 			if (req->oldidx)
906 				error = SYSCTL_OUT(req, ".", 1);
907 			if (!error)
908 				error = SYSCTL_OUT(req, buf, strlen(buf));
909 			if (error)
910 				goto out;
911 			namelen--;
912 			name++;
913 			continue;
914 		}
915 		lsp2 = NULL;
916 		SLIST_FOREACH(oid, lsp, oid_link) {
917 			if (oid->oid_number != *name)
918 				continue;
919 
920 			if (req->oldidx)
921 				error = SYSCTL_OUT(req, ".", 1);
922 			if (!error)
923 				error = SYSCTL_OUT(req, oid->oid_name,
924 					strlen(oid->oid_name));
925 			if (error)
926 				goto out;
927 
928 			namelen--;
929 			name++;
930 
931 			if ((oid->oid_kind & CTLTYPE) != CTLTYPE_NODE)
932 				break;
933 
934 			if (oid->oid_handler)
935 				break;
936 
937 			lsp2 = SYSCTL_CHILDREN(oid);
938 			break;
939 		}
940 		lsp = lsp2;
941 	}
942 	error = SYSCTL_OUT(req, "", 1);
943  out:
944 	SYSCTL_RUNLOCK(&tracker);
945 	return (error);
946 }
947 
948 /*
949  * XXXRW/JA: Shouldn't return name data for nodes that we don't permit in
950  * capability mode.
951  */
952 static SYSCTL_NODE(_sysctl, 1, name, CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_CAPRD,
953     sysctl_sysctl_name, "");
954 
955 static int
956 sysctl_sysctl_next_ls(struct sysctl_oid_list *lsp, int *name, u_int namelen,
957 	int *next, int *len, int level, struct sysctl_oid **oidpp)
958 {
959 	struct sysctl_oid *oidp;
960 
961 	SYSCTL_ASSERT_LOCKED();
962 	*len = level;
963 	SLIST_FOREACH(oidp, lsp, oid_link) {
964 		*next = oidp->oid_number;
965 		*oidpp = oidp;
966 
967 		if (oidp->oid_kind & CTLFLAG_SKIP)
968 			continue;
969 
970 		if (!namelen) {
971 			if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
972 				return (0);
973 			if (oidp->oid_handler)
974 				/* We really should call the handler here...*/
975 				return (0);
976 			lsp = SYSCTL_CHILDREN(oidp);
977 			if (!sysctl_sysctl_next_ls(lsp, 0, 0, next+1,
978 				len, level+1, oidpp))
979 				return (0);
980 			goto emptynode;
981 		}
982 
983 		if (oidp->oid_number < *name)
984 			continue;
985 
986 		if (oidp->oid_number > *name) {
987 			if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
988 				return (0);
989 			if (oidp->oid_handler)
990 				return (0);
991 			lsp = SYSCTL_CHILDREN(oidp);
992 			if (!sysctl_sysctl_next_ls(lsp, name+1, namelen-1,
993 				next+1, len, level+1, oidpp))
994 				return (0);
995 			goto next;
996 		}
997 		if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
998 			continue;
999 
1000 		if (oidp->oid_handler)
1001 			continue;
1002 
1003 		lsp = SYSCTL_CHILDREN(oidp);
1004 		if (!sysctl_sysctl_next_ls(lsp, name+1, namelen-1, next+1,
1005 			len, level+1, oidpp))
1006 			return (0);
1007 	next:
1008 		namelen = 1;
1009 	emptynode:
1010 		*len = level;
1011 	}
1012 	return (1);
1013 }
1014 
1015 static int
1016 sysctl_sysctl_next(SYSCTL_HANDLER_ARGS)
1017 {
1018 	int *name = (int *) arg1;
1019 	u_int namelen = arg2;
1020 	int i, j, error;
1021 	struct sysctl_oid *oid;
1022 	struct sysctl_oid_list *lsp = &sysctl__children;
1023 	struct rm_priotracker tracker;
1024 	int newoid[CTL_MAXNAME];
1025 
1026 	SYSCTL_RLOCK(&tracker);
1027 	i = sysctl_sysctl_next_ls(lsp, name, namelen, newoid, &j, 1, &oid);
1028 	SYSCTL_RUNLOCK(&tracker);
1029 	if (i)
1030 		return (ENOENT);
1031 	error = SYSCTL_OUT(req, newoid, j * sizeof (int));
1032 	return (error);
1033 }
1034 
1035 /*
1036  * XXXRW/JA: Shouldn't return next data for nodes that we don't permit in
1037  * capability mode.
1038  */
1039 static SYSCTL_NODE(_sysctl, 2, next, CTLFLAG_RD | CTLFLAG_MPSAFE | CTLFLAG_CAPRD,
1040     sysctl_sysctl_next, "");
1041 
1042 static int
1043 name2oid(char *name, int *oid, int *len, struct sysctl_oid **oidpp)
1044 {
1045 	struct sysctl_oid *oidp;
1046 	struct sysctl_oid_list *lsp = &sysctl__children;
1047 	char *p;
1048 
1049 	SYSCTL_ASSERT_LOCKED();
1050 
1051 	for (*len = 0; *len < CTL_MAXNAME;) {
1052 		p = strsep(&name, ".");
1053 
1054 		oidp = SLIST_FIRST(lsp);
1055 		for (;; oidp = SLIST_NEXT(oidp, oid_link)) {
1056 			if (oidp == NULL)
1057 				return (ENOENT);
1058 			if (strcmp(p, oidp->oid_name) == 0)
1059 				break;
1060 		}
1061 		*oid++ = oidp->oid_number;
1062 		(*len)++;
1063 
1064 		if (name == NULL || *name == '\0') {
1065 			if (oidpp)
1066 				*oidpp = oidp;
1067 			return (0);
1068 		}
1069 
1070 		if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
1071 			break;
1072 
1073 		if (oidp->oid_handler)
1074 			break;
1075 
1076 		lsp = SYSCTL_CHILDREN(oidp);
1077 	}
1078 	return (ENOENT);
1079 }
1080 
1081 static int
1082 sysctl_sysctl_name2oid(SYSCTL_HANDLER_ARGS)
1083 {
1084 	char *p;
1085 	int error, oid[CTL_MAXNAME], len = 0;
1086 	struct sysctl_oid *op = NULL;
1087 	struct rm_priotracker tracker;
1088 
1089 	if (!req->newlen)
1090 		return (ENOENT);
1091 	if (req->newlen >= MAXPATHLEN)	/* XXX arbitrary, undocumented */
1092 		return (ENAMETOOLONG);
1093 
1094 	p = malloc(req->newlen+1, M_SYSCTL, M_WAITOK);
1095 
1096 	error = SYSCTL_IN(req, p, req->newlen);
1097 	if (error) {
1098 		free(p, M_SYSCTL);
1099 		return (error);
1100 	}
1101 
1102 	p [req->newlen] = '\0';
1103 
1104 	SYSCTL_RLOCK(&tracker);
1105 	error = name2oid(p, oid, &len, &op);
1106 	SYSCTL_RUNLOCK(&tracker);
1107 
1108 	free(p, M_SYSCTL);
1109 
1110 	if (error)
1111 		return (error);
1112 
1113 	error = SYSCTL_OUT(req, oid, len * sizeof *oid);
1114 	return (error);
1115 }
1116 
1117 /*
1118  * XXXRW/JA: Shouldn't return name2oid data for nodes that we don't permit in
1119  * capability mode.
1120  */
1121 SYSCTL_PROC(_sysctl, 3, name2oid,
1122     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_MPSAFE
1123     | CTLFLAG_CAPRW, 0, 0, sysctl_sysctl_name2oid, "I", "");
1124 
1125 static int
1126 sysctl_sysctl_oidfmt(SYSCTL_HANDLER_ARGS)
1127 {
1128 	struct sysctl_oid *oid;
1129 	struct rm_priotracker tracker;
1130 	int error;
1131 
1132 	SYSCTL_RLOCK(&tracker);
1133 	error = sysctl_find_oid(arg1, arg2, &oid, NULL, req);
1134 	if (error)
1135 		goto out;
1136 
1137 	if (oid->oid_fmt == NULL) {
1138 		error = ENOENT;
1139 		goto out;
1140 	}
1141 	error = SYSCTL_OUT(req, &oid->oid_kind, sizeof(oid->oid_kind));
1142 	if (error)
1143 		goto out;
1144 	error = SYSCTL_OUT(req, oid->oid_fmt, strlen(oid->oid_fmt) + 1);
1145  out:
1146 	SYSCTL_RUNLOCK(&tracker);
1147 	return (error);
1148 }
1149 
1150 
1151 static SYSCTL_NODE(_sysctl, 4, oidfmt, CTLFLAG_RD|CTLFLAG_MPSAFE|CTLFLAG_CAPRD,
1152     sysctl_sysctl_oidfmt, "");
1153 
1154 static int
1155 sysctl_sysctl_oiddescr(SYSCTL_HANDLER_ARGS)
1156 {
1157 	struct sysctl_oid *oid;
1158 	struct rm_priotracker tracker;
1159 	int error;
1160 
1161 	SYSCTL_RLOCK(&tracker);
1162 	error = sysctl_find_oid(arg1, arg2, &oid, NULL, req);
1163 	if (error)
1164 		goto out;
1165 
1166 	if (oid->oid_descr == NULL) {
1167 		error = ENOENT;
1168 		goto out;
1169 	}
1170 	error = SYSCTL_OUT(req, oid->oid_descr, strlen(oid->oid_descr) + 1);
1171  out:
1172 	SYSCTL_RUNLOCK(&tracker);
1173 	return (error);
1174 }
1175 
1176 static SYSCTL_NODE(_sysctl, 5, oiddescr, CTLFLAG_RD|CTLFLAG_MPSAFE|CTLFLAG_CAPRD,
1177     sysctl_sysctl_oiddescr, "");
1178 
1179 /*
1180  * Default "handler" functions.
1181  */
1182 
1183 /*
1184  * Handle an int8_t, signed or unsigned.
1185  * Two cases:
1186  *     a variable:  point arg1 at it.
1187  *     a constant:  pass it in arg2.
1188  */
1189 
1190 int
1191 sysctl_handle_8(SYSCTL_HANDLER_ARGS)
1192 {
1193 	int8_t tmpout;
1194 	int error = 0;
1195 
1196 	/*
1197 	 * Attempt to get a coherent snapshot by making a copy of the data.
1198 	 */
1199 	if (arg1)
1200 		tmpout = *(int8_t *)arg1;
1201 	else
1202 		tmpout = arg2;
1203 	error = SYSCTL_OUT(req, &tmpout, sizeof(tmpout));
1204 
1205 	if (error || !req->newptr)
1206 		return (error);
1207 
1208 	if (!arg1)
1209 		error = EPERM;
1210 	else
1211 		error = SYSCTL_IN(req, arg1, sizeof(tmpout));
1212 	return (error);
1213 }
1214 
1215 /*
1216  * Handle an int16_t, signed or unsigned.
1217  * Two cases:
1218  *     a variable:  point arg1 at it.
1219  *     a constant:  pass it in arg2.
1220  */
1221 
1222 int
1223 sysctl_handle_16(SYSCTL_HANDLER_ARGS)
1224 {
1225 	int16_t tmpout;
1226 	int error = 0;
1227 
1228 	/*
1229 	 * Attempt to get a coherent snapshot by making a copy of the data.
1230 	 */
1231 	if (arg1)
1232 		tmpout = *(int16_t *)arg1;
1233 	else
1234 		tmpout = arg2;
1235 	error = SYSCTL_OUT(req, &tmpout, sizeof(tmpout));
1236 
1237 	if (error || !req->newptr)
1238 		return (error);
1239 
1240 	if (!arg1)
1241 		error = EPERM;
1242 	else
1243 		error = SYSCTL_IN(req, arg1, sizeof(tmpout));
1244 	return (error);
1245 }
1246 
1247 /*
1248  * Handle an int32_t, signed or unsigned.
1249  * Two cases:
1250  *     a variable:  point arg1 at it.
1251  *     a constant:  pass it in arg2.
1252  */
1253 
1254 int
1255 sysctl_handle_32(SYSCTL_HANDLER_ARGS)
1256 {
1257 	int32_t tmpout;
1258 	int error = 0;
1259 
1260 	/*
1261 	 * Attempt to get a coherent snapshot by making a copy of the data.
1262 	 */
1263 	if (arg1)
1264 		tmpout = *(int32_t *)arg1;
1265 	else
1266 		tmpout = arg2;
1267 	error = SYSCTL_OUT(req, &tmpout, sizeof(tmpout));
1268 
1269 	if (error || !req->newptr)
1270 		return (error);
1271 
1272 	if (!arg1)
1273 		error = EPERM;
1274 	else
1275 		error = SYSCTL_IN(req, arg1, sizeof(tmpout));
1276 	return (error);
1277 }
1278 
1279 /*
1280  * Handle an int, signed or unsigned.
1281  * Two cases:
1282  *     a variable:  point arg1 at it.
1283  *     a constant:  pass it in arg2.
1284  */
1285 
1286 int
1287 sysctl_handle_int(SYSCTL_HANDLER_ARGS)
1288 {
1289 	int tmpout, error = 0;
1290 
1291 	/*
1292 	 * Attempt to get a coherent snapshot by making a copy of the data.
1293 	 */
1294 	if (arg1)
1295 		tmpout = *(int *)arg1;
1296 	else
1297 		tmpout = arg2;
1298 	error = SYSCTL_OUT(req, &tmpout, sizeof(int));
1299 
1300 	if (error || !req->newptr)
1301 		return (error);
1302 
1303 	if (!arg1)
1304 		error = EPERM;
1305 	else
1306 		error = SYSCTL_IN(req, arg1, sizeof(int));
1307 	return (error);
1308 }
1309 
1310 /*
1311  * Based on on sysctl_handle_int() convert milliseconds into ticks.
1312  * Note: this is used by TCP.
1313  */
1314 
1315 int
1316 sysctl_msec_to_ticks(SYSCTL_HANDLER_ARGS)
1317 {
1318 	int error, s, tt;
1319 
1320 	tt = *(int *)arg1;
1321 	s = (int)((int64_t)tt * 1000 / hz);
1322 
1323 	error = sysctl_handle_int(oidp, &s, 0, req);
1324 	if (error || !req->newptr)
1325 		return (error);
1326 
1327 	tt = (int)((int64_t)s * hz / 1000);
1328 	if (tt < 1)
1329 		return (EINVAL);
1330 
1331 	*(int *)arg1 = tt;
1332 	return (0);
1333 }
1334 
1335 
1336 /*
1337  * Handle a long, signed or unsigned.
1338  * Two cases:
1339  *     a variable:  point arg1 at it.
1340  *     a constant:  pass it in arg2.
1341  */
1342 
1343 int
1344 sysctl_handle_long(SYSCTL_HANDLER_ARGS)
1345 {
1346 	int error = 0;
1347 	long tmplong;
1348 #ifdef SCTL_MASK32
1349 	int tmpint;
1350 #endif
1351 
1352 	/*
1353 	 * Attempt to get a coherent snapshot by making a copy of the data.
1354 	 */
1355 	if (arg1)
1356 		tmplong = *(long *)arg1;
1357 	else
1358 		tmplong = arg2;
1359 #ifdef SCTL_MASK32
1360 	if (req->flags & SCTL_MASK32) {
1361 		tmpint = tmplong;
1362 		error = SYSCTL_OUT(req, &tmpint, sizeof(int));
1363 	} else
1364 #endif
1365 		error = SYSCTL_OUT(req, &tmplong, sizeof(long));
1366 
1367 	if (error || !req->newptr)
1368 		return (error);
1369 
1370 	if (!arg1)
1371 		error = EPERM;
1372 #ifdef SCTL_MASK32
1373 	else if (req->flags & SCTL_MASK32) {
1374 		error = SYSCTL_IN(req, &tmpint, sizeof(int));
1375 		*(long *)arg1 = (long)tmpint;
1376 	}
1377 #endif
1378 	else
1379 		error = SYSCTL_IN(req, arg1, sizeof(long));
1380 	return (error);
1381 }
1382 
1383 /*
1384  * Handle a 64 bit int, signed or unsigned.
1385  * Two cases:
1386  *     a variable:  point arg1 at it.
1387  *     a constant:  pass it in arg2.
1388  */
1389 int
1390 sysctl_handle_64(SYSCTL_HANDLER_ARGS)
1391 {
1392 	int error = 0;
1393 	uint64_t tmpout;
1394 
1395 	/*
1396 	 * Attempt to get a coherent snapshot by making a copy of the data.
1397 	 */
1398 	if (arg1)
1399 		tmpout = *(uint64_t *)arg1;
1400 	else
1401 		tmpout = arg2;
1402 	error = SYSCTL_OUT(req, &tmpout, sizeof(uint64_t));
1403 
1404 	if (error || !req->newptr)
1405 		return (error);
1406 
1407 	if (!arg1)
1408 		error = EPERM;
1409 	else
1410 		error = SYSCTL_IN(req, arg1, sizeof(uint64_t));
1411 	return (error);
1412 }
1413 
1414 /*
1415  * Handle our generic '\0' terminated 'C' string.
1416  * Two cases:
1417  * 	a variable string:  point arg1 at it, arg2 is max length.
1418  * 	a constant string:  point arg1 at it, arg2 is zero.
1419  */
1420 
1421 int
1422 sysctl_handle_string(SYSCTL_HANDLER_ARGS)
1423 {
1424 	size_t outlen;
1425 	int error = 0, ro_string = 0;
1426 
1427 	/*
1428 	 * A zero-length buffer indicates a fixed size read-only
1429 	 * string:
1430 	 */
1431 	if (arg2 == 0) {
1432 		arg2 = strlen((char *)arg1) + 1;
1433 		ro_string = 1;
1434 	}
1435 
1436 	if (req->oldptr != NULL) {
1437 		char *tmparg;
1438 
1439 		if (ro_string) {
1440 			tmparg = arg1;
1441 		} else {
1442 			/* try to make a coherent snapshot of the string */
1443 			tmparg = malloc(arg2, M_SYSCTLTMP, M_WAITOK);
1444 			memcpy(tmparg, arg1, arg2);
1445 		}
1446 
1447 		outlen = strnlen(tmparg, arg2 - 1) + 1;
1448 		error = SYSCTL_OUT(req, tmparg, outlen);
1449 
1450 		if (!ro_string)
1451 			free(tmparg, M_SYSCTLTMP);
1452 	} else {
1453 		outlen = strnlen((char *)arg1, arg2 - 1) + 1;
1454 		error = SYSCTL_OUT(req, NULL, outlen);
1455 	}
1456 	if (error || !req->newptr)
1457 		return (error);
1458 
1459 	if ((req->newlen - req->newidx) >= arg2) {
1460 		error = EINVAL;
1461 	} else {
1462 		arg2 = (req->newlen - req->newidx);
1463 		error = SYSCTL_IN(req, arg1, arg2);
1464 		((char *)arg1)[arg2] = '\0';
1465 	}
1466 	return (error);
1467 }
1468 
1469 /*
1470  * Handle any kind of opaque data.
1471  * arg1 points to it, arg2 is the size.
1472  */
1473 
1474 int
1475 sysctl_handle_opaque(SYSCTL_HANDLER_ARGS)
1476 {
1477 	int error, tries;
1478 	u_int generation;
1479 	struct sysctl_req req2;
1480 
1481 	/*
1482 	 * Attempt to get a coherent snapshot, by using the thread
1483 	 * pre-emption counter updated from within mi_switch() to
1484 	 * determine if we were pre-empted during a bcopy() or
1485 	 * copyout(). Make 3 attempts at doing this before giving up.
1486 	 * If we encounter an error, stop immediately.
1487 	 */
1488 	tries = 0;
1489 	req2 = *req;
1490 retry:
1491 	generation = curthread->td_generation;
1492 	error = SYSCTL_OUT(req, arg1, arg2);
1493 	if (error)
1494 		return (error);
1495 	tries++;
1496 	if (generation != curthread->td_generation && tries < 3) {
1497 		*req = req2;
1498 		goto retry;
1499 	}
1500 
1501 	error = SYSCTL_IN(req, arg1, arg2);
1502 
1503 	return (error);
1504 }
1505 
1506 /*
1507  * Transfer functions to/from kernel space.
1508  * XXX: rather untested at this point
1509  */
1510 static int
1511 sysctl_old_kernel(struct sysctl_req *req, const void *p, size_t l)
1512 {
1513 	size_t i = 0;
1514 
1515 	if (req->oldptr) {
1516 		i = l;
1517 		if (req->oldlen <= req->oldidx)
1518 			i = 0;
1519 		else
1520 			if (i > req->oldlen - req->oldidx)
1521 				i = req->oldlen - req->oldidx;
1522 		if (i > 0)
1523 			bcopy(p, (char *)req->oldptr + req->oldidx, i);
1524 	}
1525 	req->oldidx += l;
1526 	if (req->oldptr && i != l)
1527 		return (ENOMEM);
1528 	return (0);
1529 }
1530 
1531 static int
1532 sysctl_new_kernel(struct sysctl_req *req, void *p, size_t l)
1533 {
1534 	if (!req->newptr)
1535 		return (0);
1536 	if (req->newlen - req->newidx < l)
1537 		return (EINVAL);
1538 	bcopy((char *)req->newptr + req->newidx, p, l);
1539 	req->newidx += l;
1540 	return (0);
1541 }
1542 
1543 int
1544 kernel_sysctl(struct thread *td, int *name, u_int namelen, void *old,
1545     size_t *oldlenp, void *new, size_t newlen, size_t *retval, int flags)
1546 {
1547 	int error = 0;
1548 	struct sysctl_req req;
1549 
1550 	bzero(&req, sizeof req);
1551 
1552 	req.td = td;
1553 	req.flags = flags;
1554 
1555 	if (oldlenp) {
1556 		req.oldlen = *oldlenp;
1557 	}
1558 	req.validlen = req.oldlen;
1559 
1560 	if (old) {
1561 		req.oldptr= old;
1562 	}
1563 
1564 	if (new != NULL) {
1565 		req.newlen = newlen;
1566 		req.newptr = new;
1567 	}
1568 
1569 	req.oldfunc = sysctl_old_kernel;
1570 	req.newfunc = sysctl_new_kernel;
1571 	req.lock = REQ_UNWIRED;
1572 
1573 	error = sysctl_root(0, name, namelen, &req);
1574 
1575 	if (req.lock == REQ_WIRED && req.validlen > 0)
1576 		vsunlock(req.oldptr, req.validlen);
1577 
1578 	if (error && error != ENOMEM)
1579 		return (error);
1580 
1581 	if (retval) {
1582 		if (req.oldptr && req.oldidx > req.validlen)
1583 			*retval = req.validlen;
1584 		else
1585 			*retval = req.oldidx;
1586 	}
1587 	return (error);
1588 }
1589 
1590 int
1591 kernel_sysctlbyname(struct thread *td, char *name, void *old, size_t *oldlenp,
1592     void *new, size_t newlen, size_t *retval, int flags)
1593 {
1594         int oid[CTL_MAXNAME];
1595         size_t oidlen, plen;
1596 	int error;
1597 
1598 	oid[0] = 0;		/* sysctl internal magic */
1599 	oid[1] = 3;		/* name2oid */
1600 	oidlen = sizeof(oid);
1601 
1602 	error = kernel_sysctl(td, oid, 2, oid, &oidlen,
1603 	    (void *)name, strlen(name), &plen, flags);
1604 	if (error)
1605 		return (error);
1606 
1607 	error = kernel_sysctl(td, oid, plen / sizeof(int), old, oldlenp,
1608 	    new, newlen, retval, flags);
1609 	return (error);
1610 }
1611 
1612 /*
1613  * Transfer function to/from user space.
1614  */
1615 static int
1616 sysctl_old_user(struct sysctl_req *req, const void *p, size_t l)
1617 {
1618 	size_t i, len, origidx;
1619 	int error;
1620 
1621 	origidx = req->oldidx;
1622 	req->oldidx += l;
1623 	if (req->oldptr == NULL)
1624 		return (0);
1625 	/*
1626 	 * If we have not wired the user supplied buffer and we are currently
1627 	 * holding locks, drop a witness warning, as it's possible that
1628 	 * write operations to the user page can sleep.
1629 	 */
1630 	if (req->lock != REQ_WIRED)
1631 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1632 		    "sysctl_old_user()");
1633 	i = l;
1634 	len = req->validlen;
1635 	if (len <= origidx)
1636 		i = 0;
1637 	else {
1638 		if (i > len - origidx)
1639 			i = len - origidx;
1640 		if (req->lock == REQ_WIRED) {
1641 			error = copyout_nofault(p, (char *)req->oldptr +
1642 			    origidx, i);
1643 		} else
1644 			error = copyout(p, (char *)req->oldptr + origidx, i);
1645 		if (error != 0)
1646 			return (error);
1647 	}
1648 	if (i < l)
1649 		return (ENOMEM);
1650 	return (0);
1651 }
1652 
1653 static int
1654 sysctl_new_user(struct sysctl_req *req, void *p, size_t l)
1655 {
1656 	int error;
1657 
1658 	if (!req->newptr)
1659 		return (0);
1660 	if (req->newlen - req->newidx < l)
1661 		return (EINVAL);
1662 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1663 	    "sysctl_new_user()");
1664 	error = copyin((char *)req->newptr + req->newidx, p, l);
1665 	req->newidx += l;
1666 	return (error);
1667 }
1668 
1669 /*
1670  * Wire the user space destination buffer.  If set to a value greater than
1671  * zero, the len parameter limits the maximum amount of wired memory.
1672  */
1673 int
1674 sysctl_wire_old_buffer(struct sysctl_req *req, size_t len)
1675 {
1676 	int ret;
1677 	size_t wiredlen;
1678 
1679 	wiredlen = (len > 0 && len < req->oldlen) ? len : req->oldlen;
1680 	ret = 0;
1681 	if (req->lock != REQ_WIRED && req->oldptr &&
1682 	    req->oldfunc == sysctl_old_user) {
1683 		if (wiredlen != 0) {
1684 			ret = vslock(req->oldptr, wiredlen);
1685 			if (ret != 0) {
1686 				if (ret != ENOMEM)
1687 					return (ret);
1688 				wiredlen = 0;
1689 			}
1690 		}
1691 		req->lock = REQ_WIRED;
1692 		req->validlen = wiredlen;
1693 	}
1694 	return (0);
1695 }
1696 
1697 int
1698 sysctl_find_oid(int *name, u_int namelen, struct sysctl_oid **noid,
1699     int *nindx, struct sysctl_req *req)
1700 {
1701 	struct sysctl_oid_list *lsp;
1702 	struct sysctl_oid *oid;
1703 	int indx;
1704 
1705 	SYSCTL_ASSERT_LOCKED();
1706 	lsp = &sysctl__children;
1707 	indx = 0;
1708 	while (indx < CTL_MAXNAME) {
1709 		SLIST_FOREACH(oid, lsp, oid_link) {
1710 			if (oid->oid_number == name[indx])
1711 				break;
1712 		}
1713 		if (oid == NULL)
1714 			return (ENOENT);
1715 
1716 		indx++;
1717 		if ((oid->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
1718 			if (oid->oid_handler != NULL || indx == namelen) {
1719 				*noid = oid;
1720 				if (nindx != NULL)
1721 					*nindx = indx;
1722 				KASSERT((oid->oid_kind & CTLFLAG_DYING) == 0,
1723 				    ("%s found DYING node %p", __func__, oid));
1724 				return (0);
1725 			}
1726 			lsp = SYSCTL_CHILDREN(oid);
1727 		} else if (indx == namelen) {
1728 			*noid = oid;
1729 			if (nindx != NULL)
1730 				*nindx = indx;
1731 			KASSERT((oid->oid_kind & CTLFLAG_DYING) == 0,
1732 			    ("%s found DYING node %p", __func__, oid));
1733 			return (0);
1734 		} else {
1735 			return (ENOTDIR);
1736 		}
1737 	}
1738 	return (ENOENT);
1739 }
1740 
1741 /*
1742  * Traverse our tree, and find the right node, execute whatever it points
1743  * to, and return the resulting error code.
1744  */
1745 
1746 static int
1747 sysctl_root(SYSCTL_HANDLER_ARGS)
1748 {
1749 	struct sysctl_oid *oid;
1750 	struct rm_priotracker tracker;
1751 	int error, indx, lvl;
1752 
1753 	SYSCTL_RLOCK(&tracker);
1754 
1755 	error = sysctl_find_oid(arg1, arg2, &oid, &indx, req);
1756 	if (error)
1757 		goto out;
1758 
1759 	if ((oid->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
1760 		/*
1761 		 * You can't call a sysctl when it's a node, but has
1762 		 * no handler.  Inform the user that it's a node.
1763 		 * The indx may or may not be the same as namelen.
1764 		 */
1765 		if (oid->oid_handler == NULL) {
1766 			error = EISDIR;
1767 			goto out;
1768 		}
1769 	}
1770 
1771 	/* Is this sysctl writable? */
1772 	if (req->newptr && !(oid->oid_kind & CTLFLAG_WR)) {
1773 		error = EPERM;
1774 		goto out;
1775 	}
1776 
1777 	KASSERT(req->td != NULL, ("sysctl_root(): req->td == NULL"));
1778 
1779 #ifdef CAPABILITY_MODE
1780 	/*
1781 	 * If the process is in capability mode, then don't permit reading or
1782 	 * writing unless specifically granted for the node.
1783 	 */
1784 	if (IN_CAPABILITY_MODE(req->td)) {
1785 		if ((req->oldptr && !(oid->oid_kind & CTLFLAG_CAPRD)) ||
1786 		    (req->newptr && !(oid->oid_kind & CTLFLAG_CAPWR))) {
1787 			error = EPERM;
1788 			goto out;
1789 		}
1790 	}
1791 #endif
1792 
1793 	/* Is this sysctl sensitive to securelevels? */
1794 	if (req->newptr && (oid->oid_kind & CTLFLAG_SECURE)) {
1795 		lvl = (oid->oid_kind & CTLMASK_SECURE) >> CTLSHIFT_SECURE;
1796 		error = securelevel_gt(req->td->td_ucred, lvl);
1797 		if (error)
1798 			goto out;
1799 	}
1800 
1801 	/* Is this sysctl writable by only privileged users? */
1802 	if (req->newptr && !(oid->oid_kind & CTLFLAG_ANYBODY)) {
1803 		int priv;
1804 
1805 		if (oid->oid_kind & CTLFLAG_PRISON)
1806 			priv = PRIV_SYSCTL_WRITEJAIL;
1807 #ifdef VIMAGE
1808 		else if ((oid->oid_kind & CTLFLAG_VNET) &&
1809 		     prison_owns_vnet(req->td->td_ucred))
1810 			priv = PRIV_SYSCTL_WRITEJAIL;
1811 #endif
1812 		else
1813 			priv = PRIV_SYSCTL_WRITE;
1814 		error = priv_check(req->td, priv);
1815 		if (error)
1816 			goto out;
1817 	}
1818 
1819 	if (!oid->oid_handler) {
1820 		error = EINVAL;
1821 		goto out;
1822 	}
1823 
1824 	if ((oid->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
1825 		arg1 = (int *)arg1 + indx;
1826 		arg2 -= indx;
1827 	} else {
1828 		arg1 = oid->oid_arg1;
1829 		arg2 = oid->oid_arg2;
1830 	}
1831 #ifdef MAC
1832 	error = mac_system_check_sysctl(req->td->td_ucred, oid, arg1, arg2,
1833 	    req);
1834 	if (error != 0)
1835 		goto out;
1836 #endif
1837 #ifdef VIMAGE
1838 	if ((oid->oid_kind & CTLFLAG_VNET) && arg1 != NULL)
1839 		arg1 = (void *)(curvnet->vnet_data_base + (uintptr_t)arg1);
1840 #endif
1841 	error = sysctl_root_handler_locked(oid, arg1, arg2, req, &tracker);
1842 
1843 out:
1844 	SYSCTL_RUNLOCK(&tracker);
1845 	return (error);
1846 }
1847 
1848 #ifndef _SYS_SYSPROTO_H_
1849 struct sysctl_args {
1850 	int	*name;
1851 	u_int	namelen;
1852 	void	*old;
1853 	size_t	*oldlenp;
1854 	void	*new;
1855 	size_t	newlen;
1856 };
1857 #endif
1858 int
1859 sys___sysctl(struct thread *td, struct sysctl_args *uap)
1860 {
1861 	int error, i, name[CTL_MAXNAME];
1862 	size_t j;
1863 
1864 	if (uap->namelen > CTL_MAXNAME || uap->namelen < 2)
1865 		return (EINVAL);
1866 
1867  	error = copyin(uap->name, &name, uap->namelen * sizeof(int));
1868  	if (error)
1869 		return (error);
1870 
1871 	error = userland_sysctl(td, name, uap->namelen,
1872 		uap->old, uap->oldlenp, 0,
1873 		uap->new, uap->newlen, &j, 0);
1874 	if (error && error != ENOMEM)
1875 		return (error);
1876 	if (uap->oldlenp) {
1877 		i = copyout(&j, uap->oldlenp, sizeof(j));
1878 		if (i)
1879 			return (i);
1880 	}
1881 	return (error);
1882 }
1883 
1884 /*
1885  * This is used from various compatibility syscalls too.  That's why name
1886  * must be in kernel space.
1887  */
1888 int
1889 userland_sysctl(struct thread *td, int *name, u_int namelen, void *old,
1890     size_t *oldlenp, int inkernel, void *new, size_t newlen, size_t *retval,
1891     int flags)
1892 {
1893 	int error = 0, memlocked;
1894 	struct sysctl_req req;
1895 
1896 	bzero(&req, sizeof req);
1897 
1898 	req.td = td;
1899 	req.flags = flags;
1900 
1901 	if (oldlenp) {
1902 		if (inkernel) {
1903 			req.oldlen = *oldlenp;
1904 		} else {
1905 			error = copyin(oldlenp, &req.oldlen, sizeof(*oldlenp));
1906 			if (error)
1907 				return (error);
1908 		}
1909 	}
1910 	req.validlen = req.oldlen;
1911 
1912 	if (old) {
1913 		if (!useracc(old, req.oldlen, VM_PROT_WRITE))
1914 			return (EFAULT);
1915 		req.oldptr= old;
1916 	}
1917 
1918 	if (new != NULL) {
1919 		if (!useracc(new, newlen, VM_PROT_READ))
1920 			return (EFAULT);
1921 		req.newlen = newlen;
1922 		req.newptr = new;
1923 	}
1924 
1925 	req.oldfunc = sysctl_old_user;
1926 	req.newfunc = sysctl_new_user;
1927 	req.lock = REQ_UNWIRED;
1928 
1929 #ifdef KTRACE
1930 	if (KTRPOINT(curthread, KTR_SYSCTL))
1931 		ktrsysctl(name, namelen);
1932 #endif
1933 
1934 	if (req.oldptr && req.oldlen > PAGE_SIZE) {
1935 		memlocked = 1;
1936 		sx_xlock(&sysctlmemlock);
1937 	} else
1938 		memlocked = 0;
1939 	CURVNET_SET(TD_TO_VNET(td));
1940 
1941 	for (;;) {
1942 		req.oldidx = 0;
1943 		req.newidx = 0;
1944 		error = sysctl_root(0, name, namelen, &req);
1945 		if (error != EAGAIN)
1946 			break;
1947 		kern_yield(PRI_USER);
1948 	}
1949 
1950 	CURVNET_RESTORE();
1951 
1952 	if (req.lock == REQ_WIRED && req.validlen > 0)
1953 		vsunlock(req.oldptr, req.validlen);
1954 	if (memlocked)
1955 		sx_xunlock(&sysctlmemlock);
1956 
1957 	if (error && error != ENOMEM)
1958 		return (error);
1959 
1960 	if (retval) {
1961 		if (req.oldptr && req.oldidx > req.validlen)
1962 			*retval = req.validlen;
1963 		else
1964 			*retval = req.oldidx;
1965 	}
1966 	return (error);
1967 }
1968 
1969 /*
1970  * Drain into a sysctl struct.  The user buffer should be wired if a page
1971  * fault would cause issue.
1972  */
1973 static int
1974 sbuf_sysctl_drain(void *arg, const char *data, int len)
1975 {
1976 	struct sysctl_req *req = arg;
1977 	int error;
1978 
1979 	error = SYSCTL_OUT(req, data, len);
1980 	KASSERT(error >= 0, ("Got unexpected negative value %d", error));
1981 	return (error == 0 ? len : -error);
1982 }
1983 
1984 struct sbuf *
1985 sbuf_new_for_sysctl(struct sbuf *s, char *buf, int length,
1986     struct sysctl_req *req)
1987 {
1988 
1989 	/* Supply a default buffer size if none given. */
1990 	if (buf == NULL && length == 0)
1991 		length = 64;
1992 	s = sbuf_new(s, buf, length, SBUF_FIXEDLEN | SBUF_INCLUDENUL);
1993 	sbuf_set_drain(s, sbuf_sysctl_drain, req);
1994 	return (s);
1995 }
1996