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