xref: /freebsd/sys/kern/kern_sysctl.c (revision 8a166cafe0965f6bd72cd3d2f5372704f05cb5e8)
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/capability.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/sbuf.h>
58 #include <sys/sx.h>
59 #include <sys/sysproto.h>
60 #include <sys/uio.h>
61 #ifdef KTRACE
62 #include <sys/ktrace.h>
63 #endif
64 
65 #include <net/vnet.h>
66 
67 #include <security/mac/mac_framework.h>
68 
69 #include <vm/vm.h>
70 #include <vm/vm_extern.h>
71 
72 static MALLOC_DEFINE(M_SYSCTL, "sysctl", "sysctl internal magic");
73 static MALLOC_DEFINE(M_SYSCTLOID, "sysctloid", "sysctl dynamic oids");
74 static MALLOC_DEFINE(M_SYSCTLTMP, "sysctltmp", "sysctl temp output buffer");
75 
76 /*
77  * The sysctllock protects the MIB tree.  It also protects sysctl
78  * contexts used with dynamic sysctls.  The sysctl_register_oid() and
79  * sysctl_unregister_oid() routines require the sysctllock to already
80  * be held, so the sysctl_lock() and sysctl_unlock() routines are
81  * provided for the few places in the kernel which need to use that
82  * API rather than using the dynamic API.  Use of the dynamic API is
83  * strongly encouraged for most code.
84  *
85  * The sysctlmemlock is used to limit the amount of user memory wired for
86  * sysctl requests.  This is implemented by serializing any userland
87  * sysctl requests larger than a single page via an exclusive lock.
88  */
89 static struct sx sysctllock;
90 static struct sx sysctlmemlock;
91 
92 #define	SYSCTL_XLOCK()		sx_xlock(&sysctllock)
93 #define	SYSCTL_XUNLOCK()	sx_xunlock(&sysctllock)
94 #define	SYSCTL_ASSERT_XLOCKED()	sx_assert(&sysctllock, SA_XLOCKED)
95 #define	SYSCTL_INIT()		sx_init(&sysctllock, "sysctl lock")
96 #define	SYSCTL_SLEEP(ch, wmesg, timo)					\
97 				sx_sleep(ch, &sysctllock, 0, wmesg, timo)
98 
99 static int sysctl_root(SYSCTL_HANDLER_ARGS);
100 
101 struct sysctl_oid_list sysctl__children; /* root list */
102 
103 static int	sysctl_remove_oid_locked(struct sysctl_oid *oidp, int del,
104 		    int recurse);
105 
106 static struct sysctl_oid *
107 sysctl_find_oidname(const char *name, struct sysctl_oid_list *list)
108 {
109 	struct sysctl_oid *oidp;
110 
111 	SYSCTL_ASSERT_XLOCKED();
112 	SLIST_FOREACH(oidp, list, oid_link) {
113 		if (strcmp(oidp->oid_name, name) == 0) {
114 			return (oidp);
115 		}
116 	}
117 	return (NULL);
118 }
119 
120 /*
121  * Initialization of the MIB tree.
122  *
123  * Order by number in each list.
124  */
125 void
126 sysctl_lock(void)
127 {
128 
129 	SYSCTL_XLOCK();
130 }
131 
132 void
133 sysctl_unlock(void)
134 {
135 
136 	SYSCTL_XUNLOCK();
137 }
138 
139 void
140 sysctl_register_oid(struct sysctl_oid *oidp)
141 {
142 	struct sysctl_oid_list *parent = oidp->oid_parent;
143 	struct sysctl_oid *p;
144 	struct sysctl_oid *q;
145 
146 	/*
147 	 * First check if another oid with the same name already
148 	 * exists in the parent's list.
149 	 */
150 	SYSCTL_ASSERT_XLOCKED();
151 	p = sysctl_find_oidname(oidp->oid_name, parent);
152 	if (p != NULL) {
153 		if ((p->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
154 			p->oid_refcnt++;
155 			return;
156 		} else {
157 			printf("can't re-use a leaf (%s)!\n", p->oid_name);
158 			return;
159 		}
160 	}
161 	/*
162 	 * If this oid has a number OID_AUTO, give it a number which
163 	 * is greater than any current oid.
164 	 * NOTE: DO NOT change the starting value here, change it in
165 	 * <sys/sysctl.h>, and make sure it is at least 256 to
166 	 * accomodate e.g. net.inet.raw as a static sysctl node.
167 	 */
168 	if (oidp->oid_number == OID_AUTO) {
169 		static int newoid = CTL_AUTO_START;
170 
171 		oidp->oid_number = newoid++;
172 		if (newoid == 0x7fffffff)
173 			panic("out of oids");
174 	}
175 #if 0
176 	else if (oidp->oid_number >= CTL_AUTO_START) {
177 		/* do not panic; this happens when unregistering sysctl sets */
178 		printf("static sysctl oid too high: %d", oidp->oid_number);
179 	}
180 #endif
181 
182 	/*
183 	 * Insert the oid into the parent's list in order.
184 	 */
185 	q = NULL;
186 	SLIST_FOREACH(p, parent, oid_link) {
187 		if (oidp->oid_number < p->oid_number)
188 			break;
189 		q = p;
190 	}
191 	if (q)
192 		SLIST_INSERT_AFTER(q, oidp, oid_link);
193 	else
194 		SLIST_INSERT_HEAD(parent, oidp, oid_link);
195 }
196 
197 void
198 sysctl_unregister_oid(struct sysctl_oid *oidp)
199 {
200 	struct sysctl_oid *p;
201 	int error;
202 
203 	SYSCTL_ASSERT_XLOCKED();
204 	error = ENOENT;
205 	if (oidp->oid_number == OID_AUTO) {
206 		error = EINVAL;
207 	} else {
208 		SLIST_FOREACH(p, oidp->oid_parent, oid_link) {
209 			if (p == oidp) {
210 				SLIST_REMOVE(oidp->oid_parent, oidp,
211 				    sysctl_oid, oid_link);
212 				error = 0;
213 				break;
214 			}
215 		}
216 	}
217 
218 	/*
219 	 * This can happen when a module fails to register and is
220 	 * being unloaded afterwards.  It should not be a panic()
221 	 * for normal use.
222 	 */
223 	if (error)
224 		printf("%s: failed to unregister sysctl\n", __func__);
225 }
226 
227 /* Initialize a new context to keep track of dynamically added sysctls. */
228 int
229 sysctl_ctx_init(struct sysctl_ctx_list *c)
230 {
231 
232 	if (c == NULL) {
233 		return (EINVAL);
234 	}
235 
236 	/*
237 	 * No locking here, the caller is responsible for not adding
238 	 * new nodes to a context until after this function has
239 	 * returned.
240 	 */
241 	TAILQ_INIT(c);
242 	return (0);
243 }
244 
245 /* Free the context, and destroy all dynamic oids registered in this context */
246 int
247 sysctl_ctx_free(struct sysctl_ctx_list *clist)
248 {
249 	struct sysctl_ctx_entry *e, *e1;
250 	int error;
251 
252 	error = 0;
253 	/*
254 	 * First perform a "dry run" to check if it's ok to remove oids.
255 	 * XXX FIXME
256 	 * XXX This algorithm is a hack. But I don't know any
257 	 * XXX better solution for now...
258 	 */
259 	SYSCTL_XLOCK();
260 	TAILQ_FOREACH(e, clist, link) {
261 		error = sysctl_remove_oid_locked(e->entry, 0, 0);
262 		if (error)
263 			break;
264 	}
265 	/*
266 	 * Restore deregistered entries, either from the end,
267 	 * or from the place where error occured.
268 	 * e contains the entry that was not unregistered
269 	 */
270 	if (error)
271 		e1 = TAILQ_PREV(e, sysctl_ctx_list, link);
272 	else
273 		e1 = TAILQ_LAST(clist, sysctl_ctx_list);
274 	while (e1 != NULL) {
275 		sysctl_register_oid(e1->entry);
276 		e1 = TAILQ_PREV(e1, sysctl_ctx_list, link);
277 	}
278 	if (error) {
279 		SYSCTL_XUNLOCK();
280 		return(EBUSY);
281 	}
282 	/* Now really delete the entries */
283 	e = TAILQ_FIRST(clist);
284 	while (e != NULL) {
285 		e1 = TAILQ_NEXT(e, link);
286 		error = sysctl_remove_oid_locked(e->entry, 1, 0);
287 		if (error)
288 			panic("sysctl_remove_oid: corrupt tree, entry: %s",
289 			    e->entry->oid_name);
290 		free(e, M_SYSCTLOID);
291 		e = e1;
292 	}
293 	SYSCTL_XUNLOCK();
294 	return (error);
295 }
296 
297 /* Add an entry to the context */
298 struct sysctl_ctx_entry *
299 sysctl_ctx_entry_add(struct sysctl_ctx_list *clist, struct sysctl_oid *oidp)
300 {
301 	struct sysctl_ctx_entry *e;
302 
303 	SYSCTL_ASSERT_XLOCKED();
304 	if (clist == NULL || oidp == NULL)
305 		return(NULL);
306 	e = malloc(sizeof(struct sysctl_ctx_entry), M_SYSCTLOID, M_WAITOK);
307 	e->entry = oidp;
308 	TAILQ_INSERT_HEAD(clist, e, link);
309 	return (e);
310 }
311 
312 /* Find an entry in the context */
313 struct sysctl_ctx_entry *
314 sysctl_ctx_entry_find(struct sysctl_ctx_list *clist, struct sysctl_oid *oidp)
315 {
316 	struct sysctl_ctx_entry *e;
317 
318 	SYSCTL_ASSERT_XLOCKED();
319 	if (clist == NULL || oidp == NULL)
320 		return(NULL);
321 	TAILQ_FOREACH(e, clist, link) {
322 		if(e->entry == oidp)
323 			return(e);
324 	}
325 	return (e);
326 }
327 
328 /*
329  * Delete an entry from the context.
330  * NOTE: this function doesn't free oidp! You have to remove it
331  * with sysctl_remove_oid().
332  */
333 int
334 sysctl_ctx_entry_del(struct sysctl_ctx_list *clist, struct sysctl_oid *oidp)
335 {
336 	struct sysctl_ctx_entry *e;
337 
338 	if (clist == NULL || oidp == NULL)
339 		return (EINVAL);
340 	SYSCTL_XLOCK();
341 	e = sysctl_ctx_entry_find(clist, oidp);
342 	if (e != NULL) {
343 		TAILQ_REMOVE(clist, e, link);
344 		SYSCTL_XUNLOCK();
345 		free(e, M_SYSCTLOID);
346 		return (0);
347 	} else {
348 		SYSCTL_XUNLOCK();
349 		return (ENOENT);
350 	}
351 }
352 
353 /*
354  * Remove dynamically created sysctl trees.
355  * oidp - top of the tree to be removed
356  * del - if 0 - just deregister, otherwise free up entries as well
357  * recurse - if != 0 traverse the subtree to be deleted
358  */
359 int
360 sysctl_remove_oid(struct sysctl_oid *oidp, int del, int recurse)
361 {
362 	int error;
363 
364 	SYSCTL_XLOCK();
365 	error = sysctl_remove_oid_locked(oidp, del, recurse);
366 	SYSCTL_XUNLOCK();
367 	return (error);
368 }
369 
370 int
371 sysctl_remove_name(struct sysctl_oid *parent, const char *name,
372     int del, int recurse)
373 {
374 	struct sysctl_oid *p, *tmp;
375 	int error;
376 
377 	error = ENOENT;
378 	SYSCTL_XLOCK();
379 	SLIST_FOREACH_SAFE(p, SYSCTL_CHILDREN(parent), oid_link, tmp) {
380 		if (strcmp(p->oid_name, name) == 0) {
381 			error = sysctl_remove_oid_locked(p, del, recurse);
382 			break;
383 		}
384 	}
385 	SYSCTL_XUNLOCK();
386 
387 	return (error);
388 }
389 
390 
391 static int
392 sysctl_remove_oid_locked(struct sysctl_oid *oidp, int del, int recurse)
393 {
394 	struct sysctl_oid *p, *tmp;
395 	int error;
396 
397 	SYSCTL_ASSERT_XLOCKED();
398 	if (oidp == NULL)
399 		return(EINVAL);
400 	if ((oidp->oid_kind & CTLFLAG_DYN) == 0) {
401 		printf("can't remove non-dynamic nodes!\n");
402 		return (EINVAL);
403 	}
404 	/*
405 	 * WARNING: normal method to do this should be through
406 	 * sysctl_ctx_free(). Use recursing as the last resort
407 	 * method to purge your sysctl tree of leftovers...
408 	 * However, if some other code still references these nodes,
409 	 * it will panic.
410 	 */
411 	if ((oidp->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
412 		if (oidp->oid_refcnt == 1) {
413 			SLIST_FOREACH_SAFE(p,
414 			    SYSCTL_CHILDREN(oidp), oid_link, tmp) {
415 				if (!recurse)
416 					return (ENOTEMPTY);
417 				error = sysctl_remove_oid_locked(p, del,
418 				    recurse);
419 				if (error)
420 					return (error);
421 			}
422 			if (del)
423 				free(SYSCTL_CHILDREN(oidp), M_SYSCTLOID);
424 		}
425 	}
426 	if (oidp->oid_refcnt > 1 ) {
427 		oidp->oid_refcnt--;
428 	} else {
429 		if (oidp->oid_refcnt == 0) {
430 			printf("Warning: bad oid_refcnt=%u (%s)!\n",
431 				oidp->oid_refcnt, oidp->oid_name);
432 			return (EINVAL);
433 		}
434 		sysctl_unregister_oid(oidp);
435 		if (del) {
436 			/*
437 			 * Wait for all threads running the handler to drain.
438 			 * This preserves the previous behavior when the
439 			 * sysctl lock was held across a handler invocation,
440 			 * and is necessary for module unload correctness.
441 			 */
442 			while (oidp->oid_running > 0) {
443 				oidp->oid_kind |= CTLFLAG_DYING;
444 				SYSCTL_SLEEP(&oidp->oid_running, "oidrm", 0);
445 			}
446 			if (oidp->oid_descr)
447 				free((void *)(uintptr_t)(const void *)oidp->oid_descr, M_SYSCTLOID);
448 			free((void *)(uintptr_t)(const void *)oidp->oid_name,
449 			     M_SYSCTLOID);
450 			free(oidp, M_SYSCTLOID);
451 		}
452 	}
453 	return (0);
454 }
455 /*
456  * Create new sysctls at run time.
457  * clist may point to a valid context initialized with sysctl_ctx_init().
458  */
459 struct sysctl_oid *
460 sysctl_add_oid(struct sysctl_ctx_list *clist, struct sysctl_oid_list *parent,
461 	int number, const char *name, int kind, void *arg1, intptr_t arg2,
462 	int (*handler)(SYSCTL_HANDLER_ARGS), const char *fmt, const char *descr)
463 {
464 	struct sysctl_oid *oidp;
465 	ssize_t len;
466 	char *newname;
467 
468 	/* You have to hook up somewhere.. */
469 	if (parent == NULL)
470 		return(NULL);
471 	/* Check if the node already exists, otherwise create it */
472 	SYSCTL_XLOCK();
473 	oidp = sysctl_find_oidname(name, parent);
474 	if (oidp != NULL) {
475 		if ((oidp->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
476 			oidp->oid_refcnt++;
477 			/* Update the context */
478 			if (clist != NULL)
479 				sysctl_ctx_entry_add(clist, oidp);
480 			SYSCTL_XUNLOCK();
481 			return (oidp);
482 		} else {
483 			SYSCTL_XUNLOCK();
484 			printf("can't re-use a leaf (%s)!\n", name);
485 			return (NULL);
486 		}
487 	}
488 	oidp = malloc(sizeof(struct sysctl_oid), M_SYSCTLOID, M_WAITOK|M_ZERO);
489 	oidp->oid_parent = parent;
490 	SLIST_NEXT(oidp, oid_link) = NULL;
491 	oidp->oid_number = number;
492 	oidp->oid_refcnt = 1;
493 	len = strlen(name);
494 	newname = malloc(len + 1, M_SYSCTLOID, M_WAITOK);
495 	bcopy(name, newname, len + 1);
496 	newname[len] = '\0';
497 	oidp->oid_name = newname;
498 	oidp->oid_handler = handler;
499 	oidp->oid_kind = CTLFLAG_DYN | kind;
500 	if ((kind & CTLTYPE) == CTLTYPE_NODE) {
501 		/* Allocate space for children */
502 		SYSCTL_CHILDREN_SET(oidp, malloc(sizeof(struct sysctl_oid_list),
503 		    M_SYSCTLOID, M_WAITOK));
504 		SLIST_INIT(SYSCTL_CHILDREN(oidp));
505 		oidp->oid_arg2 = arg2;
506 	} else {
507 		oidp->oid_arg1 = arg1;
508 		oidp->oid_arg2 = arg2;
509 	}
510 	oidp->oid_fmt = fmt;
511 	if (descr) {
512 		int len = strlen(descr) + 1;
513 		oidp->oid_descr = malloc(len, M_SYSCTLOID, M_WAITOK);
514 		if (oidp->oid_descr)
515 			strcpy((char *)(uintptr_t)(const void *)oidp->oid_descr, descr);
516 	}
517 	/* Update the context, if used */
518 	if (clist != NULL)
519 		sysctl_ctx_entry_add(clist, oidp);
520 	/* Register this oid */
521 	sysctl_register_oid(oidp);
522 	SYSCTL_XUNLOCK();
523 	return (oidp);
524 }
525 
526 /*
527  * Rename an existing oid.
528  */
529 void
530 sysctl_rename_oid(struct sysctl_oid *oidp, const char *name)
531 {
532 	ssize_t len;
533 	char *newname;
534 	void *oldname;
535 
536 	len = strlen(name);
537 	newname = malloc(len + 1, M_SYSCTLOID, M_WAITOK);
538 	bcopy(name, newname, len + 1);
539 	newname[len] = '\0';
540 	SYSCTL_XLOCK();
541 	oldname = (void *)(uintptr_t)(const void *)oidp->oid_name;
542 	oidp->oid_name = newname;
543 	SYSCTL_XUNLOCK();
544 	free(oldname, M_SYSCTLOID);
545 }
546 
547 /*
548  * Reparent an existing oid.
549  */
550 int
551 sysctl_move_oid(struct sysctl_oid *oid, struct sysctl_oid_list *parent)
552 {
553 	struct sysctl_oid *oidp;
554 
555 	SYSCTL_XLOCK();
556 	if (oid->oid_parent == parent) {
557 		SYSCTL_XUNLOCK();
558 		return (0);
559 	}
560 	oidp = sysctl_find_oidname(oid->oid_name, parent);
561 	if (oidp != NULL) {
562 		SYSCTL_XUNLOCK();
563 		return (EEXIST);
564 	}
565 	sysctl_unregister_oid(oid);
566 	oid->oid_parent = parent;
567 	oid->oid_number = OID_AUTO;
568 	sysctl_register_oid(oid);
569 	SYSCTL_XUNLOCK();
570 	return (0);
571 }
572 
573 /*
574  * Register the kernel's oids on startup.
575  */
576 SET_DECLARE(sysctl_set, struct sysctl_oid);
577 
578 static void
579 sysctl_register_all(void *arg)
580 {
581 	struct sysctl_oid **oidp;
582 
583 	sx_init(&sysctlmemlock, "sysctl mem");
584 	SYSCTL_INIT();
585 	SYSCTL_XLOCK();
586 	SET_FOREACH(oidp, sysctl_set)
587 		sysctl_register_oid(*oidp);
588 	SYSCTL_XUNLOCK();
589 }
590 SYSINIT(sysctl, SI_SUB_KMEM, SI_ORDER_ANY, sysctl_register_all, 0);
591 
592 /*
593  * "Staff-functions"
594  *
595  * These functions implement a presently undocumented interface
596  * used by the sysctl program to walk the tree, and get the type
597  * so it can print the value.
598  * This interface is under work and consideration, and should probably
599  * be killed with a big axe by the first person who can find the time.
600  * (be aware though, that the proper interface isn't as obvious as it
601  * may seem, there are various conflicting requirements.
602  *
603  * {0,0}	printf the entire MIB-tree.
604  * {0,1,...}	return the name of the "..." OID.
605  * {0,2,...}	return the next OID.
606  * {0,3}	return the OID of the name in "new"
607  * {0,4,...}	return the kind & format info for the "..." OID.
608  * {0,5,...}	return the description the "..." OID.
609  */
610 
611 #ifdef SYSCTL_DEBUG
612 static void
613 sysctl_sysctl_debug_dump_node(struct sysctl_oid_list *l, int i)
614 {
615 	int k;
616 	struct sysctl_oid *oidp;
617 
618 	SYSCTL_ASSERT_XLOCKED();
619 	SLIST_FOREACH(oidp, l, oid_link) {
620 
621 		for (k=0; k<i; k++)
622 			printf(" ");
623 
624 		printf("%d %s ", oidp->oid_number, oidp->oid_name);
625 
626 		printf("%c%c",
627 			oidp->oid_kind & CTLFLAG_RD ? 'R':' ',
628 			oidp->oid_kind & CTLFLAG_WR ? 'W':' ');
629 
630 		if (oidp->oid_handler)
631 			printf(" *Handler");
632 
633 		switch (oidp->oid_kind & CTLTYPE) {
634 			case CTLTYPE_NODE:
635 				printf(" Node\n");
636 				if (!oidp->oid_handler) {
637 					sysctl_sysctl_debug_dump_node(
638 						oidp->oid_arg1, i+2);
639 				}
640 				break;
641 			case CTLTYPE_INT:    printf(" Int\n"); break;
642 			case CTLTYPE_UINT:   printf(" u_int\n"); break;
643 			case CTLTYPE_LONG:   printf(" Long\n"); break;
644 			case CTLTYPE_ULONG:  printf(" u_long\n"); break;
645 			case CTLTYPE_STRING: printf(" String\n"); break;
646 			case CTLTYPE_U64:    printf(" uint64_t\n"); break;
647 			case CTLTYPE_S64:    printf(" int64_t\n"); break;
648 			case CTLTYPE_OPAQUE: printf(" Opaque/struct\n"); break;
649 			default:	     printf("\n");
650 		}
651 
652 	}
653 }
654 
655 static int
656 sysctl_sysctl_debug(SYSCTL_HANDLER_ARGS)
657 {
658 	int error;
659 
660 	error = priv_check(req->td, PRIV_SYSCTL_DEBUG);
661 	if (error)
662 		return (error);
663 	SYSCTL_XLOCK();
664 	sysctl_sysctl_debug_dump_node(&sysctl__children, 0);
665 	SYSCTL_XUNLOCK();
666 	return (ENOENT);
667 }
668 
669 SYSCTL_PROC(_sysctl, 0, debug, CTLTYPE_STRING|CTLFLAG_RD,
670 	0, 0, sysctl_sysctl_debug, "-", "");
671 #endif
672 
673 static int
674 sysctl_sysctl_name(SYSCTL_HANDLER_ARGS)
675 {
676 	int *name = (int *) arg1;
677 	u_int namelen = arg2;
678 	int error = 0;
679 	struct sysctl_oid *oid;
680 	struct sysctl_oid_list *lsp = &sysctl__children, *lsp2;
681 	char buf[10];
682 
683 	SYSCTL_XLOCK();
684 	while (namelen) {
685 		if (!lsp) {
686 			snprintf(buf,sizeof(buf),"%d",*name);
687 			if (req->oldidx)
688 				error = SYSCTL_OUT(req, ".", 1);
689 			if (!error)
690 				error = SYSCTL_OUT(req, buf, strlen(buf));
691 			if (error)
692 				goto out;
693 			namelen--;
694 			name++;
695 			continue;
696 		}
697 		lsp2 = 0;
698 		SLIST_FOREACH(oid, lsp, oid_link) {
699 			if (oid->oid_number != *name)
700 				continue;
701 
702 			if (req->oldidx)
703 				error = SYSCTL_OUT(req, ".", 1);
704 			if (!error)
705 				error = SYSCTL_OUT(req, oid->oid_name,
706 					strlen(oid->oid_name));
707 			if (error)
708 				goto out;
709 
710 			namelen--;
711 			name++;
712 
713 			if ((oid->oid_kind & CTLTYPE) != CTLTYPE_NODE)
714 				break;
715 
716 			if (oid->oid_handler)
717 				break;
718 
719 			lsp2 = SYSCTL_CHILDREN(oid);
720 			break;
721 		}
722 		lsp = lsp2;
723 	}
724 	error = SYSCTL_OUT(req, "", 1);
725  out:
726 	SYSCTL_XUNLOCK();
727 	return (error);
728 }
729 
730 /*
731  * XXXRW/JA: Shouldn't return name data for nodes that we don't permit in
732  * capability mode.
733  */
734 static SYSCTL_NODE(_sysctl, 1, name, CTLFLAG_RD | CTLFLAG_CAPRD,
735     sysctl_sysctl_name, "");
736 
737 static int
738 sysctl_sysctl_next_ls(struct sysctl_oid_list *lsp, int *name, u_int namelen,
739 	int *next, int *len, int level, struct sysctl_oid **oidpp)
740 {
741 	struct sysctl_oid *oidp;
742 
743 	SYSCTL_ASSERT_XLOCKED();
744 	*len = level;
745 	SLIST_FOREACH(oidp, lsp, oid_link) {
746 		*next = oidp->oid_number;
747 		*oidpp = oidp;
748 
749 		if (oidp->oid_kind & CTLFLAG_SKIP)
750 			continue;
751 
752 		if (!namelen) {
753 			if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
754 				return (0);
755 			if (oidp->oid_handler)
756 				/* We really should call the handler here...*/
757 				return (0);
758 			lsp = SYSCTL_CHILDREN(oidp);
759 			if (!sysctl_sysctl_next_ls(lsp, 0, 0, next+1,
760 				len, level+1, oidpp))
761 				return (0);
762 			goto emptynode;
763 		}
764 
765 		if (oidp->oid_number < *name)
766 			continue;
767 
768 		if (oidp->oid_number > *name) {
769 			if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
770 				return (0);
771 			if (oidp->oid_handler)
772 				return (0);
773 			lsp = SYSCTL_CHILDREN(oidp);
774 			if (!sysctl_sysctl_next_ls(lsp, name+1, namelen-1,
775 				next+1, len, level+1, oidpp))
776 				return (0);
777 			goto next;
778 		}
779 		if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
780 			continue;
781 
782 		if (oidp->oid_handler)
783 			continue;
784 
785 		lsp = SYSCTL_CHILDREN(oidp);
786 		if (!sysctl_sysctl_next_ls(lsp, name+1, namelen-1, next+1,
787 			len, level+1, oidpp))
788 			return (0);
789 	next:
790 		namelen = 1;
791 	emptynode:
792 		*len = level;
793 	}
794 	return (1);
795 }
796 
797 static int
798 sysctl_sysctl_next(SYSCTL_HANDLER_ARGS)
799 {
800 	int *name = (int *) arg1;
801 	u_int namelen = arg2;
802 	int i, j, error;
803 	struct sysctl_oid *oid;
804 	struct sysctl_oid_list *lsp = &sysctl__children;
805 	int newoid[CTL_MAXNAME];
806 
807 	SYSCTL_XLOCK();
808 	i = sysctl_sysctl_next_ls(lsp, name, namelen, newoid, &j, 1, &oid);
809 	SYSCTL_XUNLOCK();
810 	if (i)
811 		return (ENOENT);
812 	error = SYSCTL_OUT(req, newoid, j * sizeof (int));
813 	return (error);
814 }
815 
816 /*
817  * XXXRW/JA: Shouldn't return next data for nodes that we don't permit in
818  * capability mode.
819  */
820 static SYSCTL_NODE(_sysctl, 2, next, CTLFLAG_RD | CTLFLAG_CAPRD,
821     sysctl_sysctl_next, "");
822 
823 static int
824 name2oid(char *name, int *oid, int *len, struct sysctl_oid **oidpp)
825 {
826 	int i;
827 	struct sysctl_oid *oidp;
828 	struct sysctl_oid_list *lsp = &sysctl__children;
829 	char *p;
830 
831 	SYSCTL_ASSERT_XLOCKED();
832 
833 	if (!*name)
834 		return (ENOENT);
835 
836 	p = name + strlen(name) - 1 ;
837 	if (*p == '.')
838 		*p = '\0';
839 
840 	*len = 0;
841 
842 	for (p = name; *p && *p != '.'; p++)
843 		;
844 	i = *p;
845 	if (i == '.')
846 		*p = '\0';
847 
848 	oidp = SLIST_FIRST(lsp);
849 
850 	while (oidp && *len < CTL_MAXNAME) {
851 		if (strcmp(name, oidp->oid_name)) {
852 			oidp = SLIST_NEXT(oidp, oid_link);
853 			continue;
854 		}
855 		*oid++ = oidp->oid_number;
856 		(*len)++;
857 
858 		if (!i) {
859 			if (oidpp)
860 				*oidpp = oidp;
861 			return (0);
862 		}
863 
864 		if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
865 			break;
866 
867 		if (oidp->oid_handler)
868 			break;
869 
870 		lsp = SYSCTL_CHILDREN(oidp);
871 		oidp = SLIST_FIRST(lsp);
872 		name = p+1;
873 		for (p = name; *p && *p != '.'; p++)
874 				;
875 		i = *p;
876 		if (i == '.')
877 			*p = '\0';
878 	}
879 	return (ENOENT);
880 }
881 
882 static int
883 sysctl_sysctl_name2oid(SYSCTL_HANDLER_ARGS)
884 {
885 	char *p;
886 	int error, oid[CTL_MAXNAME], len = 0;
887 	struct sysctl_oid *op = 0;
888 
889 	if (!req->newlen)
890 		return (ENOENT);
891 	if (req->newlen >= MAXPATHLEN)	/* XXX arbitrary, undocumented */
892 		return (ENAMETOOLONG);
893 
894 	p = malloc(req->newlen+1, M_SYSCTL, M_WAITOK);
895 
896 	error = SYSCTL_IN(req, p, req->newlen);
897 	if (error) {
898 		free(p, M_SYSCTL);
899 		return (error);
900 	}
901 
902 	p [req->newlen] = '\0';
903 
904 	SYSCTL_XLOCK();
905 	error = name2oid(p, oid, &len, &op);
906 	SYSCTL_XUNLOCK();
907 
908 	free(p, M_SYSCTL);
909 
910 	if (error)
911 		return (error);
912 
913 	error = SYSCTL_OUT(req, oid, len * sizeof *oid);
914 	return (error);
915 }
916 
917 /*
918  * XXXRW/JA: Shouldn't return name2oid data for nodes that we don't permit in
919  * capability mode.
920  */
921 SYSCTL_PROC(_sysctl, 3, name2oid,
922     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_MPSAFE
923     | CTLFLAG_CAPRW, 0, 0, sysctl_sysctl_name2oid, "I", "");
924 
925 static int
926 sysctl_sysctl_oidfmt(SYSCTL_HANDLER_ARGS)
927 {
928 	struct sysctl_oid *oid;
929 	int error;
930 
931 	SYSCTL_XLOCK();
932 	error = sysctl_find_oid(arg1, arg2, &oid, NULL, req);
933 	if (error)
934 		goto out;
935 
936 	if (oid->oid_fmt == NULL) {
937 		error = ENOENT;
938 		goto out;
939 	}
940 	error = SYSCTL_OUT(req, &oid->oid_kind, sizeof(oid->oid_kind));
941 	if (error)
942 		goto out;
943 	error = SYSCTL_OUT(req, oid->oid_fmt, strlen(oid->oid_fmt) + 1);
944  out:
945 	SYSCTL_XUNLOCK();
946 	return (error);
947 }
948 
949 
950 static SYSCTL_NODE(_sysctl, 4, oidfmt, CTLFLAG_RD|CTLFLAG_MPSAFE|CTLFLAG_CAPRD,
951     sysctl_sysctl_oidfmt, "");
952 
953 static int
954 sysctl_sysctl_oiddescr(SYSCTL_HANDLER_ARGS)
955 {
956 	struct sysctl_oid *oid;
957 	int error;
958 
959 	SYSCTL_XLOCK();
960 	error = sysctl_find_oid(arg1, arg2, &oid, NULL, req);
961 	if (error)
962 		goto out;
963 
964 	if (oid->oid_descr == NULL) {
965 		error = ENOENT;
966 		goto out;
967 	}
968 	error = SYSCTL_OUT(req, oid->oid_descr, strlen(oid->oid_descr) + 1);
969  out:
970 	SYSCTL_XUNLOCK();
971 	return (error);
972 }
973 
974 static SYSCTL_NODE(_sysctl, 5, oiddescr, CTLFLAG_RD|CTLFLAG_CAPRD,
975     sysctl_sysctl_oiddescr, "");
976 
977 /*
978  * Default "handler" functions.
979  */
980 
981 /*
982  * Handle an int, signed or unsigned.
983  * Two cases:
984  *     a variable:  point arg1 at it.
985  *     a constant:  pass it in arg2.
986  */
987 
988 int
989 sysctl_handle_int(SYSCTL_HANDLER_ARGS)
990 {
991 	int tmpout, error = 0;
992 
993 	/*
994 	 * Attempt to get a coherent snapshot by making a copy of the data.
995 	 */
996 	if (arg1)
997 		tmpout = *(int *)arg1;
998 	else
999 		tmpout = arg2;
1000 	error = SYSCTL_OUT(req, &tmpout, sizeof(int));
1001 
1002 	if (error || !req->newptr)
1003 		return (error);
1004 
1005 	if (!arg1)
1006 		error = EPERM;
1007 	else
1008 		error = SYSCTL_IN(req, arg1, sizeof(int));
1009 	return (error);
1010 }
1011 
1012 /*
1013  * Based on on sysctl_handle_int() convert milliseconds into ticks.
1014  * Note: this is used by TCP.
1015  */
1016 
1017 int
1018 sysctl_msec_to_ticks(SYSCTL_HANDLER_ARGS)
1019 {
1020 	int error, s, tt;
1021 
1022 	tt = *(int *)arg1;
1023 	s = (int)((int64_t)tt * 1000 / hz);
1024 
1025 	error = sysctl_handle_int(oidp, &s, 0, req);
1026 	if (error || !req->newptr)
1027 		return (error);
1028 
1029 	tt = (int)((int64_t)s * hz / 1000);
1030 	if (tt < 1)
1031 		return (EINVAL);
1032 
1033 	*(int *)arg1 = tt;
1034 	return (0);
1035 }
1036 
1037 
1038 /*
1039  * Handle a long, signed or unsigned.
1040  * Two cases:
1041  *     a variable:  point arg1 at it.
1042  *     a constant:  pass it in arg2.
1043  */
1044 
1045 int
1046 sysctl_handle_long(SYSCTL_HANDLER_ARGS)
1047 {
1048 	int error = 0;
1049 	long tmplong;
1050 #ifdef SCTL_MASK32
1051 	int tmpint;
1052 #endif
1053 
1054 	/*
1055 	 * Attempt to get a coherent snapshot by making a copy of the data.
1056 	 */
1057 	if (arg1)
1058 		tmplong = *(long *)arg1;
1059 	else
1060 		tmplong = arg2;
1061 #ifdef SCTL_MASK32
1062 	if (req->flags & SCTL_MASK32) {
1063 		tmpint = tmplong;
1064 		error = SYSCTL_OUT(req, &tmpint, sizeof(int));
1065 	} else
1066 #endif
1067 		error = SYSCTL_OUT(req, &tmplong, sizeof(long));
1068 
1069 	if (error || !req->newptr)
1070 		return (error);
1071 
1072 	if (!arg1)
1073 		error = EPERM;
1074 #ifdef SCTL_MASK32
1075 	else if (req->flags & SCTL_MASK32) {
1076 		error = SYSCTL_IN(req, &tmpint, sizeof(int));
1077 		*(long *)arg1 = (long)tmpint;
1078 	}
1079 #endif
1080 	else
1081 		error = SYSCTL_IN(req, arg1, sizeof(long));
1082 	return (error);
1083 }
1084 
1085 /*
1086  * Handle a 64 bit int, signed or unsigned.
1087  * Two cases:
1088  *     a variable:  point arg1 at it.
1089  *     a constant:  pass it in arg2.
1090  */
1091 int
1092 sysctl_handle_64(SYSCTL_HANDLER_ARGS)
1093 {
1094 	int error = 0;
1095 	uint64_t tmpout;
1096 
1097 	/*
1098 	 * Attempt to get a coherent snapshot by making a copy of the data.
1099 	 */
1100 	if (arg1)
1101 		tmpout = *(uint64_t *)arg1;
1102 	else
1103 		tmpout = arg2;
1104 	error = SYSCTL_OUT(req, &tmpout, sizeof(uint64_t));
1105 
1106 	if (error || !req->newptr)
1107 		return (error);
1108 
1109 	if (!arg1)
1110 		error = EPERM;
1111 	else
1112 		error = SYSCTL_IN(req, arg1, sizeof(uint64_t));
1113 	return (error);
1114 }
1115 
1116 /*
1117  * Handle our generic '\0' terminated 'C' string.
1118  * Two cases:
1119  * 	a variable string:  point arg1 at it, arg2 is max length.
1120  * 	a constant string:  point arg1 at it, arg2 is zero.
1121  */
1122 
1123 int
1124 sysctl_handle_string(SYSCTL_HANDLER_ARGS)
1125 {
1126 	int error=0;
1127 	char *tmparg;
1128 	size_t outlen;
1129 
1130 	/*
1131 	 * Attempt to get a coherent snapshot by copying to a
1132 	 * temporary kernel buffer.
1133 	 */
1134 retry:
1135 	outlen = strlen((char *)arg1)+1;
1136 	tmparg = malloc(outlen, M_SYSCTLTMP, M_WAITOK);
1137 
1138 	if (strlcpy(tmparg, (char *)arg1, outlen) >= outlen) {
1139 		free(tmparg, M_SYSCTLTMP);
1140 		goto retry;
1141 	}
1142 
1143 	error = SYSCTL_OUT(req, tmparg, outlen);
1144 	free(tmparg, M_SYSCTLTMP);
1145 
1146 	if (error || !req->newptr)
1147 		return (error);
1148 
1149 	if ((req->newlen - req->newidx) >= arg2) {
1150 		error = EINVAL;
1151 	} else {
1152 		arg2 = (req->newlen - req->newidx);
1153 		error = SYSCTL_IN(req, arg1, arg2);
1154 		((char *)arg1)[arg2] = '\0';
1155 	}
1156 
1157 	return (error);
1158 }
1159 
1160 /*
1161  * Handle any kind of opaque data.
1162  * arg1 points to it, arg2 is the size.
1163  */
1164 
1165 int
1166 sysctl_handle_opaque(SYSCTL_HANDLER_ARGS)
1167 {
1168 	int error, tries;
1169 	u_int generation;
1170 	struct sysctl_req req2;
1171 
1172 	/*
1173 	 * Attempt to get a coherent snapshot, by using the thread
1174 	 * pre-emption counter updated from within mi_switch() to
1175 	 * determine if we were pre-empted during a bcopy() or
1176 	 * copyout(). Make 3 attempts at doing this before giving up.
1177 	 * If we encounter an error, stop immediately.
1178 	 */
1179 	tries = 0;
1180 	req2 = *req;
1181 retry:
1182 	generation = curthread->td_generation;
1183 	error = SYSCTL_OUT(req, arg1, arg2);
1184 	if (error)
1185 		return (error);
1186 	tries++;
1187 	if (generation != curthread->td_generation && tries < 3) {
1188 		*req = req2;
1189 		goto retry;
1190 	}
1191 
1192 	error = SYSCTL_IN(req, arg1, arg2);
1193 
1194 	return (error);
1195 }
1196 
1197 /*
1198  * Transfer functions to/from kernel space.
1199  * XXX: rather untested at this point
1200  */
1201 static int
1202 sysctl_old_kernel(struct sysctl_req *req, const void *p, size_t l)
1203 {
1204 	size_t i = 0;
1205 
1206 	if (req->oldptr) {
1207 		i = l;
1208 		if (req->oldlen <= req->oldidx)
1209 			i = 0;
1210 		else
1211 			if (i > req->oldlen - req->oldidx)
1212 				i = req->oldlen - req->oldidx;
1213 		if (i > 0)
1214 			bcopy(p, (char *)req->oldptr + req->oldidx, i);
1215 	}
1216 	req->oldidx += l;
1217 	if (req->oldptr && i != l)
1218 		return (ENOMEM);
1219 	return (0);
1220 }
1221 
1222 static int
1223 sysctl_new_kernel(struct sysctl_req *req, void *p, size_t l)
1224 {
1225 	if (!req->newptr)
1226 		return (0);
1227 	if (req->newlen - req->newidx < l)
1228 		return (EINVAL);
1229 	bcopy((char *)req->newptr + req->newidx, p, l);
1230 	req->newidx += l;
1231 	return (0);
1232 }
1233 
1234 int
1235 kernel_sysctl(struct thread *td, int *name, u_int namelen, void *old,
1236     size_t *oldlenp, void *new, size_t newlen, size_t *retval, int flags)
1237 {
1238 	int error = 0;
1239 	struct sysctl_req req;
1240 
1241 	bzero(&req, sizeof req);
1242 
1243 	req.td = td;
1244 	req.flags = flags;
1245 
1246 	if (oldlenp) {
1247 		req.oldlen = *oldlenp;
1248 	}
1249 	req.validlen = req.oldlen;
1250 
1251 	if (old) {
1252 		req.oldptr= old;
1253 	}
1254 
1255 	if (new != NULL) {
1256 		req.newlen = newlen;
1257 		req.newptr = new;
1258 	}
1259 
1260 	req.oldfunc = sysctl_old_kernel;
1261 	req.newfunc = sysctl_new_kernel;
1262 	req.lock = REQ_UNWIRED;
1263 
1264 	SYSCTL_XLOCK();
1265 	error = sysctl_root(0, name, namelen, &req);
1266 	SYSCTL_XUNLOCK();
1267 
1268 	if (req.lock == REQ_WIRED && req.validlen > 0)
1269 		vsunlock(req.oldptr, req.validlen);
1270 
1271 	if (error && error != ENOMEM)
1272 		return (error);
1273 
1274 	if (retval) {
1275 		if (req.oldptr && req.oldidx > req.validlen)
1276 			*retval = req.validlen;
1277 		else
1278 			*retval = req.oldidx;
1279 	}
1280 	return (error);
1281 }
1282 
1283 int
1284 kernel_sysctlbyname(struct thread *td, char *name, void *old, size_t *oldlenp,
1285     void *new, size_t newlen, size_t *retval, int flags)
1286 {
1287         int oid[CTL_MAXNAME];
1288         size_t oidlen, plen;
1289 	int error;
1290 
1291 	oid[0] = 0;		/* sysctl internal magic */
1292 	oid[1] = 3;		/* name2oid */
1293 	oidlen = sizeof(oid);
1294 
1295 	error = kernel_sysctl(td, oid, 2, oid, &oidlen,
1296 	    (void *)name, strlen(name), &plen, flags);
1297 	if (error)
1298 		return (error);
1299 
1300 	error = kernel_sysctl(td, oid, plen / sizeof(int), old, oldlenp,
1301 	    new, newlen, retval, flags);
1302 	return (error);
1303 }
1304 
1305 /*
1306  * Transfer function to/from user space.
1307  */
1308 static int
1309 sysctl_old_user(struct sysctl_req *req, const void *p, size_t l)
1310 {
1311 	size_t i, len, origidx;
1312 	int error;
1313 
1314 	origidx = req->oldidx;
1315 	req->oldidx += l;
1316 	if (req->oldptr == NULL)
1317 		return (0);
1318 	/*
1319 	 * If we have not wired the user supplied buffer and we are currently
1320 	 * holding locks, drop a witness warning, as it's possible that
1321 	 * write operations to the user page can sleep.
1322 	 */
1323 	if (req->lock != REQ_WIRED)
1324 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1325 		    "sysctl_old_user()");
1326 	i = l;
1327 	len = req->validlen;
1328 	if (len <= origidx)
1329 		i = 0;
1330 	else {
1331 		if (i > len - origidx)
1332 			i = len - origidx;
1333 		if (req->lock == REQ_WIRED) {
1334 			error = copyout_nofault(p, (char *)req->oldptr +
1335 			    origidx, i);
1336 		} else
1337 			error = copyout(p, (char *)req->oldptr + origidx, i);
1338 		if (error != 0)
1339 			return (error);
1340 	}
1341 	if (i < l)
1342 		return (ENOMEM);
1343 	return (0);
1344 }
1345 
1346 static int
1347 sysctl_new_user(struct sysctl_req *req, void *p, size_t l)
1348 {
1349 	int error;
1350 
1351 	if (!req->newptr)
1352 		return (0);
1353 	if (req->newlen - req->newidx < l)
1354 		return (EINVAL);
1355 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1356 	    "sysctl_new_user()");
1357 	error = copyin((char *)req->newptr + req->newidx, p, l);
1358 	req->newidx += l;
1359 	return (error);
1360 }
1361 
1362 /*
1363  * Wire the user space destination buffer.  If set to a value greater than
1364  * zero, the len parameter limits the maximum amount of wired memory.
1365  */
1366 int
1367 sysctl_wire_old_buffer(struct sysctl_req *req, size_t len)
1368 {
1369 	int ret;
1370 	size_t wiredlen;
1371 
1372 	wiredlen = (len > 0 && len < req->oldlen) ? len : req->oldlen;
1373 	ret = 0;
1374 	if (req->lock != REQ_WIRED && req->oldptr &&
1375 	    req->oldfunc == sysctl_old_user) {
1376 		if (wiredlen != 0) {
1377 			ret = vslock(req->oldptr, wiredlen);
1378 			if (ret != 0) {
1379 				if (ret != ENOMEM)
1380 					return (ret);
1381 				wiredlen = 0;
1382 			}
1383 		}
1384 		req->lock = REQ_WIRED;
1385 		req->validlen = wiredlen;
1386 	}
1387 	return (0);
1388 }
1389 
1390 int
1391 sysctl_find_oid(int *name, u_int namelen, struct sysctl_oid **noid,
1392     int *nindx, struct sysctl_req *req)
1393 {
1394 	struct sysctl_oid_list *lsp;
1395 	struct sysctl_oid *oid;
1396 	int indx;
1397 
1398 	SYSCTL_ASSERT_XLOCKED();
1399 	lsp = &sysctl__children;
1400 	indx = 0;
1401 	while (indx < CTL_MAXNAME) {
1402 		SLIST_FOREACH(oid, lsp, oid_link) {
1403 			if (oid->oid_number == name[indx])
1404 				break;
1405 		}
1406 		if (oid == NULL)
1407 			return (ENOENT);
1408 
1409 		indx++;
1410 		if ((oid->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
1411 			if (oid->oid_handler != NULL || indx == namelen) {
1412 				*noid = oid;
1413 				if (nindx != NULL)
1414 					*nindx = indx;
1415 				KASSERT((oid->oid_kind & CTLFLAG_DYING) == 0,
1416 				    ("%s found DYING node %p", __func__, oid));
1417 				return (0);
1418 			}
1419 			lsp = SYSCTL_CHILDREN(oid);
1420 		} else if (indx == namelen) {
1421 			*noid = oid;
1422 			if (nindx != NULL)
1423 				*nindx = indx;
1424 			KASSERT((oid->oid_kind & CTLFLAG_DYING) == 0,
1425 			    ("%s found DYING node %p", __func__, oid));
1426 			return (0);
1427 		} else {
1428 			return (ENOTDIR);
1429 		}
1430 	}
1431 	return (ENOENT);
1432 }
1433 
1434 /*
1435  * Traverse our tree, and find the right node, execute whatever it points
1436  * to, and return the resulting error code.
1437  */
1438 
1439 static int
1440 sysctl_root(SYSCTL_HANDLER_ARGS)
1441 {
1442 	struct sysctl_oid *oid;
1443 	int error, indx, lvl;
1444 
1445 	SYSCTL_ASSERT_XLOCKED();
1446 
1447 	error = sysctl_find_oid(arg1, arg2, &oid, &indx, req);
1448 	if (error)
1449 		return (error);
1450 
1451 	if ((oid->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
1452 		/*
1453 		 * You can't call a sysctl when it's a node, but has
1454 		 * no handler.  Inform the user that it's a node.
1455 		 * The indx may or may not be the same as namelen.
1456 		 */
1457 		if (oid->oid_handler == NULL)
1458 			return (EISDIR);
1459 	}
1460 
1461 	/* Is this sysctl writable? */
1462 	if (req->newptr && !(oid->oid_kind & CTLFLAG_WR))
1463 		return (EPERM);
1464 
1465 	KASSERT(req->td != NULL, ("sysctl_root(): req->td == NULL"));
1466 
1467 #ifdef CAPABILITY_MODE
1468 	/*
1469 	 * If the process is in capability mode, then don't permit reading or
1470 	 * writing unless specifically granted for the node.
1471 	 */
1472 	if (IN_CAPABILITY_MODE(req->td)) {
1473 		if (req->oldptr && !(oid->oid_kind & CTLFLAG_CAPRD))
1474 			return (EPERM);
1475 		if (req->newptr && !(oid->oid_kind & CTLFLAG_CAPWR))
1476 			return (EPERM);
1477 	}
1478 #endif
1479 
1480 	/* Is this sysctl sensitive to securelevels? */
1481 	if (req->newptr && (oid->oid_kind & CTLFLAG_SECURE)) {
1482 		lvl = (oid->oid_kind & CTLMASK_SECURE) >> CTLSHIFT_SECURE;
1483 		error = securelevel_gt(req->td->td_ucred, lvl);
1484 		if (error)
1485 			return (error);
1486 	}
1487 
1488 	/* Is this sysctl writable by only privileged users? */
1489 	if (req->newptr && !(oid->oid_kind & CTLFLAG_ANYBODY)) {
1490 		int priv;
1491 
1492 		if (oid->oid_kind & CTLFLAG_PRISON)
1493 			priv = PRIV_SYSCTL_WRITEJAIL;
1494 #ifdef VIMAGE
1495 		else if ((oid->oid_kind & CTLFLAG_VNET) &&
1496 		     prison_owns_vnet(req->td->td_ucred))
1497 			priv = PRIV_SYSCTL_WRITEJAIL;
1498 #endif
1499 		else
1500 			priv = PRIV_SYSCTL_WRITE;
1501 		error = priv_check(req->td, priv);
1502 		if (error)
1503 			return (error);
1504 	}
1505 
1506 	if (!oid->oid_handler)
1507 		return (EINVAL);
1508 
1509 	if ((oid->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
1510 		arg1 = (int *)arg1 + indx;
1511 		arg2 -= indx;
1512 	} else {
1513 		arg1 = oid->oid_arg1;
1514 		arg2 = oid->oid_arg2;
1515 	}
1516 #ifdef MAC
1517 	error = mac_system_check_sysctl(req->td->td_ucred, oid, arg1, arg2,
1518 	    req);
1519 	if (error != 0)
1520 		return (error);
1521 #endif
1522 	oid->oid_running++;
1523 	SYSCTL_XUNLOCK();
1524 
1525 	if (!(oid->oid_kind & CTLFLAG_MPSAFE))
1526 		mtx_lock(&Giant);
1527 	error = oid->oid_handler(oid, arg1, arg2, req);
1528 	if (!(oid->oid_kind & CTLFLAG_MPSAFE))
1529 		mtx_unlock(&Giant);
1530 
1531 	KFAIL_POINT_ERROR(_debug_fail_point, sysctl_running, error);
1532 
1533 	SYSCTL_XLOCK();
1534 	oid->oid_running--;
1535 	if (oid->oid_running == 0 && (oid->oid_kind & CTLFLAG_DYING) != 0)
1536 		wakeup(&oid->oid_running);
1537 	return (error);
1538 }
1539 
1540 #ifndef _SYS_SYSPROTO_H_
1541 struct sysctl_args {
1542 	int	*name;
1543 	u_int	namelen;
1544 	void	*old;
1545 	size_t	*oldlenp;
1546 	void	*new;
1547 	size_t	newlen;
1548 };
1549 #endif
1550 int
1551 sys___sysctl(struct thread *td, struct sysctl_args *uap)
1552 {
1553 	int error, i, name[CTL_MAXNAME];
1554 	size_t j;
1555 
1556 	if (uap->namelen > CTL_MAXNAME || uap->namelen < 2)
1557 		return (EINVAL);
1558 
1559  	error = copyin(uap->name, &name, uap->namelen * sizeof(int));
1560  	if (error)
1561 		return (error);
1562 
1563 	error = userland_sysctl(td, name, uap->namelen,
1564 		uap->old, uap->oldlenp, 0,
1565 		uap->new, uap->newlen, &j, 0);
1566 	if (error && error != ENOMEM)
1567 		return (error);
1568 	if (uap->oldlenp) {
1569 		i = copyout(&j, uap->oldlenp, sizeof(j));
1570 		if (i)
1571 			return (i);
1572 	}
1573 	return (error);
1574 }
1575 
1576 /*
1577  * This is used from various compatibility syscalls too.  That's why name
1578  * must be in kernel space.
1579  */
1580 int
1581 userland_sysctl(struct thread *td, int *name, u_int namelen, void *old,
1582     size_t *oldlenp, int inkernel, void *new, size_t newlen, size_t *retval,
1583     int flags)
1584 {
1585 	int error = 0, memlocked;
1586 	struct sysctl_req req;
1587 
1588 	bzero(&req, sizeof req);
1589 
1590 	req.td = td;
1591 	req.flags = flags;
1592 
1593 	if (oldlenp) {
1594 		if (inkernel) {
1595 			req.oldlen = *oldlenp;
1596 		} else {
1597 			error = copyin(oldlenp, &req.oldlen, sizeof(*oldlenp));
1598 			if (error)
1599 				return (error);
1600 		}
1601 	}
1602 	req.validlen = req.oldlen;
1603 
1604 	if (old) {
1605 		if (!useracc(old, req.oldlen, VM_PROT_WRITE))
1606 			return (EFAULT);
1607 		req.oldptr= old;
1608 	}
1609 
1610 	if (new != NULL) {
1611 		if (!useracc(new, newlen, VM_PROT_READ))
1612 			return (EFAULT);
1613 		req.newlen = newlen;
1614 		req.newptr = new;
1615 	}
1616 
1617 	req.oldfunc = sysctl_old_user;
1618 	req.newfunc = sysctl_new_user;
1619 	req.lock = REQ_UNWIRED;
1620 
1621 #ifdef KTRACE
1622 	if (KTRPOINT(curthread, KTR_SYSCTL))
1623 		ktrsysctl(name, namelen);
1624 #endif
1625 
1626 	if (req.oldlen > PAGE_SIZE) {
1627 		memlocked = 1;
1628 		sx_xlock(&sysctlmemlock);
1629 	} else
1630 		memlocked = 0;
1631 	CURVNET_SET(TD_TO_VNET(td));
1632 
1633 	for (;;) {
1634 		req.oldidx = 0;
1635 		req.newidx = 0;
1636 		SYSCTL_XLOCK();
1637 		error = sysctl_root(0, name, namelen, &req);
1638 		SYSCTL_XUNLOCK();
1639 		if (error != EAGAIN)
1640 			break;
1641 		kern_yield(PRI_USER);
1642 	}
1643 
1644 	CURVNET_RESTORE();
1645 
1646 	if (req.lock == REQ_WIRED && req.validlen > 0)
1647 		vsunlock(req.oldptr, req.validlen);
1648 	if (memlocked)
1649 		sx_xunlock(&sysctlmemlock);
1650 
1651 	if (error && error != ENOMEM)
1652 		return (error);
1653 
1654 	if (retval) {
1655 		if (req.oldptr && req.oldidx > req.validlen)
1656 			*retval = req.validlen;
1657 		else
1658 			*retval = req.oldidx;
1659 	}
1660 	return (error);
1661 }
1662 
1663 /*
1664  * Drain into a sysctl struct.  The user buffer should be wired if a page
1665  * fault would cause issue.
1666  */
1667 static int
1668 sbuf_sysctl_drain(void *arg, const char *data, int len)
1669 {
1670 	struct sysctl_req *req = arg;
1671 	int error;
1672 
1673 	error = SYSCTL_OUT(req, data, len);
1674 	KASSERT(error >= 0, ("Got unexpected negative value %d", error));
1675 	return (error == 0 ? len : -error);
1676 }
1677 
1678 struct sbuf *
1679 sbuf_new_for_sysctl(struct sbuf *s, char *buf, int length,
1680     struct sysctl_req *req)
1681 {
1682 
1683 	s = sbuf_new(s, buf, length, SBUF_FIXEDLEN);
1684 	sbuf_set_drain(s, sbuf_sysctl_drain, req);
1685 	return (s);
1686 }
1687