Home | History | Annotate | Line # | Download | only in kern
kern_sysctl.c revision 1.201
      1 /*	$NetBSD: kern_sysctl.c,v 1.201 2006/09/02 06:33:11 christos Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2003 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Andrew Brown.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *      This product includes software developed by the NetBSD
     21  *      Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 /*-
     40  * Copyright (c) 1982, 1986, 1989, 1993
     41  *	The Regents of the University of California.  All rights reserved.
     42  *
     43  * This code is derived from software contributed to Berkeley by
     44  * Mike Karels at Berkeley Software Design, Inc.
     45  *
     46  * Redistribution and use in source and binary forms, with or without
     47  * modification, are permitted provided that the following conditions
     48  * are met:
     49  * 1. Redistributions of source code must retain the above copyright
     50  *    notice, this list of conditions and the following disclaimer.
     51  * 2. Redistributions in binary form must reproduce the above copyright
     52  *    notice, this list of conditions and the following disclaimer in the
     53  *    documentation and/or other materials provided with the distribution.
     54  * 3. Neither the name of the University nor the names of its contributors
     55  *    may be used to endorse or promote products derived from this software
     56  *    without specific prior written permission.
     57  *
     58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     68  * SUCH DAMAGE.
     69  *
     70  *	@(#)kern_sysctl.c	8.9 (Berkeley) 5/20/95
     71  */
     72 
     73 /*
     74  * sysctl system call.
     75  */
     76 
     77 #include <sys/cdefs.h>
     78 __KERNEL_RCSID(0, "$NetBSD: kern_sysctl.c,v 1.201 2006/09/02 06:33:11 christos Exp $");
     79 
     80 #include "opt_defcorename.h"
     81 #include "ksyms.h"
     82 
     83 #include <sys/param.h>
     84 #define __COMPAT_SYSCTL
     85 #include <sys/sysctl.h>
     86 #include <sys/systm.h>
     87 #include <sys/buf.h>
     88 #include <sys/ksyms.h>
     89 #include <sys/malloc.h>
     90 #include <sys/mount.h>
     91 #include <sys/sa.h>
     92 #include <sys/syscallargs.h>
     93 #include <sys/kauth.h>
     94 #include <machine/stdarg.h>
     95 
     96 #define	MAXDESCLEN	1024
     97 MALLOC_DEFINE(M_SYSCTLNODE, "sysctlnode", "sysctl node structures");
     98 MALLOC_DEFINE(M_SYSCTLDATA, "sysctldata", "misc sysctl data");
     99 
    100 static int sysctl_mmap(SYSCTLFN_PROTO);
    101 static int sysctl_alloc(struct sysctlnode *, int);
    102 static int sysctl_realloc(struct sysctlnode *);
    103 
    104 static int sysctl_cvt_in(struct lwp *, int *, const void *, size_t,
    105 			 struct sysctlnode *);
    106 static int sysctl_cvt_out(struct lwp *, int, const struct sysctlnode *,
    107 			  void *, size_t, size_t *);
    108 
    109 static int sysctl_log_add(struct sysctllog **, const struct sysctlnode *);
    110 static int sysctl_log_realloc(struct sysctllog *);
    111 
    112 struct sysctllog {
    113 	const struct sysctlnode *log_root;
    114 	int *log_num;
    115 	int log_size, log_left;
    116 };
    117 
    118 /*
    119  * the "root" of the new sysctl tree
    120  */
    121 struct sysctlnode sysctl_root = {
    122 	.sysctl_flags = SYSCTL_VERSION|
    123 	    CTLFLAG_ROOT|CTLFLAG_READWRITE|
    124 	    CTLTYPE_NODE,
    125 	.sysctl_num = 0,
    126 	/*
    127 	 * XXX once all ports are on gcc3, we can get rid of this
    128 	 * ugliness and simply make it into
    129 	 *
    130 	 *	.sysctl_size = sizeof(struct sysctlnode),
    131 	 */
    132 	sysc_init_field(_sysctl_size, sizeof(struct sysctlnode)),
    133 	.sysctl_name = "(root)",
    134 };
    135 
    136 /*
    137  * link set of functions that add nodes at boot time (see also
    138  * sysctl_buildtree())
    139  */
    140 __link_set_decl(sysctl_funcs, sysctl_setup_func);
    141 
    142 /*
    143  * The `sysctl_lock' is intended to serialize access to the sysctl
    144  * tree.  Given that it is now (a) dynamic, and (b) most consumers of
    145  * sysctl are going to be copying data out, the old `sysctl_memlock'
    146  * has been `upgraded' to simply guard the whole tree.
    147  *
    148  * The two new data here are to keep track of the locked chunk of
    149  * memory, if there is one, so that it can be released more easily
    150  * from anywhere.
    151  */
    152 struct lock sysctl_treelock;
    153 caddr_t sysctl_memaddr;
    154 size_t sysctl_memsize;
    155 
    156 /*
    157  * Attributes stored in the kernel.
    158  */
    159 char hostname[MAXHOSTNAMELEN];
    160 int hostnamelen;
    161 
    162 char domainname[MAXHOSTNAMELEN];
    163 int domainnamelen;
    164 
    165 long hostid;
    166 
    167 #ifndef DEFCORENAME
    168 #define	DEFCORENAME	"%n.core"
    169 #endif
    170 char defcorename[MAXPATHLEN] = DEFCORENAME;
    171 
    172 /*
    173  * ********************************************************************
    174  * Section 0: Some simple glue
    175  * ********************************************************************
    176  * By wrapping copyin(), copyout(), and copyinstr() like this, we can
    177  * stop caring about who's calling us and simplify some code a bunch.
    178  * ********************************************************************
    179  */
    180 static inline int
    181 sysctl_copyin(const struct lwp *l, const void *uaddr, void *kaddr, size_t len)
    182 {
    183 
    184 	if (l != NULL)
    185 		return (copyin(uaddr, kaddr, len));
    186 	else
    187 		return (kcopy(uaddr, kaddr, len));
    188 }
    189 
    190 static inline int
    191 sysctl_copyout(const struct lwp *l, const void *kaddr, void *uaddr, size_t len)
    192 {
    193 
    194 	if (l != NULL)
    195 		return (copyout(kaddr, uaddr, len));
    196 	else
    197 		return (kcopy(kaddr, uaddr, len));
    198 }
    199 
    200 static inline int
    201 sysctl_copyinstr(const struct lwp *l, const void *uaddr, void *kaddr,
    202 		 size_t len, size_t *done)
    203 {
    204 
    205 	if (l != NULL)
    206 		return (copyinstr(uaddr, kaddr, len, done));
    207 	else
    208 		return (copystr(uaddr, kaddr, len, done));
    209 }
    210 
    211 /*
    212  * ********************************************************************
    213  * Initialize sysctl subsystem.
    214  * ********************************************************************
    215  */
    216 void
    217 sysctl_init(void)
    218 {
    219 	sysctl_setup_func * const *sysctl_setup, f;
    220 
    221 	lockinit(&sysctl_treelock, PRIBIO|PCATCH, "sysctl", 0, 0);
    222 
    223 	/*
    224 	 * dynamic mib numbers start here
    225 	 */
    226 	sysctl_root.sysctl_num = CREATE_BASE;
    227 
    228         __link_set_foreach(sysctl_setup, sysctl_funcs) {
    229 		/*
    230 		 * XXX - why do i have to coerce the pointers like this?
    231 		 */
    232 		f = (void*)*sysctl_setup;
    233 		(*f)(NULL);
    234 	}
    235 
    236 	/*
    237 	 * setting this means no more permanent nodes can be added,
    238 	 * trees that claim to be readonly at the root now are, and if
    239 	 * the main tree is readonly, *everything* is.
    240 	 */
    241 	sysctl_root.sysctl_flags |= CTLFLAG_PERMANENT;
    242 
    243 }
    244 
    245 /*
    246  * ********************************************************************
    247  * The main native sysctl system call itself.
    248  * ********************************************************************
    249  */
    250 int
    251 sys___sysctl(struct lwp *l, void *v, register_t *retval)
    252 {
    253 	struct sys___sysctl_args /* {
    254 		syscallarg(const int *) name;
    255 		syscallarg(u_int) namelen;
    256 		syscallarg(void *) old;
    257 		syscallarg(size_t *) oldlenp;
    258 		syscallarg(const void *) new;
    259 		syscallarg(size_t) newlen;
    260 	} */ *uap = v;
    261 	int error, nerror, name[CTL_MAXNAME];
    262 	size_t oldlen, savelen, *oldlenp;
    263 
    264 	/*
    265 	 * get oldlen
    266 	 */
    267 	oldlen = 0;
    268 	oldlenp = SCARG(uap, oldlenp);
    269 	if (oldlenp != NULL) {
    270 		error = copyin(oldlenp, &oldlen, sizeof(oldlen));
    271 		if (error)
    272 			return (error);
    273 	}
    274 	savelen = oldlen;
    275 
    276 	/*
    277 	 * top-level sysctl names may or may not be non-terminal, but
    278 	 * we don't care
    279 	 */
    280 	if (SCARG(uap, namelen) > CTL_MAXNAME || SCARG(uap, namelen) < 1)
    281 		return (EINVAL);
    282 	error = copyin(SCARG(uap, name), &name,
    283 		       SCARG(uap, namelen) * sizeof(int));
    284 	if (error)
    285 		return (error);
    286 
    287 	/*
    288 	 * wire old so that copyout() is less likely to fail?
    289 	 */
    290 	error = sysctl_lock(l, SCARG(uap, old), savelen);
    291 	if (error)
    292 		return (error);
    293 
    294 	/*
    295 	 * do sysctl work (NULL means main built-in default tree)
    296 	 */
    297 	error = sysctl_dispatch(&name[0], SCARG(uap, namelen),
    298 				SCARG(uap, old), &oldlen,
    299 				SCARG(uap, new), SCARG(uap, newlen),
    300 				&name[0], l, NULL);
    301 
    302 	/*
    303 	 * release the sysctl lock
    304 	 */
    305 	sysctl_unlock(l);
    306 
    307 	/*
    308 	 * set caller's oldlen to new value even in the face of an
    309 	 * error (if this gets an error and they didn't have one, they
    310 	 * get this one)
    311 	 */
    312 	if (oldlenp) {
    313 		nerror = copyout(&oldlen, oldlenp, sizeof(oldlen));
    314 		if (error == 0)
    315 			error = nerror;
    316 	}
    317 
    318 	/*
    319 	 * if the only problem is that we weren't given enough space,
    320 	 * that's an ENOMEM error
    321 	 */
    322 	if (error == 0 && SCARG(uap, old) != NULL && savelen < oldlen)
    323 		error = ENOMEM;
    324 
    325 	return (error);
    326 }
    327 
    328 /*
    329  * ********************************************************************
    330  * Section 1: How the tree is used
    331  * ********************************************************************
    332  * Implementations of sysctl for emulations should typically need only
    333  * these three functions in this order: lock the tree, dispatch
    334  * request into it, unlock the tree.
    335  * ********************************************************************
    336  */
    337 int
    338 sysctl_lock(struct lwp *l, void *oldp, size_t savelen)
    339 {
    340 	int error = 0;
    341 
    342 	error = lockmgr(&sysctl_treelock, LK_EXCLUSIVE, NULL);
    343 	if (error)
    344 		return (error);
    345 
    346 	if (l != NULL && oldp != NULL && savelen) {
    347 		/*
    348 		 * be lazy - memory is locked for short time only, so
    349 		 * just do a basic check against system limit
    350 		 */
    351 		if (uvmexp.wired + atop(savelen) > uvmexp.wiredmax) {
    352 			lockmgr(&sysctl_treelock, LK_RELEASE, NULL);
    353 			return (ENOMEM);
    354 		}
    355 		error = uvm_vslock(l->l_proc, oldp, savelen, VM_PROT_WRITE);
    356 		if (error) {
    357 			(void) lockmgr(&sysctl_treelock, LK_RELEASE, NULL);
    358 			return (error);
    359 		}
    360 		sysctl_memaddr = oldp;
    361 		sysctl_memsize = savelen;
    362 	}
    363 
    364 	return (0);
    365 }
    366 
    367 /*
    368  * ********************************************************************
    369  * the main sysctl dispatch routine.  scans the given tree and picks a
    370  * function to call based on what it finds.
    371  * ********************************************************************
    372  */
    373 int
    374 sysctl_dispatch(SYSCTLFN_ARGS)
    375 {
    376 	int error;
    377 	sysctlfn fn;
    378 	int ni;
    379 
    380 	if (rnode && SYSCTL_VERS(rnode->sysctl_flags) != SYSCTL_VERSION) {
    381 		printf("sysctl_dispatch: rnode %p wrong version\n", rnode);
    382 		return (EINVAL);
    383 	}
    384 
    385 	fn = NULL;
    386 	error = sysctl_locate(l, name, namelen, &rnode, &ni);
    387 
    388 	if (rnode->sysctl_func != NULL) {
    389 		/*
    390 		 * the node we ended up at has a function, so call it.  it can
    391 		 * hand off to query or create if it wants to.
    392 		 */
    393 		fn = rnode->sysctl_func;
    394 	} else if (error == 0) {
    395 		/*
    396 		 * we found the node they were looking for, so do a lookup.
    397 		 */
    398 		fn = (sysctlfn)sysctl_lookup; /* XXX may write to rnode */
    399 	} else if (error == ENOENT && (ni + 1) == namelen && name[ni] < 0) {
    400 		/*
    401 		 * prospective parent node found, but the terminal node was
    402 		 * not.  generic operations associate with the parent.
    403 		 */
    404 		switch (name[ni]) {
    405 		case CTL_QUERY:
    406 			fn = sysctl_query;
    407 			break;
    408 		case CTL_CREATE:
    409 #if NKSYMS > 0
    410 		case CTL_CREATESYM:
    411 #endif /* NKSYMS > 0 */
    412 			fn = (sysctlfn)sysctl_create; /* we own the rnode */
    413 			break;
    414 		case CTL_DESTROY:
    415 			fn = (sysctlfn)sysctl_destroy; /* we own the rnode */
    416 			break;
    417 		case CTL_MMAP:
    418 			fn = (sysctlfn)sysctl_mmap; /* we own the rnode */
    419 			break;
    420 		case CTL_DESCRIBE:
    421 			fn = sysctl_describe;
    422 			break;
    423 		default:
    424 			error = EOPNOTSUPP;
    425 			break;
    426 		}
    427 	}
    428 
    429 	/*
    430 	 * after all of that, maybe we found someone who knows how to
    431 	 * get us what we want?
    432 	 */
    433 	if (fn != NULL)
    434 		error = (*fn)(name + ni, namelen - ni, oldp, oldlenp,
    435 			      newp, newlen, name, l, rnode);
    436 	else if (error == 0)
    437 		error = EOPNOTSUPP;
    438 
    439 	return (error);
    440 }
    441 
    442 /*
    443  * ********************************************************************
    444  * Releases the tree lock.  Note that if uvm_vslock() was called when
    445  * the lock was taken, we release that memory now.  By keeping track
    446  * of where and how much by ourselves, the lock can be released much
    447  * more easily from anywhere.
    448  * ********************************************************************
    449  */
    450 void
    451 sysctl_unlock(struct lwp *l)
    452 {
    453 
    454 	if (l != NULL && sysctl_memsize != 0) {
    455 		uvm_vsunlock(l->l_proc, sysctl_memaddr, sysctl_memsize);
    456 		sysctl_memsize = 0;
    457 	}
    458 
    459 	(void) lockmgr(&sysctl_treelock, LK_RELEASE, NULL);
    460 }
    461 
    462 /*
    463  * ********************************************************************
    464  * Section 2: The main tree interfaces
    465  * ********************************************************************
    466  * This is how sysctl_dispatch() does its work, and you can too, by
    467  * calling these routines from helpers (though typically only
    468  * sysctl_lookup() will be used).  The tree MUST BE LOCKED when these
    469  * are called.
    470  * ********************************************************************
    471  */
    472 
    473 /*
    474  * sysctl_locate -- Finds the node matching the given mib under the
    475  * given tree (via rv).  If no tree is given, we fall back to the
    476  * native tree.  The current process (via l) is used for access
    477  * control on the tree (some nodes may be traversable only by root) and
    478  * on return, nip will show how many numbers in the mib were consumed.
    479  */
    480 int
    481 sysctl_locate(struct lwp *l, const int *name, u_int namelen,
    482 	      const struct sysctlnode **rnode, int *nip)
    483 {
    484 	const struct sysctlnode *node, *pnode;
    485 	int tn, si, ni, error, alias;
    486 
    487 	/*
    488 	 * basic checks and setup
    489 	 */
    490 	if (*rnode == NULL)
    491 		*rnode = &sysctl_root;
    492 	if (nip)
    493 		*nip = 0;
    494 	if (namelen == 0)
    495 		return (0);
    496 
    497 	/*
    498 	 * search starts from "root"
    499 	 */
    500 	pnode = *rnode;
    501 	if (SYSCTL_VERS(pnode->sysctl_flags) != SYSCTL_VERSION) {
    502 		printf("sysctl_locate: pnode %p wrong version\n", pnode);
    503 		return (EINVAL);
    504 	}
    505 	node = pnode->sysctl_child;
    506 	error = 0;
    507 
    508 	/*
    509 	 * scan for node to which new node should be attached
    510 	 */
    511 	for (ni = 0; ni < namelen; ni++) {
    512 		/*
    513 		 * walked off bottom of tree
    514 		 */
    515 		if (node == NULL) {
    516 			if (SYSCTL_TYPE(pnode->sysctl_flags) == CTLTYPE_NODE)
    517 				error = ENOENT;
    518 			else
    519 				error = ENOTDIR;
    520 			break;
    521 		}
    522 		/*
    523 		 * can anyone traverse this node or only root?
    524 		 */
    525 		if (l != NULL && (pnode->sysctl_flags & CTLFLAG_PRIVATE) &&
    526 		    (error = kauth_authorize_generic(l->l_cred,
    527 		    KAUTH_GENERIC_ISSUSER, &l->l_acflag)) != 0)
    528 			return (error);
    529 		/*
    530 		 * find a child node with the right number
    531 		 */
    532 		tn = name[ni];
    533 		alias = 0;
    534 
    535 		si = 0;
    536 		/*
    537 		 * Note: ANYNUMBER only matches positive integers.
    538 		 * Since ANYNUMBER is only permitted on single-node
    539 		 * sub-trees (eg proc), check before the loop and skip
    540 		 * it if we can.
    541 		 */
    542 		if ((node[si].sysctl_flags & CTLFLAG_ANYNUMBER) && (tn >= 0))
    543 			goto foundit;
    544 		for (; si < pnode->sysctl_clen; si++) {
    545 			if (node[si].sysctl_num == tn) {
    546 				if (node[si].sysctl_flags & CTLFLAG_ALIAS) {
    547 					if (alias++ == 4)
    548 						break;
    549 					else {
    550 						tn = node[si].sysctl_alias;
    551 						si = -1;
    552 					}
    553 				} else
    554 					goto foundit;
    555 			}
    556 		}
    557 		/*
    558 		 * if we ran off the end, it obviously doesn't exist
    559 		 */
    560 		error = ENOENT;
    561 		break;
    562 
    563 		/*
    564 		 * so far so good, move on down the line
    565 		 */
    566 	  foundit:
    567 		pnode = &node[si];
    568 		if (SYSCTL_TYPE(pnode->sysctl_flags) == CTLTYPE_NODE)
    569 			node = node[si].sysctl_child;
    570 		else
    571 			node = NULL;
    572 	}
    573 
    574 	*rnode = pnode;
    575 	if (nip)
    576 		*nip = ni;
    577 
    578 	return (error);
    579 }
    580 
    581 /*
    582  * sysctl_query -- The auto-discovery engine.  Copies out the structs
    583  * describing nodes under the given node and handles overlay trees.
    584  */
    585 int
    586 sysctl_query(SYSCTLFN_ARGS)
    587 {
    588 	int error, ni, elim, v;
    589 	size_t out, left, t;
    590 	const struct sysctlnode *enode, *onode;
    591 	struct sysctlnode qnode;
    592 
    593 	if (SYSCTL_VERS(rnode->sysctl_flags) != SYSCTL_VERSION) {
    594 		printf("sysctl_query: rnode %p wrong version\n", rnode);
    595 		return (EINVAL);
    596 	}
    597 
    598 	if (SYSCTL_TYPE(rnode->sysctl_flags) != CTLTYPE_NODE)
    599 		return (ENOTDIR);
    600 	if (namelen != 1 || name[0] != CTL_QUERY)
    601 		return (EINVAL);
    602 
    603 	error = 0;
    604 	out = 0;
    605 	left = *oldlenp;
    606 	elim = 0;
    607 	enode = NULL;
    608 
    609 	/*
    610 	 * translate the given request to a current node
    611 	 */
    612 	error = sysctl_cvt_in(l, &v, newp, newlen, &qnode);
    613 	if (error)
    614 		return (error);
    615 
    616 	/*
    617 	 * if the request specifies a version, check it
    618 	 */
    619 	if (qnode.sysctl_ver != 0) {
    620 		enode = rnode;
    621 		if (qnode.sysctl_ver != enode->sysctl_ver &&
    622 		    qnode.sysctl_ver != sysctl_rootof(enode)->sysctl_ver)
    623 			return (EINVAL);
    624 	}
    625 
    626 	/*
    627 	 * process has overlay tree
    628 	 */
    629 	if (l && l->l_proc->p_emul->e_sysctlovly) {
    630 		enode = l->l_proc->p_emul->e_sysctlovly;
    631 		elim = (name - oname);
    632 		error = sysctl_locate(l, oname, elim, &enode, NULL);
    633 		if (error == 0) {
    634 			/* ah, found parent in overlay */
    635 			elim = enode->sysctl_clen;
    636 			enode = enode->sysctl_child;
    637 		} else {
    638 			error = 0;
    639 			elim = 0;
    640 			enode = NULL;
    641 		}
    642 	}
    643 
    644 	for (ni = 0; ni < rnode->sysctl_clen; ni++) {
    645 		onode = &rnode->sysctl_child[ni];
    646 		if (enode && enode->sysctl_num == onode->sysctl_num) {
    647 			if (SYSCTL_TYPE(enode->sysctl_flags) != CTLTYPE_NODE)
    648 				onode = enode;
    649 			if (--elim > 0)
    650 				enode++;
    651 			else
    652 				enode = NULL;
    653 		}
    654 		error = sysctl_cvt_out(l, v, onode, oldp, left, &t);
    655 		if (error)
    656 			return (error);
    657 		if (oldp != NULL)
    658 			oldp = (char*)oldp + t;
    659 		out += t;
    660 		left -= MIN(left, t);
    661 	}
    662 
    663 	/*
    664 	 * overlay trees *MUST* be entirely consumed
    665 	 */
    666 	KASSERT(enode == NULL);
    667 
    668 	*oldlenp = out;
    669 
    670 	return (error);
    671 }
    672 
    673 /*
    674  * sysctl_create -- Adds a node (the description of which is taken
    675  * from newp) to the tree, returning a copy of it in the space pointed
    676  * to by oldp.  In the event that the requested slot is already taken
    677  * (either by name or by number), the offending node is returned
    678  * instead.  Yes, this is complex, but we want to make sure everything
    679  * is proper.
    680  */
    681 #ifdef SYSCTL_DEBUG_CREATE
    682 int _sysctl_create(SYSCTLFN_ARGS);
    683 int
    684 _sysctl_create(SYSCTLFN_ARGS)
    685 #else
    686 int
    687 sysctl_create(SYSCTLFN_ARGS)
    688 #endif
    689 {
    690 	struct sysctlnode nnode, *node, *pnode;
    691 	int error, ni, at, nm, type, sz, flags, anum, v;
    692 	void *own;
    693 
    694 	error = 0;
    695 	own = NULL;
    696 	anum = -1;
    697 
    698 	if (SYSCTL_VERS(rnode->sysctl_flags) != SYSCTL_VERSION) {
    699 		printf("sysctl_create: rnode %p wrong version\n", rnode);
    700 		return (EINVAL);
    701 	}
    702 
    703 	if (namelen != 1 || (name[namelen - 1] != CTL_CREATE
    704 #if NKSYMS > 0
    705 			     && name[namelen - 1] != CTL_CREATESYM
    706 #endif /* NKSYMS > 0 */
    707 			     ))
    708 		return (EINVAL);
    709 
    710 	/*
    711 	 * processes can only add nodes at securelevel 0, must be
    712 	 * root, and can't add nodes to a parent that's not writeable
    713 	 */
    714 	if (l != NULL) {
    715 #ifndef SYSCTL_DISALLOW_CREATE
    716 		if (securelevel > 0)
    717 			return (EPERM);
    718 		error = kauth_authorize_generic(l->l_cred,
    719 		    KAUTH_GENERIC_ISSUSER, &l->l_acflag);
    720 		if (error)
    721 			return (error);
    722 		if (!(rnode->sysctl_flags & CTLFLAG_READWRITE))
    723 #endif /* SYSCTL_DISALLOW_CREATE */
    724 			return (EPERM);
    725 	}
    726 
    727 	/*
    728 	 * nothing can add a node if:
    729 	 * we've finished initial set up and
    730 	 * the tree itself is not writeable or
    731 	 * the entire sysctl system is not writeable
    732 	 */
    733 	if ((sysctl_root.sysctl_flags & CTLFLAG_PERMANENT) &&
    734 	    (!(sysctl_rootof(rnode)->sysctl_flags & CTLFLAG_READWRITE) ||
    735 	     !(sysctl_root.sysctl_flags & CTLFLAG_READWRITE)))
    736 		return (EPERM);
    737 
    738 	/*
    739 	 * it must be a "node", not a "int" or something
    740 	 */
    741 	if (SYSCTL_TYPE(rnode->sysctl_flags) != CTLTYPE_NODE)
    742 		return (ENOTDIR);
    743 	if (rnode->sysctl_flags & CTLFLAG_ALIAS) {
    744 		printf("sysctl_create: attempt to add node to aliased "
    745 		       "node %p\n", rnode);
    746 		return (EINVAL);
    747 	}
    748 	pnode = __UNCONST(rnode); /* we are adding children to this node */
    749 
    750 	if (newp == NULL)
    751 		return (EINVAL);
    752 	error = sysctl_cvt_in(l, &v, newp, newlen, &nnode);
    753 	if (error)
    754 		return (error);
    755 
    756 	/*
    757 	 * nodes passed in don't *have* parents
    758 	 */
    759 	if (nnode.sysctl_parent != NULL)
    760 		return (EINVAL);
    761 
    762 	/*
    763 	 * if we are indeed adding it, it should be a "good" name and
    764 	 * number
    765 	 */
    766 	nm = nnode.sysctl_num;
    767 #if NKSYMS > 0
    768 	if (nm == CTL_CREATESYM)
    769 		nm = CTL_CREATE;
    770 #endif /* NKSYMS > 0 */
    771 	if (nm < 0 && nm != CTL_CREATE)
    772 		return (EINVAL);
    773 	sz = 0;
    774 
    775 	/*
    776 	 * the name can't start with a digit
    777 	 */
    778 	if (nnode.sysctl_name[sz] >= '0' &&
    779 	    nnode.sysctl_name[sz] <= '9')
    780 		return (EINVAL);
    781 
    782 	/*
    783 	 * the name must be only alphanumerics or - or _, longer than
    784 	 * 0 bytes and less that SYSCTL_NAMELEN
    785 	 */
    786 	while (sz < SYSCTL_NAMELEN && nnode.sysctl_name[sz] != '\0') {
    787 		if ((nnode.sysctl_name[sz] >= '0' &&
    788 		     nnode.sysctl_name[sz] <= '9') ||
    789 		    (nnode.sysctl_name[sz] >= 'A' &&
    790 		     nnode.sysctl_name[sz] <= 'Z') ||
    791 		    (nnode.sysctl_name[sz] >= 'a' &&
    792 		     nnode.sysctl_name[sz] <= 'z') ||
    793 		    nnode.sysctl_name[sz] == '-' ||
    794 		    nnode.sysctl_name[sz] == '_')
    795 			sz++;
    796 		else
    797 			return (EINVAL);
    798 	}
    799 	if (sz == 0 || sz == SYSCTL_NAMELEN)
    800 		return (EINVAL);
    801 
    802 	/*
    803 	 * various checks revolve around size vs type, etc
    804 	 */
    805 	type = SYSCTL_TYPE(nnode.sysctl_flags);
    806 	flags = SYSCTL_FLAGS(nnode.sysctl_flags);
    807 	sz = nnode.sysctl_size;
    808 
    809 	/*
    810 	 * find out if there's a collision, and if so, let the caller
    811 	 * know what they collided with
    812 	 */
    813 	node = pnode->sysctl_child;
    814 	at = 0;
    815 	if (node) {
    816 		if ((flags | node->sysctl_flags) & CTLFLAG_ANYNUMBER)
    817 			/* No siblings for a CTLFLAG_ANYNUMBER node */
    818 			return EINVAL;
    819 		for (ni = 0; ni < pnode->sysctl_clen; ni++) {
    820 			if (nm == node[ni].sysctl_num ||
    821 			    strcmp(nnode.sysctl_name, node[ni].sysctl_name) == 0) {
    822 				/*
    823 				 * ignore error here, since we
    824 				 * are already fixed on EEXIST
    825 				 */
    826 				(void)sysctl_cvt_out(l, v, &node[ni], oldp,
    827 						     *oldlenp, oldlenp);
    828 				return (EEXIST);
    829 			}
    830 			if (nm > node[ni].sysctl_num)
    831 				at++;
    832 		}
    833 	}
    834 
    835 	/*
    836 	 * use sysctl_ver to add to the tree iff it hasn't changed
    837 	 */
    838 	if (nnode.sysctl_ver != 0) {
    839 		/*
    840 		 * a specified value must match either the parent
    841 		 * node's version or the root node's version
    842 		 */
    843 		if (nnode.sysctl_ver != sysctl_rootof(rnode)->sysctl_ver &&
    844 		    nnode.sysctl_ver != rnode->sysctl_ver) {
    845 			return (EINVAL);
    846 		}
    847 	}
    848 
    849 	/*
    850 	 * only the kernel can assign functions to entries
    851 	 */
    852 	if (l != NULL && nnode.sysctl_func != NULL)
    853 		return (EPERM);
    854 
    855 	/*
    856 	 * only the kernel can create permanent entries, and only then
    857 	 * before the kernel is finished setting itself up
    858 	 */
    859 	if (l != NULL && (flags & ~SYSCTL_USERFLAGS))
    860 		return (EPERM);
    861 	if ((flags & CTLFLAG_PERMANENT) &
    862 	    (sysctl_root.sysctl_flags & CTLFLAG_PERMANENT))
    863 		return (EPERM);
    864 	if ((flags & (CTLFLAG_OWNDATA | CTLFLAG_IMMEDIATE)) ==
    865 	    (CTLFLAG_OWNDATA | CTLFLAG_IMMEDIATE))
    866 		return (EINVAL);
    867 	if ((flags & CTLFLAG_IMMEDIATE) &&
    868 	    type != CTLTYPE_INT && type != CTLTYPE_QUAD)
    869 		return (EINVAL);
    870 
    871 	/*
    872 	 * check size, or set it if unset and we can figure it out.
    873 	 * kernel created nodes are allowed to have a function instead
    874 	 * of a size (or a data pointer).
    875 	 */
    876 	switch (type) {
    877 	case CTLTYPE_NODE:
    878 		/*
    879 		 * only *i* can assert the size of a node
    880 		 */
    881 		if (flags & CTLFLAG_ALIAS) {
    882 			anum = nnode.sysctl_alias;
    883 			if (anum < 0)
    884 				return (EINVAL);
    885 			nnode.sysctl_alias = 0;
    886 		}
    887 		if (sz != 0 || nnode.sysctl_data != NULL)
    888 			return (EINVAL);
    889 		if (nnode.sysctl_csize != 0 ||
    890 		    nnode.sysctl_clen != 0 ||
    891 		    nnode.sysctl_child != 0)
    892 			return (EINVAL);
    893 		if (flags & CTLFLAG_OWNDATA)
    894 			return (EINVAL);
    895 		sz = sizeof(struct sysctlnode);
    896 		break;
    897 	case CTLTYPE_INT:
    898 		/*
    899 		 * since an int is an int, if the size is not given or
    900 		 * is wrong, we can "int-uit" it.
    901 		 */
    902 		if (sz != 0 && sz != sizeof(int))
    903 			return (EINVAL);
    904 		sz = sizeof(int);
    905 		break;
    906 	case CTLTYPE_STRING:
    907 		/*
    908 		 * strings are a little more tricky
    909 		 */
    910 		if (sz == 0) {
    911 			if (l == NULL) {
    912 				if (nnode.sysctl_func == NULL) {
    913 					if (nnode.sysctl_data == NULL)
    914 						return (EINVAL);
    915 					else
    916 						sz = strlen(nnode.sysctl_data) +
    917 						    1;
    918 				}
    919 			} else if (nnode.sysctl_data == NULL &&
    920 				 flags & CTLFLAG_OWNDATA) {
    921 				return (EINVAL);
    922 			} else {
    923 				char *vp, *e;
    924 				size_t s;
    925 
    926 				/*
    927 				 * we want a rough idea of what the
    928 				 * size is now
    929 				 */
    930 				vp = malloc(PAGE_SIZE, M_SYSCTLDATA,
    931 					     M_WAITOK|M_CANFAIL);
    932 				if (vp == NULL)
    933 					return (ENOMEM);
    934 				e = nnode.sysctl_data;
    935 				do {
    936 					error = copyinstr(e, vp, PAGE_SIZE, &s);
    937 					if (error) {
    938 						if (error != ENAMETOOLONG) {
    939 							free(vp, M_SYSCTLDATA);
    940 							return (error);
    941 						}
    942 						e += PAGE_SIZE;
    943 						if ((e - 32 * PAGE_SIZE) >
    944 						    (char*)nnode.sysctl_data) {
    945 							free(vp, M_SYSCTLDATA);
    946 							return (ERANGE);
    947 						}
    948 					}
    949 				} while (error != 0);
    950 				sz = s + (e - (char*)nnode.sysctl_data);
    951 				free(vp, M_SYSCTLDATA);
    952 			}
    953 		}
    954 		break;
    955 	case CTLTYPE_QUAD:
    956 		if (sz != 0 && sz != sizeof(u_quad_t))
    957 			return (EINVAL);
    958 		sz = sizeof(u_quad_t);
    959 		break;
    960 	case CTLTYPE_STRUCT:
    961 		if (sz == 0) {
    962 			if (l != NULL || nnode.sysctl_func == NULL)
    963 				return (EINVAL);
    964 			if (flags & CTLFLAG_OWNDATA)
    965 				return (EINVAL);
    966 		}
    967 		break;
    968 	default:
    969 		return (EINVAL);
    970 	}
    971 
    972 	/*
    973 	 * at this point, if sz is zero, we *must* have a
    974 	 * function to go with it and we can't own it.
    975 	 */
    976 
    977 	/*
    978 	 *  l  ptr own
    979 	 *  0   0   0  -> EINVAL (if no func)
    980 	 *  0   0   1  -> own
    981 	 *  0   1   0  -> kptr
    982 	 *  0   1   1  -> kptr
    983 	 *  1   0   0  -> EINVAL
    984 	 *  1   0   1  -> own
    985 	 *  1   1   0  -> kptr, no own (fault on lookup)
    986 	 *  1   1   1  -> uptr, own
    987 	 */
    988 	if (type != CTLTYPE_NODE) {
    989 		if (sz != 0) {
    990 			if (flags & CTLFLAG_OWNDATA) {
    991 				own = malloc(sz, M_SYSCTLDATA,
    992 					     M_WAITOK|M_CANFAIL);
    993 				if (own == NULL)
    994 					return ENOMEM;
    995 				if (nnode.sysctl_data == NULL)
    996 					memset(own, 0, sz);
    997 				else {
    998 					error = sysctl_copyin(l,
    999 					    nnode.sysctl_data, own, sz);
   1000 					if (error != 0) {
   1001 						free(own, M_SYSCTLDATA);
   1002 						return (error);
   1003 					}
   1004 				}
   1005 			} else if ((nnode.sysctl_data != NULL) &&
   1006 				 !(flags & CTLFLAG_IMMEDIATE)) {
   1007 #if NKSYMS > 0
   1008 				if (name[namelen - 1] == CTL_CREATESYM) {
   1009 					char symname[128]; /* XXX enough? */
   1010 					u_long symaddr;
   1011 					size_t symlen;
   1012 
   1013 					error = sysctl_copyinstr(l,
   1014 					    nnode.sysctl_data, symname,
   1015 					    sizeof(symname), &symlen);
   1016 					if (error)
   1017 						return (error);
   1018 					error = ksyms_getval(NULL, symname,
   1019 					    &symaddr, KSYMS_EXTERN);
   1020 					if (error)
   1021 						return (error); /* EINVAL? */
   1022 					nnode.sysctl_data = (void*)symaddr;
   1023 				}
   1024 #endif /* NKSYMS > 0 */
   1025 				/*
   1026 				 * Ideally, we'd like to verify here
   1027 				 * that this address is acceptable,
   1028 				 * but...
   1029 				 *
   1030 				 * - it might be valid now, only to
   1031 				 *   become invalid later
   1032 				 *
   1033 				 * - it might be invalid only for the
   1034 				 *   moment and valid later
   1035 				 *
   1036 				 * - or something else.
   1037 				 *
   1038 				 * Since we can't get a good answer,
   1039 				 * we'll just accept the address as
   1040 				 * given, and fault on individual
   1041 				 * lookups.
   1042 				 */
   1043 			}
   1044 		} else if (nnode.sysctl_func == NULL)
   1045 			return (EINVAL);
   1046 	}
   1047 
   1048 	/*
   1049 	 * a process can't assign a function to a node, and the kernel
   1050 	 * can't create a node that has no function or data.
   1051 	 * (XXX somewhat redundant check)
   1052 	 */
   1053 	if (l != NULL || nnode.sysctl_func == NULL) {
   1054 		if (type != CTLTYPE_NODE &&
   1055 		    nnode.sysctl_data == NULL &&
   1056 		    !(flags & CTLFLAG_IMMEDIATE) &&
   1057 		    own == NULL)
   1058 			return (EINVAL);
   1059 	}
   1060 
   1061 #ifdef SYSCTL_DISALLOW_KWRITE
   1062 	/*
   1063 	 * a process can't create a writable node unless it refers to
   1064 	 * new data.
   1065 	 */
   1066 	if (l != NULL && own == NULL && type != CTLTYPE_NODE &&
   1067 	    (flags & CTLFLAG_READWRITE) != CTLFLAG_READONLY &&
   1068 	    !(flags & CTLFLAG_IMMEDIATE))
   1069 		return (EPERM);
   1070 #endif /* SYSCTL_DISALLOW_KWRITE */
   1071 
   1072 	/*
   1073 	 * make sure there's somewhere to put the new stuff.
   1074 	 */
   1075 	if (pnode->sysctl_child == NULL) {
   1076 		if (flags & CTLFLAG_ANYNUMBER)
   1077 			error = sysctl_alloc(pnode, 1);
   1078 		else
   1079 			error = sysctl_alloc(pnode, 0);
   1080 		if (error) {
   1081 			if (own != NULL)
   1082 				free(own, M_SYSCTLDATA);
   1083 			return (error);
   1084 		}
   1085 	}
   1086 	node = pnode->sysctl_child;
   1087 
   1088 	/*
   1089 	 * no collisions, so pick a good dynamic number if we need to.
   1090 	 */
   1091 	if (nm == CTL_CREATE) {
   1092 		nm = ++sysctl_root.sysctl_num;
   1093 		for (ni = 0; ni < pnode->sysctl_clen; ni++) {
   1094 			if (nm == node[ni].sysctl_num) {
   1095 				nm++;
   1096 				ni = -1;
   1097 			} else if (nm > node[ni].sysctl_num)
   1098 				at = ni + 1;
   1099 		}
   1100 	}
   1101 
   1102 	/*
   1103 	 * oops...ran out of space
   1104 	 */
   1105 	if (pnode->sysctl_clen == pnode->sysctl_csize) {
   1106 		error = sysctl_realloc(pnode);
   1107 		if (error) {
   1108 			if (own != NULL)
   1109 				free(own, M_SYSCTLDATA);
   1110 			return (error);
   1111 		}
   1112 		node = pnode->sysctl_child;
   1113 	}
   1114 
   1115 	/*
   1116 	 * insert new node data
   1117 	 */
   1118 	if (at < pnode->sysctl_clen) {
   1119 		int t;
   1120 
   1121 		/*
   1122 		 * move the nodes that should come after the new one
   1123 		 */
   1124 		memmove(&node[at + 1], &node[at],
   1125 			(pnode->sysctl_clen - at) * sizeof(struct sysctlnode));
   1126 		memset(&node[at], 0, sizeof(struct sysctlnode));
   1127 		node[at].sysctl_parent = pnode;
   1128 		/*
   1129 		 * and...reparent any children of any moved nodes
   1130 		 */
   1131 		for (ni = at; ni <= pnode->sysctl_clen; ni++)
   1132 			if (SYSCTL_TYPE(node[ni].sysctl_flags) == CTLTYPE_NODE)
   1133 				for (t = 0; t < node[ni].sysctl_clen; t++)
   1134 					node[ni].sysctl_child[t].sysctl_parent =
   1135 						&node[ni];
   1136 	}
   1137 	node = &node[at];
   1138 	pnode->sysctl_clen++;
   1139 
   1140 	strlcpy(node->sysctl_name, nnode.sysctl_name,
   1141 		sizeof(node->sysctl_name));
   1142 	node->sysctl_num = nm;
   1143 	node->sysctl_size = sz;
   1144 	node->sysctl_flags = SYSCTL_VERSION|type|flags; /* XXX other trees */
   1145 	node->sysctl_csize = 0;
   1146 	node->sysctl_clen = 0;
   1147 	if (own) {
   1148 		node->sysctl_data = own;
   1149 		node->sysctl_flags |= CTLFLAG_OWNDATA;
   1150 	} else if (flags & CTLFLAG_ALIAS) {
   1151 		node->sysctl_alias = anum;
   1152 	} else if (flags & CTLFLAG_IMMEDIATE) {
   1153 		switch (type) {
   1154 		case CTLTYPE_INT:
   1155 			node->sysctl_idata = nnode.sysctl_idata;
   1156 			break;
   1157 		case CTLTYPE_QUAD:
   1158 			node->sysctl_qdata = nnode.sysctl_qdata;
   1159 			break;
   1160 		}
   1161 	} else {
   1162 		node->sysctl_data = nnode.sysctl_data;
   1163 		node->sysctl_flags &= ~CTLFLAG_OWNDATA;
   1164 	}
   1165         node->sysctl_func = nnode.sysctl_func;
   1166         node->sysctl_child = NULL;
   1167 	/* node->sysctl_parent should already be done */
   1168 
   1169 	/*
   1170 	 * update "version" on path to "root"
   1171 	 */
   1172 	for (; rnode->sysctl_parent != NULL; rnode = rnode->sysctl_parent)
   1173 		;
   1174 	pnode = node;
   1175 	for (nm = rnode->sysctl_ver + 1; pnode != NULL;
   1176 	     pnode = pnode->sysctl_parent)
   1177 		pnode->sysctl_ver = nm;
   1178 
   1179 	/* If this fails, the node is already added - the user won't know! */
   1180 	error = sysctl_cvt_out(l, v, node, oldp, *oldlenp, oldlenp);
   1181 
   1182 	return (error);
   1183 }
   1184 
   1185 /*
   1186  * ********************************************************************
   1187  * A wrapper around sysctl_create() that prints the thing we're trying
   1188  * to add.
   1189  * ********************************************************************
   1190  */
   1191 #ifdef SYSCTL_DEBUG_CREATE
   1192 int
   1193 sysctl_create(SYSCTLFN_ARGS)
   1194 {
   1195 	const struct sysctlnode *node;
   1196 	int k, rc, ni, nl = namelen + (name - oname);
   1197 
   1198 	node = newp;
   1199 
   1200 	printf("namelen %d (", nl);
   1201 	for (ni = 0; ni < nl - 1; ni++)
   1202 		printf(" %d", oname[ni]);
   1203 	printf(" %d )\t[%s]\tflags %08x (%08x %d %zu)\n",
   1204 	       k = node->sysctl_num,
   1205 	       node->sysctl_name,
   1206 	       node->sysctl_flags,
   1207 	       SYSCTL_FLAGS(node->sysctl_flags),
   1208 	       SYSCTL_TYPE(node->sysctl_flags),
   1209 	       node->sysctl_size);
   1210 
   1211 	node = rnode;
   1212 	rc = _sysctl_create(SYSCTLFN_CALL(rnode));
   1213 
   1214 	printf("sysctl_create(");
   1215 	for (ni = 0; ni < nl - 1; ni++)
   1216 		printf(" %d", oname[ni]);
   1217 	printf(" %d ) returned %d\n", k, rc);
   1218 
   1219 	return (rc);
   1220 }
   1221 #endif /* SYSCTL_DEBUG_CREATE */
   1222 
   1223 /*
   1224  * sysctl_destroy -- Removes a node (as described by newp) from the
   1225  * given tree, returning (if successful) a copy of the dead node in
   1226  * oldp.  Since we're removing stuff, there's not much to check.
   1227  */
   1228 int
   1229 sysctl_destroy(SYSCTLFN_ARGS)
   1230 {
   1231 	struct sysctlnode *node, *pnode, onode, nnode;
   1232 	int ni, error, v;
   1233 
   1234 	if (SYSCTL_VERS(rnode->sysctl_flags) != SYSCTL_VERSION) {
   1235 		printf("sysctl_destroy: rnode %p wrong version\n", rnode);
   1236 		return (EINVAL);
   1237 	}
   1238 
   1239 	error = 0;
   1240 
   1241 	if (namelen != 1 || name[namelen - 1] != CTL_DESTROY)
   1242 		return (EINVAL);
   1243 
   1244 	/*
   1245 	 * processes can only destroy nodes at securelevel 0, must be
   1246 	 * root, and can't remove nodes from a parent that's not
   1247 	 * writeable
   1248 	 */
   1249 	if (l != NULL) {
   1250 #ifndef SYSCTL_DISALLOW_CREATE
   1251 		if (securelevel > 0)
   1252 			return (EPERM);
   1253 		error = kauth_authorize_generic(l->l_cred,
   1254 		    KAUTH_GENERIC_ISSUSER, &l->l_acflag);
   1255 		if (error)
   1256 			return (error);
   1257 		if (!(rnode->sysctl_flags & CTLFLAG_READWRITE))
   1258 #endif /* SYSCTL_DISALLOW_CREATE */
   1259 			return (EPERM);
   1260 	}
   1261 
   1262 	/*
   1263 	 * nothing can remove a node if:
   1264 	 * the node is permanent (checked later) or
   1265 	 * the tree itself is not writeable or
   1266 	 * the entire sysctl system is not writeable
   1267 	 *
   1268 	 * note that we ignore whether setup is complete or not,
   1269 	 * because these rules always apply.
   1270 	 */
   1271 	if (!(sysctl_rootof(rnode)->sysctl_flags & CTLFLAG_READWRITE) ||
   1272 	    !(sysctl_root.sysctl_flags & CTLFLAG_READWRITE))
   1273 		return (EPERM);
   1274 
   1275 	if (newp == NULL)
   1276 		return (EINVAL);
   1277 	error = sysctl_cvt_in(l, &v, newp, newlen, &nnode);
   1278 	if (error)
   1279 		return (error);
   1280 	memset(&onode, 0, sizeof(struct sysctlnode));
   1281 
   1282 	node = rnode->sysctl_child;
   1283 	for (ni = 0; ni < rnode->sysctl_clen; ni++) {
   1284 		if (nnode.sysctl_num == node[ni].sysctl_num) {
   1285 			/*
   1286 			 * if name specified, must match
   1287 			 */
   1288 			if (nnode.sysctl_name[0] != '\0' &&
   1289 			    strcmp(nnode.sysctl_name, node[ni].sysctl_name))
   1290 				continue;
   1291 			/*
   1292 			 * if version specified, must match
   1293 			 */
   1294 			if (nnode.sysctl_ver != 0 &&
   1295 			    nnode.sysctl_ver != node[ni].sysctl_ver)
   1296 				continue;
   1297 			/*
   1298 			 * this must be the one
   1299 			 */
   1300 			break;
   1301 		}
   1302 	}
   1303 	if (ni == rnode->sysctl_clen)
   1304 		return (ENOENT);
   1305 	node = &node[ni];
   1306 	pnode = node->sysctl_parent;
   1307 
   1308 	/*
   1309 	 * if the kernel says permanent, it is, so there.  nyah.
   1310 	 */
   1311 	if (SYSCTL_FLAGS(node->sysctl_flags) & CTLFLAG_PERMANENT)
   1312 		return (EPERM);
   1313 
   1314 	/*
   1315 	 * can't delete non-empty nodes
   1316 	 */
   1317 	if (SYSCTL_TYPE(node->sysctl_flags) == CTLTYPE_NODE &&
   1318 	    node->sysctl_clen != 0)
   1319 		return (ENOTEMPTY);
   1320 
   1321 	/*
   1322 	 * if the node "owns" data, release it now
   1323 	 */
   1324 	if (node->sysctl_flags & CTLFLAG_OWNDATA) {
   1325 		if (node->sysctl_data != NULL)
   1326 			free(node->sysctl_data, M_SYSCTLDATA);
   1327 		node->sysctl_data = NULL;
   1328 	}
   1329 	if (node->sysctl_flags & CTLFLAG_OWNDESC) {
   1330 		if (node->sysctl_desc != NULL)
   1331 			/*XXXUNCONST*/
   1332 			free(__UNCONST(node->sysctl_desc), M_SYSCTLDATA);
   1333 		node->sysctl_desc = NULL;
   1334 	}
   1335 
   1336 	/*
   1337 	 * if the node to be removed is not the last one on the list,
   1338 	 * move the remaining nodes up, and reparent any grandchildren
   1339 	 */
   1340 	onode = *node;
   1341 	if (ni < pnode->sysctl_clen - 1) {
   1342 		int t;
   1343 
   1344 		memmove(&pnode->sysctl_child[ni], &pnode->sysctl_child[ni + 1],
   1345 			(pnode->sysctl_clen - ni - 1) *
   1346 			sizeof(struct sysctlnode));
   1347 		for (; ni < pnode->sysctl_clen - 1; ni++)
   1348 			if (SYSCTL_TYPE(pnode->sysctl_child[ni].sysctl_flags) ==
   1349 			    CTLTYPE_NODE)
   1350 				for (t = 0;
   1351 				     t < pnode->sysctl_child[ni].sysctl_clen;
   1352 				     t++)
   1353 					pnode->sysctl_child[ni].sysctl_child[t].
   1354 						sysctl_parent =
   1355 						&pnode->sysctl_child[ni];
   1356 		ni = pnode->sysctl_clen - 1;
   1357 		node = &pnode->sysctl_child[ni];
   1358 	}
   1359 
   1360 	/*
   1361 	 * reset the space we just vacated
   1362 	 */
   1363 	memset(node, 0, sizeof(struct sysctlnode));
   1364 	node->sysctl_parent = pnode;
   1365 	pnode->sysctl_clen--;
   1366 
   1367 	/*
   1368 	 * if this parent just lost its last child, nuke the creche
   1369 	 */
   1370 	if (pnode->sysctl_clen == 0) {
   1371 		free(pnode->sysctl_child, M_SYSCTLNODE);
   1372 		pnode->sysctl_csize = 0;
   1373 		pnode->sysctl_child = NULL;
   1374 	}
   1375 
   1376 	/*
   1377 	 * update "version" on path to "root"
   1378 	 */
   1379         for (; rnode->sysctl_parent != NULL; rnode = rnode->sysctl_parent)
   1380                 ;
   1381 	for (ni = rnode->sysctl_ver + 1; pnode != NULL;
   1382 	     pnode = pnode->sysctl_parent)
   1383 		pnode->sysctl_ver = ni;
   1384 
   1385 	error = sysctl_cvt_out(l, v, &onode, oldp, *oldlenp, oldlenp);
   1386 
   1387 	return (error);
   1388 }
   1389 
   1390 /*
   1391  * sysctl_lookup -- Handles copyin/copyout of new and old values.
   1392  * Partial reads are globally allowed.  Only root can write to things
   1393  * unless the node says otherwise.
   1394  */
   1395 int
   1396 sysctl_lookup(SYSCTLFN_ARGS)
   1397 {
   1398 	int error, rw;
   1399 	size_t sz, len;
   1400 	void *d;
   1401 
   1402 	if (SYSCTL_VERS(rnode->sysctl_flags) != SYSCTL_VERSION) {
   1403 		printf("sysctl_lookup: rnode %p wrong version\n", rnode);
   1404 		return (EINVAL);
   1405 	}
   1406 
   1407 	error = 0;
   1408 
   1409 	/*
   1410 	 * you can't "look up" a node.  you can "query" it, but you
   1411 	 * can't "look it up".
   1412 	 */
   1413 	if (SYSCTL_TYPE(rnode->sysctl_flags) == CTLTYPE_NODE || namelen != 0)
   1414 		return (EINVAL);
   1415 
   1416 	/*
   1417 	 * some nodes are private, so only root can look into them.
   1418 	 */
   1419 	if (l != NULL && (rnode->sysctl_flags & CTLFLAG_PRIVATE) &&
   1420 	    (error = kauth_authorize_generic(l->l_cred,
   1421 	    KAUTH_GENERIC_ISSUSER, &l->l_acflag)) != 0)
   1422 		return (error);
   1423 
   1424 	/*
   1425 	 * if a node wants to be writable according to different rules
   1426 	 * other than "only root can write to stuff unless a flag is
   1427 	 * set", then it needs its own function which should have been
   1428 	 * called and not us.
   1429 	 */
   1430 	if (l != NULL && newp != NULL &&
   1431 	    !(rnode->sysctl_flags & CTLFLAG_ANYWRITE) &&
   1432 	    (error = kauth_authorize_generic(l->l_cred,
   1433 	    KAUTH_GENERIC_ISSUSER, &l->l_acflag)) != 0)
   1434 		return (error);
   1435 
   1436 	/*
   1437 	 * is this node supposedly writable?
   1438 	 */
   1439 	rw = (rnode->sysctl_flags & CTLFLAG_READWRITE) ? 1 : 0;
   1440 
   1441 	/*
   1442 	 * it appears not to be writable at this time, so if someone
   1443 	 * tried to write to it, we must tell them to go away
   1444 	 */
   1445 	if (!rw && newp != NULL)
   1446 		return (EPERM);
   1447 
   1448 	/*
   1449 	 * step one, copy out the stuff we have presently
   1450 	 */
   1451 	if (rnode->sysctl_flags & CTLFLAG_IMMEDIATE) {
   1452 		/*
   1453 		 * note that we discard const here because we are
   1454 		 * modifying the contents of the node (which is okay
   1455 		 * because it's ours)
   1456 		 */
   1457 		switch (SYSCTL_TYPE(rnode->sysctl_flags)) {
   1458 		case CTLTYPE_INT:
   1459 			d = __UNCONST(&rnode->sysctl_idata);
   1460 			break;
   1461 		case CTLTYPE_QUAD:
   1462 			d = __UNCONST(&rnode->sysctl_qdata);
   1463 			break;
   1464 		default:
   1465 			return (EINVAL);
   1466 		}
   1467 	} else
   1468 		d = rnode->sysctl_data;
   1469 	if (SYSCTL_TYPE(rnode->sysctl_flags) == CTLTYPE_STRING)
   1470 		sz = strlen(d) + 1; /* XXX@@@ possible fault here */
   1471 	else
   1472 		sz = rnode->sysctl_size;
   1473 	if (oldp != NULL)
   1474 		error = sysctl_copyout(l, d, oldp, MIN(sz, *oldlenp));
   1475 	if (error)
   1476 		return (error);
   1477 	*oldlenp = sz;
   1478 
   1479 	/*
   1480 	 * are we done?
   1481 	 */
   1482 	if (newp == NULL || newlen == 0)
   1483 		return (0);
   1484 
   1485 	/*
   1486 	 * hmm...not done.  must now "copy in" new value.  re-adjust
   1487 	 * sz to maximum value (strings are "weird").
   1488 	 */
   1489 	sz = rnode->sysctl_size;
   1490 	switch (SYSCTL_TYPE(rnode->sysctl_flags)) {
   1491 	case CTLTYPE_INT:
   1492 	case CTLTYPE_QUAD:
   1493 	case CTLTYPE_STRUCT:
   1494 		/*
   1495 		 * these data must be *exactly* the same size coming
   1496 		 * in.
   1497 		 */
   1498 		if (newlen != sz)
   1499 			return (EINVAL);
   1500 		error = sysctl_copyin(l, newp, d, sz);
   1501 		break;
   1502 	case CTLTYPE_STRING: {
   1503 		/*
   1504 		 * strings, on the other hand, can be shorter, and we
   1505 		 * let userland be sloppy about the trailing nul.
   1506 		 */
   1507 		char *newbuf;
   1508 
   1509 		/*
   1510 		 * too much new string?
   1511 		 */
   1512 		if (newlen > sz)
   1513 			return (EINVAL);
   1514 
   1515 		/*
   1516 		 * temporary copy of new inbound string
   1517 		 */
   1518 		len = MIN(sz, newlen);
   1519 		newbuf = malloc(len, M_SYSCTLDATA, M_WAITOK|M_CANFAIL);
   1520 		if (newbuf == NULL)
   1521 			return (ENOMEM);
   1522 		error = sysctl_copyin(l, newp, newbuf, len);
   1523 		if (error) {
   1524 			free(newbuf, M_SYSCTLDATA);
   1525 			return (error);
   1526 		}
   1527 
   1528 		/*
   1529 		 * did they null terminate it, or do we have space
   1530 		 * left to do it ourselves?
   1531 		 */
   1532 		if (newbuf[len - 1] != '\0' && len == sz) {
   1533 			free(newbuf, M_SYSCTLDATA);
   1534 			return (EINVAL);
   1535 		}
   1536 
   1537 		/*
   1538 		 * looks good, so pop it into place and zero the rest.
   1539 		 */
   1540 		if (len > 0)
   1541 			memcpy(d, newbuf, len);
   1542 		if (sz != len)
   1543 			memset((char*)d + len, 0, sz - len);
   1544 		free(newbuf, M_SYSCTLDATA);
   1545 		break;
   1546 	}
   1547 	default:
   1548 		return (EINVAL);
   1549 	}
   1550 
   1551 	return (error);
   1552 }
   1553 
   1554 /*
   1555  * sysctl_mmap -- Dispatches sysctl mmap requests to those nodes that
   1556  * purport to handle it.  This interface isn't fully fleshed out yet,
   1557  * unfortunately.
   1558  */
   1559 static int
   1560 sysctl_mmap(SYSCTLFN_ARGS)
   1561 {
   1562 	const struct sysctlnode *node;
   1563 	struct sysctlnode nnode;
   1564 	int error;
   1565 
   1566 	if (SYSCTL_VERS(rnode->sysctl_flags) != SYSCTL_VERSION) {
   1567 		printf("sysctl_mmap: rnode %p wrong version\n", rnode);
   1568 		return (EINVAL);
   1569 	}
   1570 
   1571 	/*
   1572 	 * let's just pretend that didn't happen, m'kay?
   1573 	 */
   1574 	if (l == NULL)
   1575 		return (EPERM);
   1576 
   1577 	/*
   1578 	 * is this a sysctlnode description of an mmap request?
   1579 	 */
   1580 	if (newp == NULL || newlen != sizeof(struct sysctlnode))
   1581 		return (EINVAL);
   1582 	error = sysctl_copyin(l, newp, &nnode, sizeof(nnode));
   1583 	if (error)
   1584 		return (error);
   1585 
   1586 	/*
   1587 	 * does the node they asked for exist?
   1588 	 */
   1589 	if (namelen != 1)
   1590 		return (EOPNOTSUPP);
   1591 	node = rnode;
   1592         error = sysctl_locate(l, &nnode.sysctl_num, 1, &node, NULL);
   1593 	if (error)
   1594 		return (error);
   1595 
   1596 	/*
   1597 	 * does this node that we have found purport to handle mmap?
   1598 	 */
   1599 	if (node->sysctl_func == NULL ||
   1600 	    !(node->sysctl_flags & CTLFLAG_MMAP))
   1601 		return (EOPNOTSUPP);
   1602 
   1603 	/*
   1604 	 * well...okay, they asked for it.
   1605 	 */
   1606 	return ((*node->sysctl_func)(SYSCTLFN_CALL(node)));
   1607 }
   1608 
   1609 int
   1610 sysctl_describe(SYSCTLFN_ARGS)
   1611 {
   1612 	struct sysctldesc *d;
   1613 	void *bf;
   1614 	size_t sz, left, tot;
   1615 	int i, error, v = -1;
   1616 	struct sysctlnode *node;
   1617 	struct sysctlnode dnode;
   1618 
   1619 	if (SYSCTL_VERS(rnode->sysctl_flags) != SYSCTL_VERSION) {
   1620 		printf("sysctl_query: rnode %p wrong version\n", rnode);
   1621 		return (EINVAL);
   1622 	}
   1623 
   1624 	if (SYSCTL_TYPE(rnode->sysctl_flags) != CTLTYPE_NODE)
   1625 		return (ENOTDIR);
   1626 	if (namelen != 1 || name[0] != CTL_DESCRIBE)
   1627 		return (EINVAL);
   1628 
   1629 	/*
   1630 	 * get ready...
   1631 	 */
   1632 	error = 0;
   1633 	d = bf = malloc(MAXDESCLEN, M_TEMP, M_WAITOK|M_CANFAIL);
   1634 	if (bf == NULL)
   1635 		return ENOMEM;
   1636 	tot = 0;
   1637 	node = rnode->sysctl_child;
   1638 	left = *oldlenp;
   1639 
   1640 	/*
   1641 	 * no request -> all descriptions at this level
   1642 	 * request with desc unset -> just this node
   1643 	 * request with desc set -> set descr for this node
   1644 	 */
   1645 	if (newp != NULL) {
   1646 		error = sysctl_cvt_in(l, &v, newp, newlen, &dnode);
   1647 		if (error)
   1648 			goto out;
   1649 		if (dnode.sysctl_desc != NULL) {
   1650 			/*
   1651 			 * processes cannot set descriptions above
   1652 			 * securelevel 0.  and must be root.  blah
   1653 			 * blah blah.  a couple more checks are made
   1654 			 * once we find the node we want.
   1655 			 */
   1656 			if (l != NULL) {
   1657 #ifndef SYSCTL_DISALLOW_CREATE
   1658 				if (securelevel > 0) {
   1659 					error = EPERM;
   1660 					goto out;
   1661 				}
   1662 				error = kauth_authorize_generic(l->l_cred,
   1663 				    KAUTH_GENERIC_ISSUSER, &l->l_acflag);
   1664 				if (error)
   1665 					goto out;
   1666 #else /* SYSCTL_DISALLOW_CREATE */
   1667 				error = EPERM;
   1668 				goto out;
   1669 #endif /* SYSCTL_DISALLOW_CREATE */
   1670 			}
   1671 
   1672 			/*
   1673 			 * find node and try to set the description on it
   1674 			 */
   1675 			for (i = 0; i < rnode->sysctl_clen; i++)
   1676 				if (node[i].sysctl_num == dnode.sysctl_num)
   1677 					break;
   1678 			if (i == rnode->sysctl_clen) {
   1679 				error = ENOENT;
   1680 				goto out;
   1681 			}
   1682 			node = &node[i];
   1683 
   1684 			/*
   1685 			 * did the caller specify a node version?
   1686 			 */
   1687 			if (dnode.sysctl_ver != 0 &&
   1688 			    dnode.sysctl_ver != node->sysctl_ver) {
   1689 				error = EINVAL;
   1690 				goto out;
   1691 			}
   1692 
   1693 			/*
   1694 			 * okay...some rules:
   1695 			 * (1) if setup is done and the tree is
   1696 			 *     read-only or the whole system is
   1697 			 *     read-only
   1698 			 * (2) no one can set a description on a
   1699 			 *     permanent node (it must be set when
   1700 			 *     using createv)
   1701 			 * (3) processes cannot *change* a description
   1702 			 * (4) processes *can*, however, set a
   1703 			 *     description on a read-only node so that
   1704 			 *     one can be created and then described
   1705 			 *     in two steps
   1706 			 * anything else come to mind?
   1707 			 */
   1708 			if ((sysctl_root.sysctl_flags & CTLFLAG_PERMANENT) &&
   1709 			    (!(sysctl_rootof(node)->sysctl_flags &
   1710 			       CTLFLAG_READWRITE) ||
   1711 			     !(sysctl_root.sysctl_flags & CTLFLAG_READWRITE))) {
   1712 				error = EPERM;
   1713 				goto out;
   1714 			}
   1715 			if (node->sysctl_flags & CTLFLAG_PERMANENT) {
   1716 				error = EPERM;
   1717 				goto out;
   1718 			}
   1719 			if (l != NULL && node->sysctl_desc != NULL) {
   1720 				error = EPERM;
   1721 				goto out;
   1722 			}
   1723 
   1724 			/*
   1725 			 * right, let's go ahead.  the first step is
   1726 			 * making the description into something the
   1727 			 * node can "own", if need be.
   1728 			 */
   1729 			if (l != NULL ||
   1730 			    dnode.sysctl_flags & CTLFLAG_OWNDESC) {
   1731 				char *nd, *k;
   1732 
   1733 				k = malloc(MAXDESCLEN, M_TEMP,
   1734 				    M_WAITOK|M_CANFAIL);
   1735 				if (k == NULL) {
   1736 					error = ENOMEM;
   1737 					goto out;
   1738 				}
   1739 				error = sysctl_copyinstr(l, dnode.sysctl_desc,
   1740 							 k, MAXDESCLEN, &sz);
   1741 				if (error) {
   1742 					free(k, M_TEMP);
   1743 					goto out;
   1744 				}
   1745 				nd = malloc(sz, M_SYSCTLDATA,
   1746 					    M_WAITOK|M_CANFAIL);
   1747 				if (nd == NULL) {
   1748 					free(k, M_TEMP);
   1749 					error = ENOMEM;
   1750 					goto out;
   1751 				}
   1752 				memcpy(nd, k, sz);
   1753 				dnode.sysctl_flags |= CTLFLAG_OWNDESC;
   1754 				dnode.sysctl_desc = nd;
   1755 				free(k, M_TEMP);
   1756 			}
   1757 
   1758 			/*
   1759 			 * now "release" the old description and
   1760 			 * attach the new one.  ta-da.
   1761 			 */
   1762 			if ((node->sysctl_flags & CTLFLAG_OWNDESC) &&
   1763 			    node->sysctl_desc != NULL)
   1764 				/*XXXUNCONST*/
   1765 				free(__UNCONST(node->sysctl_desc), M_SYSCTLDATA);
   1766 			node->sysctl_desc = dnode.sysctl_desc;
   1767 			node->sysctl_flags |=
   1768 				(dnode.sysctl_flags & CTLFLAG_OWNDESC);
   1769 
   1770 			/*
   1771 			 * now we "fall out" and into the loop which
   1772 			 * will copy the new description back out for
   1773 			 * those interested parties
   1774 			 */
   1775 		}
   1776 	}
   1777 
   1778 	/*
   1779 	 * scan for one description or just retrieve all descriptions
   1780 	 */
   1781 	for (i = 0; i < rnode->sysctl_clen; i++) {
   1782 		/*
   1783 		 * did they ask for the description of only one node?
   1784 		 */
   1785 		if (v != -1 && node[i].sysctl_num != dnode.sysctl_num)
   1786 			continue;
   1787 
   1788 		/*
   1789 		 * don't describe "private" nodes to non-suser users
   1790 		 */
   1791 		if ((node[i].sysctl_flags & CTLFLAG_PRIVATE) && (l != NULL) &&
   1792 		    !(kauth_authorize_generic(l->l_cred,
   1793 		    KAUTH_GENERIC_ISSUSER, &l->l_acflag)))
   1794 			continue;
   1795 
   1796 		/*
   1797 		 * is this description "valid"?
   1798 		 */
   1799 		memset(bf, 0, MAXDESCLEN);
   1800 		if (node[i].sysctl_desc == NULL)
   1801 			sz = 1;
   1802 		else if (copystr(node[i].sysctl_desc, &d->descr_str[0],
   1803 				 MAXDESCLEN - sizeof(*d), &sz) != 0) {
   1804 			/*
   1805 			 * erase possible partial description
   1806 			 */
   1807 			memset(bf, 0, MAXDESCLEN);
   1808 			sz = 1;
   1809 		}
   1810 
   1811 		/*
   1812 		 * we've got it, stuff it into the caller's buffer
   1813 		 */
   1814 		d->descr_num = node[i].sysctl_num;
   1815 		d->descr_ver = node[i].sysctl_ver;
   1816 		d->descr_len = sz; /* includes trailing nul */
   1817 		sz = (caddr_t)NEXT_DESCR(d) - (caddr_t)d;
   1818 		if (oldp != NULL && left >= sz) {
   1819 			error = sysctl_copyout(l, d, oldp, sz);
   1820 			if (error)
   1821 				goto out;
   1822 			left -= sz;
   1823 			oldp = (void *)__sysc_desc_adv(oldp, d->descr_len);
   1824 		}
   1825 		tot += sz;
   1826 
   1827 		/*
   1828 		 * if we get this far with v not "unset", they asked
   1829 		 * for a specific node and we found it
   1830 		 */
   1831 		if (v != -1)
   1832 			break;
   1833 	}
   1834 
   1835 	/*
   1836 	 * did we find it after all?
   1837 	 */
   1838 	if (v != -1 && tot == 0)
   1839 		error = ENOENT;
   1840 	else
   1841 		*oldlenp = tot;
   1842 
   1843 out:
   1844 	free(bf, M_TEMP);
   1845 	return (error);
   1846 }
   1847 
   1848 /*
   1849  * ********************************************************************
   1850  * Section 3: Create and destroy from inside the kernel
   1851  * ********************************************************************
   1852  * sysctl_createv() and sysctl_destroyv() are simpler-to-use
   1853  * interfaces for the kernel to fling new entries into the mib and rip
   1854  * them out later.  In the case of sysctl_createv(), the returned copy
   1855  * of the node (see sysctl_create()) will be translated back into a
   1856  * pointer to the actual node.
   1857  *
   1858  * Note that sysctl_createv() will return 0 if the create request
   1859  * matches an existing node (ala mkdir -p), and that sysctl_destroyv()
   1860  * will return 0 if the node to be destroyed already does not exist
   1861  * (aka rm -f) or if it is a parent of other nodes.
   1862  *
   1863  * This allows two (or more) different subsystems to assert sub-tree
   1864  * existence before populating their own nodes, and to remove their
   1865  * own nodes without orphaning the others when they are done.
   1866  * ********************************************************************
   1867  */
   1868 int
   1869 sysctl_createv(struct sysctllog **log, int cflags,
   1870 	       const struct sysctlnode **rnode, const struct sysctlnode **cnode,
   1871 	       int flags, int type, const char *namep, const char *descr,
   1872 	       sysctlfn func, u_quad_t qv, void *newp, size_t newlen,
   1873 	       ...)
   1874 {
   1875 	va_list ap;
   1876 	int error, ni, namelen, name[CTL_MAXNAME];
   1877 	const struct sysctlnode *root, *pnode;
   1878 	struct sysctlnode nnode, onode, *dnode;
   1879 	size_t sz;
   1880 
   1881 	/*
   1882 	 * where are we putting this?
   1883 	 */
   1884 	if (rnode != NULL && *rnode == NULL) {
   1885 		printf("sysctl_createv: rnode NULL\n");
   1886 		return (EINVAL);
   1887 	}
   1888 	root = rnode ? *rnode : NULL;
   1889 	if (cnode != NULL)
   1890 		*cnode = NULL;
   1891 	if (cflags != 0)
   1892 		return (EINVAL);
   1893 
   1894 	/*
   1895 	 * what is it?
   1896 	 */
   1897 	flags = SYSCTL_VERSION|SYSCTL_TYPE(type)|SYSCTL_FLAGS(flags);
   1898 	if (log != NULL)
   1899 		flags &= ~CTLFLAG_PERMANENT;
   1900 
   1901 	/*
   1902 	 * where do we put it?
   1903 	 */
   1904 	va_start(ap, newlen);
   1905 	namelen = 0;
   1906 	ni = -1;
   1907 	do {
   1908 		if (++ni == CTL_MAXNAME)
   1909 			return (ENAMETOOLONG);
   1910 		name[ni] = va_arg(ap, int);
   1911 		/*
   1912 		 * sorry, this is not supported from here
   1913 		 */
   1914 		if (name[ni] == CTL_CREATESYM)
   1915 			return (EINVAL);
   1916 	} while (name[ni] != CTL_EOL && name[ni] != CTL_CREATE);
   1917 	namelen = ni + (name[ni] == CTL_CREATE ? 1 : 0);
   1918 	va_end(ap);
   1919 
   1920 	/*
   1921 	 * what's it called
   1922 	 */
   1923 	if (strlcpy(nnode.sysctl_name, namep, sizeof(nnode.sysctl_name)) >=
   1924 	    sizeof(nnode.sysctl_name))
   1925 		return (ENAMETOOLONG);
   1926 
   1927 	/*
   1928 	 * cons up the description of the new node
   1929 	 */
   1930 	nnode.sysctl_num = name[namelen - 1];
   1931 	name[namelen - 1] = CTL_CREATE;
   1932 	nnode.sysctl_size = newlen;
   1933 	nnode.sysctl_flags = flags;
   1934 	if (type == CTLTYPE_NODE) {
   1935 		nnode.sysctl_csize = 0;
   1936 		nnode.sysctl_clen = 0;
   1937 		nnode.sysctl_child = NULL;
   1938 		if (flags & CTLFLAG_ALIAS)
   1939 			nnode.sysctl_alias = qv;
   1940 	} else if (flags & CTLFLAG_IMMEDIATE) {
   1941 		switch (type) {
   1942 		case CTLTYPE_INT:
   1943 			nnode.sysctl_idata = qv;
   1944 			break;
   1945 		case CTLTYPE_QUAD:
   1946 			nnode.sysctl_qdata = qv;
   1947 			break;
   1948 		default:
   1949 			return (EINVAL);
   1950 		}
   1951 	} else {
   1952 		nnode.sysctl_data = newp;
   1953 	}
   1954 	nnode.sysctl_func = func;
   1955 	nnode.sysctl_parent = NULL;
   1956 	nnode.sysctl_ver = 0;
   1957 
   1958 	/*
   1959 	 * initialize lock state -- we need locks if the main tree has
   1960 	 * been marked as complete, but since we could be called from
   1961 	 * either there, or from a device driver (say, at device
   1962 	 * insertion), or from an lkm (at lkm load time, say), we
   1963 	 * don't really want to "wait"...
   1964 	 */
   1965 	error = sysctl_lock(NULL, NULL, 0);
   1966 	if (error)
   1967 		return (error);
   1968 
   1969 	/*
   1970 	 * locate the prospective parent of the new node, and if we
   1971 	 * find it, add the new node.
   1972 	 */
   1973 	sz = sizeof(onode);
   1974 	pnode = root;
   1975 	error = sysctl_locate(NULL, &name[0], namelen - 1, &pnode, &ni);
   1976 	if (error) {
   1977 		printf("sysctl_createv: sysctl_locate(%s) returned %d\n",
   1978 		       nnode.sysctl_name, error);
   1979 		sysctl_unlock(NULL);
   1980 		return (error);
   1981 	}
   1982 	error = sysctl_create(&name[ni], namelen - ni, &onode, &sz,
   1983 			      &nnode, sizeof(nnode), &name[0], NULL,
   1984 			      pnode);
   1985 
   1986 	/*
   1987 	 * unfortunately the node we wanted to create is already
   1988 	 * there.  if the node that's already there is a reasonable
   1989 	 * facsimile of the node we wanted to create, just pretend
   1990 	 * (for the caller's benefit) that we managed to create the
   1991 	 * node they wanted.
   1992 	 */
   1993 	if (error == EEXIST) {
   1994 		/* name is the same as requested... */
   1995 		if (strcmp(nnode.sysctl_name, onode.sysctl_name) == 0 &&
   1996 		    /* they want the same function... */
   1997 		    nnode.sysctl_func == onode.sysctl_func &&
   1998 		    /* number is the same as requested, or... */
   1999 		    (nnode.sysctl_num == onode.sysctl_num ||
   2000 		     /* they didn't pick a number... */
   2001 		     nnode.sysctl_num == CTL_CREATE)) {
   2002 			/*
   2003 			 * collision here from trying to create
   2004 			 * something that already existed; let's give
   2005 			 * our customers a hand and tell them they got
   2006 			 * what they wanted.
   2007 			 */
   2008 #ifdef SYSCTL_DEBUG_CREATE
   2009 			printf("cleared\n");
   2010 #endif /* SYSCTL_DEBUG_CREATE */
   2011 			error = 0;
   2012 		}
   2013 	}
   2014 
   2015 	if (error == 0 &&
   2016 	    (cnode != NULL || log != NULL || descr != NULL)) {
   2017 		/*
   2018 		 * sysctl_create() gave us back a copy of the node,
   2019 		 * but we need to know where it actually is...
   2020 		 */
   2021 		pnode = root;
   2022 		error = sysctl_locate(NULL, &name[0], namelen - 1, &pnode, &ni);
   2023 
   2024 		/*
   2025 		 * manual scan of last layer so that aliased nodes
   2026 		 * aren't followed.
   2027 		 */
   2028 		if (error == 0) {
   2029 			for (ni = 0; ni < pnode->sysctl_clen; ni++)
   2030 				if (pnode->sysctl_child[ni].sysctl_num ==
   2031 				    onode.sysctl_num)
   2032 					break;
   2033 			if (ni < pnode->sysctl_clen)
   2034 				pnode = &pnode->sysctl_child[ni];
   2035 			else
   2036 				error = ENOENT;
   2037 		}
   2038 
   2039 		/*
   2040 		 * not expecting an error here, but...
   2041 		 */
   2042 		if (error == 0) {
   2043 			if (log != NULL)
   2044 				sysctl_log_add(log, pnode);
   2045 			if (cnode != NULL)
   2046 				*cnode = pnode;
   2047 			if (descr != NULL) {
   2048 				/*
   2049 				 * allow first caller to *set* a
   2050 				 * description actually to set it
   2051 				 *
   2052 				 * discard const here so we can attach
   2053 				 * the description
   2054 				 */
   2055 				dnode = __UNCONST(pnode);
   2056 				if (pnode->sysctl_desc != NULL)
   2057 					/* skip it...we've got one */;
   2058 				else if (flags & CTLFLAG_OWNDESC) {
   2059 					size_t l = strlen(descr) + 1;
   2060 					char *d = malloc(l, M_SYSCTLDATA,
   2061 							 M_WAITOK|M_CANFAIL);
   2062 					if (d != NULL) {
   2063 						memcpy(d, descr, l);
   2064 						dnode->sysctl_desc = d;
   2065 						dnode->sysctl_flags |=
   2066 						    CTLFLAG_OWNDESC;
   2067 					}
   2068 				} else
   2069 					dnode->sysctl_desc = descr;
   2070 			}
   2071 		} else {
   2072 			printf("sysctl_create succeeded but node not found?!\n");
   2073 			/*
   2074 			 *  confusing, but the create said it
   2075 			 * succeeded, so...
   2076 			 */
   2077 			error = 0;
   2078 		}
   2079 	}
   2080 
   2081 	/*
   2082 	 * now it should be safe to release the lock state.  note that
   2083 	 * the pointer to the newly created node being passed back may
   2084 	 * not be "good" for very long.
   2085 	 */
   2086 	sysctl_unlock(NULL);
   2087 
   2088 	if (error != 0) {
   2089 		printf("sysctl_createv: sysctl_create(%s) returned %d\n",
   2090 		       nnode.sysctl_name, error);
   2091 #if 0
   2092 		if (error != ENOENT)
   2093 			sysctl_dump(&onode);
   2094 #endif
   2095 	}
   2096 
   2097 	return (error);
   2098 }
   2099 
   2100 int
   2101 sysctl_destroyv(struct sysctlnode *rnode, ...)
   2102 {
   2103 	va_list ap;
   2104 	int error, name[CTL_MAXNAME], namelen, ni;
   2105 	const struct sysctlnode *pnode, *node;
   2106 	struct sysctlnode dnode, *onode;
   2107 	size_t sz;
   2108 
   2109 	va_start(ap, rnode);
   2110 	namelen = 0;
   2111 	ni = 0;
   2112 	do {
   2113 		if (ni == CTL_MAXNAME)
   2114 			return (ENAMETOOLONG);
   2115 		name[ni] = va_arg(ap, int);
   2116 	} while (name[ni++] != CTL_EOL);
   2117 	namelen = ni - 1;
   2118 	va_end(ap);
   2119 
   2120 	/*
   2121 	 * i can't imagine why we'd be destroying a node when the tree
   2122 	 * wasn't complete, but who knows?
   2123 	 */
   2124 	error = sysctl_lock(NULL, NULL, 0);
   2125 	if (error)
   2126 		return (error);
   2127 
   2128 	/*
   2129 	 * where is it?
   2130 	 */
   2131 	node = rnode;
   2132 	error = sysctl_locate(NULL, &name[0], namelen - 1, &node, &ni);
   2133 	if (error) {
   2134 		/* they want it gone and it's not there, so... */
   2135 		sysctl_unlock(NULL);
   2136 		return (error == ENOENT ? 0 : error);
   2137 	}
   2138 
   2139 	/*
   2140 	 * set up the deletion
   2141 	 */
   2142 	pnode = node;
   2143 	node = &dnode;
   2144 	memset(&dnode, 0, sizeof(dnode));
   2145 	dnode.sysctl_flags = SYSCTL_VERSION;
   2146 	dnode.sysctl_num = name[namelen - 1];
   2147 
   2148 	/*
   2149 	 * we found it, now let's nuke it
   2150 	 */
   2151 	name[namelen - 1] = CTL_DESTROY;
   2152 	sz = 0;
   2153 	error = sysctl_destroy(&name[namelen - 1], 1, NULL, &sz,
   2154 			       node, sizeof(*node), &name[0], NULL,
   2155 			       pnode);
   2156 	if (error == ENOTEMPTY) {
   2157 		/*
   2158 		 * think of trying to delete "foo" when "foo.bar"
   2159 		 * (which someone else put there) is still in
   2160 		 * existence
   2161 		 */
   2162 		error = 0;
   2163 
   2164 		/*
   2165 		 * dunno who put the description there, but if this
   2166 		 * node can ever be removed, we need to make sure the
   2167 		 * string doesn't go out of context.  that means we
   2168 		 * need to find the node that's still there (don't use
   2169 		 * sysctl_locate() because that follows aliasing).
   2170 		 */
   2171 		node = pnode->sysctl_child;
   2172 		for (ni = 0; ni < pnode->sysctl_clen; ni++)
   2173 			if (node[ni].sysctl_num == dnode.sysctl_num)
   2174 				break;
   2175 		node = (ni < pnode->sysctl_clen) ? &node[ni] : NULL;
   2176 
   2177 		/*
   2178 		 * if we found it, and this node has a description,
   2179 		 * and this node can be released, and it doesn't
   2180 		 * already own its own description...sigh.  :)
   2181 		 */
   2182 		if (node != NULL && node->sysctl_desc != NULL &&
   2183 		    !(node->sysctl_flags & CTLFLAG_PERMANENT) &&
   2184 		    !(node->sysctl_flags & CTLFLAG_OWNDESC)) {
   2185 			char *d;
   2186 
   2187 			sz = strlen(node->sysctl_desc) + 1;
   2188 			d = malloc(sz, M_SYSCTLDATA, M_WAITOK|M_CANFAIL);
   2189 			if (d != NULL) {
   2190 				/*
   2191 				 * discard const so that we can
   2192 				 * re-attach the description
   2193 				 */
   2194 				memcpy(d, node->sysctl_desc, sz);
   2195 				onode = __UNCONST(node);
   2196 				onode->sysctl_desc = d;
   2197 				onode->sysctl_flags |= CTLFLAG_OWNDESC;
   2198 			} else {
   2199 				/*
   2200 				 * XXX drop the description?  be
   2201 				 * afraid?  don't care?
   2202 				 */
   2203 			}
   2204 		}
   2205 	}
   2206 
   2207         sysctl_unlock(NULL);
   2208 
   2209 	return (error);
   2210 }
   2211 
   2212 #if 0
   2213 /*
   2214  * ********************************************************************
   2215  * the dump routine.  i haven't yet decided how (if at all) i'll call
   2216  * this from userland when it's in the kernel.
   2217  * ********************************************************************
   2218  */
   2219 static const char *
   2220 sf(int f)
   2221 {
   2222 	static char s[256];
   2223 	char *c;
   2224 
   2225 	s[0] = '\0';
   2226 	c = "";
   2227 
   2228 #define print_flag(_f, _s, _c, _q, _x) \
   2229 	if (((_f) & (__CONCAT(CTLFLAG_,_x))) == (__CONCAT(CTLFLAG_,_q))) { \
   2230 		strlcat((_s), (_c), sizeof(_s)); \
   2231 		strlcat((_s), __STRING(_q), sizeof(_s)); \
   2232 		(_c) = ","; \
   2233 		(_f) &= ~__CONCAT(CTLFLAG_,_x); \
   2234 	}
   2235 
   2236 	print_flag(f, s, c, READONLY,  READWRITE);
   2237 	print_flag(f, s, c, READWRITE, READWRITE);
   2238 	print_flag(f, s, c, ANYWRITE,  ANYWRITE);
   2239 	print_flag(f, s, c, PRIVATE,   PRIVATE);
   2240 	print_flag(f, s, c, PERMANENT, PERMANENT);
   2241 	print_flag(f, s, c, OWNDATA,   OWNDATA);
   2242 	print_flag(f, s, c, IMMEDIATE, IMMEDIATE);
   2243 	print_flag(f, s, c, HEX,       HEX);
   2244 	print_flag(f, s, c, ROOT,      ROOT);
   2245 	print_flag(f, s, c, ANYNUMBER, ANYNUMBER);
   2246 	print_flag(f, s, c, HIDDEN,    HIDDEN);
   2247 	print_flag(f, s, c, ALIAS,     ALIAS);
   2248 #undef print_flag
   2249 
   2250 	if (f) {
   2251 		char foo[9];
   2252 		snprintf(foo, sizeof(foo), "%x", f);
   2253 		strlcat(s, c, sizeof(s));
   2254 		strlcat(s, foo, sizeof(s));
   2255 	}
   2256 
   2257 	return (s);
   2258 }
   2259 
   2260 static const char *
   2261 st(int t)
   2262 {
   2263 
   2264 	switch (t) {
   2265 	case CTLTYPE_NODE:
   2266 		return "NODE";
   2267 	case CTLTYPE_INT:
   2268 		return "INT";
   2269 	case CTLTYPE_STRING:
   2270 		return "STRING";
   2271 	case CTLTYPE_QUAD:
   2272 		return "QUAD";
   2273 	case CTLTYPE_STRUCT:
   2274 		return "STRUCT";
   2275 	}
   2276 
   2277 	return "???";
   2278 }
   2279 
   2280 void
   2281 sysctl_dump(const struct sysctlnode *d)
   2282 {
   2283 	static char nmib[64], smib[256];
   2284 	static int indent;
   2285 	struct sysctlnode *n;
   2286 	char *np, *sp, tmp[20];
   2287 	int i;
   2288 
   2289 	if (d == NULL)
   2290 		return;
   2291 
   2292 	np = &nmib[strlen(nmib)];
   2293 	sp = &smib[strlen(smib)];
   2294 
   2295 	if (!(d->sysctl_flags & CTLFLAG_ROOT)) {
   2296 		snprintf(tmp, sizeof(tmp), "%d", d->sysctl_num);
   2297 		strcat(nmib, ".");
   2298 		strcat(smib, ".");
   2299 		strcat(nmib, tmp);
   2300 		strcat(smib, d->sysctl_name);
   2301 		printf("%s -> %s (%d)\n", &nmib[1], &smib[1],
   2302 		       SYSCTL_TYPE(d->sysctl_flags));
   2303 	}
   2304 
   2305 	if (1) {
   2306 		printf("%*s%p:\tsysctl_name  [%s]\n", indent, "",
   2307 		       d, d->sysctl_name);
   2308 		printf("%*s\t\tsysctl_num    %d\n",   indent, "",
   2309 		       d->sysctl_num);
   2310 		printf("%*s\t\tsysctl_flags  %x (flags=%x<%s> type=%d<%s> "
   2311 		       "size=%zu)\n",
   2312 		       indent, "", d->sysctl_flags,
   2313 		       SYSCTL_FLAGS(d->sysctl_flags),
   2314 		       sf(SYSCTL_FLAGS(d->sysctl_flags)),
   2315 		       SYSCTL_TYPE(d->sysctl_flags),
   2316 		       st(SYSCTL_TYPE(d->sysctl_flags)),
   2317 		       d->sysctl_size);
   2318 		if (SYSCTL_TYPE(d->sysctl_flags) == CTLTYPE_NODE) {
   2319 			printf("%*s\t\tsysctl_csize  %d\n",   indent, "",
   2320 			       d->sysctl_csize);
   2321 			printf("%*s\t\tsysctl_clen   %d\n",   indent, "",
   2322 			       d->sysctl_clen);
   2323 			printf("%*s\t\tsysctl_child  %p\n",   indent, "",
   2324 			       d->sysctl_child);
   2325 		} else
   2326 			printf("%*s\t\tsysctl_data   %p\n",   indent, "",
   2327 			       d->sysctl_data);
   2328 		printf("%*s\t\tsysctl_func   %p\n",   indent, "",
   2329 		       d->sysctl_func);
   2330 		printf("%*s\t\tsysctl_parent %p\n",   indent, "",
   2331 		       d->sysctl_parent);
   2332 		printf("%*s\t\tsysctl_ver    %d\n",   indent, "",
   2333 		       d->sysctl_ver);
   2334 	}
   2335 
   2336 	if (SYSCTL_TYPE(d->sysctl_flags) == CTLTYPE_NODE) {
   2337 		indent += 8;
   2338 		n = d->sysctl_child;
   2339 		for (i = 0; i < d->sysctl_clen; i++) {
   2340 			sysctl_dump(&n[i]);
   2341 		}
   2342 		indent -= 8;
   2343 	}
   2344 
   2345 	np[0] = '\0';
   2346 	sp[0] = '\0';
   2347 }
   2348 #endif /* 0 */
   2349 
   2350 /*
   2351  * ********************************************************************
   2352  * Deletes an entire n-ary tree.  Not recommended unless you know why
   2353  * you're doing it.  Personally, I don't know why you'd even think
   2354  * about it.
   2355  * ********************************************************************
   2356  */
   2357 void
   2358 sysctl_free(struct sysctlnode *rnode)
   2359 {
   2360 	struct sysctlnode *node, *pnode;
   2361 
   2362 	if (rnode == NULL)
   2363 		rnode = &sysctl_root;
   2364 
   2365 	if (SYSCTL_VERS(rnode->sysctl_flags) != SYSCTL_VERSION) {
   2366 		printf("sysctl_free: rnode %p wrong version\n", rnode);
   2367 		return;
   2368 	}
   2369 
   2370 	pnode = rnode;
   2371 
   2372 	node = pnode->sysctl_child;
   2373 	do {
   2374 		while (node != NULL && pnode->sysctl_csize > 0) {
   2375 			while (node <
   2376 			       &pnode->sysctl_child[pnode->sysctl_clen] &&
   2377 			       (SYSCTL_TYPE(node->sysctl_flags) !=
   2378 				CTLTYPE_NODE ||
   2379 				node->sysctl_csize == 0)) {
   2380 				if (SYSCTL_FLAGS(node->sysctl_flags) &
   2381 				    CTLFLAG_OWNDATA) {
   2382 					if (node->sysctl_data != NULL) {
   2383 						free(node->sysctl_data,
   2384 						     M_SYSCTLDATA);
   2385 						node->sysctl_data = NULL;
   2386 					}
   2387 				}
   2388 				if (SYSCTL_FLAGS(node->sysctl_flags) &
   2389 				    CTLFLAG_OWNDESC) {
   2390 					if (node->sysctl_desc != NULL) {
   2391 						/*XXXUNCONST*/
   2392 						free(__UNCONST(node->sysctl_desc),
   2393 						     M_SYSCTLDATA);
   2394 						node->sysctl_desc = NULL;
   2395 					}
   2396 				}
   2397 				node++;
   2398 			}
   2399 			if (node < &pnode->sysctl_child[pnode->sysctl_clen]) {
   2400 				pnode = node;
   2401 				node = node->sysctl_child;
   2402 			} else
   2403 				break;
   2404 		}
   2405 		if (pnode->sysctl_child != NULL)
   2406 			free(pnode->sysctl_child, M_SYSCTLNODE);
   2407 		pnode->sysctl_clen = 0;
   2408 		pnode->sysctl_csize = 0;
   2409 		pnode->sysctl_child = NULL;
   2410 		node = pnode;
   2411 		pnode = node->sysctl_parent;
   2412 	} while (pnode != NULL && node != rnode);
   2413 }
   2414 
   2415 int
   2416 sysctl_log_add(struct sysctllog **logp, const struct sysctlnode *node)
   2417 {
   2418 	int name[CTL_MAXNAME], namelen, i;
   2419 	const struct sysctlnode *pnode;
   2420 	struct sysctllog *log;
   2421 
   2422 	if (node->sysctl_flags & CTLFLAG_PERMANENT)
   2423 		return (0);
   2424 
   2425 	if (logp == NULL)
   2426 		return (0);
   2427 
   2428 	if (*logp == NULL) {
   2429 		log = malloc(sizeof(struct sysctllog),
   2430 		       M_SYSCTLDATA, M_WAITOK|M_CANFAIL);
   2431 		if (log == NULL) {
   2432 			/* XXX print error message? */
   2433 			return (-1);
   2434 		}
   2435 		log->log_num = malloc(16 * sizeof(int),
   2436 		       M_SYSCTLDATA, M_WAITOK|M_CANFAIL);
   2437 		if (log->log_num == NULL) {
   2438 			/* XXX print error message? */
   2439 			free(log, M_SYSCTLDATA);
   2440 			return (-1);
   2441 		}
   2442 		memset(log->log_num, 0, 16 * sizeof(int));
   2443 		log->log_root = NULL;
   2444 		log->log_size = 16;
   2445 		log->log_left = 16;
   2446 		*logp = log;
   2447 	} else
   2448 		log = *logp;
   2449 
   2450 	/*
   2451 	 * check that the root is proper.  it's okay to record the
   2452 	 * address of the root of a tree.  it's the only thing that's
   2453 	 * guaranteed not to shift around as nodes come and go.
   2454 	 */
   2455 	if (log->log_root == NULL)
   2456 		log->log_root = sysctl_rootof(node);
   2457 	else if (log->log_root != sysctl_rootof(node)) {
   2458 		printf("sysctl: log %p root mismatch (%p)\n",
   2459 		       log->log_root, sysctl_rootof(node));
   2460 		return (-1);
   2461 	}
   2462 
   2463 	/*
   2464 	 * we will copy out name in reverse order
   2465 	 */
   2466 	for (pnode = node, namelen = 0;
   2467 	     pnode != NULL && !(pnode->sysctl_flags & CTLFLAG_ROOT);
   2468 	     pnode = pnode->sysctl_parent)
   2469 		name[namelen++] = pnode->sysctl_num;
   2470 
   2471 	/*
   2472 	 * do we have space?
   2473 	 */
   2474 	if (log->log_left < (namelen + 3))
   2475 		sysctl_log_realloc(log);
   2476 	if (log->log_left < (namelen + 3))
   2477 		return (-1);
   2478 
   2479 	/*
   2480 	 * stuff name in, then namelen, then node type, and finally,
   2481 	 * the version for non-node nodes.
   2482 	 */
   2483 	for (i = 0; i < namelen; i++)
   2484 		log->log_num[--log->log_left] = name[i];
   2485 	log->log_num[--log->log_left] = namelen;
   2486 	log->log_num[--log->log_left] = SYSCTL_TYPE(node->sysctl_flags);
   2487 	if (log->log_num[log->log_left] != CTLTYPE_NODE)
   2488 		log->log_num[--log->log_left] = node->sysctl_ver;
   2489 	else
   2490 		log->log_num[--log->log_left] = 0;
   2491 
   2492 	return (0);
   2493 }
   2494 
   2495 void
   2496 sysctl_teardown(struct sysctllog **logp)
   2497 {
   2498 	const struct sysctlnode *rnode;
   2499 	struct sysctlnode node;
   2500 	struct sysctllog *log;
   2501 	uint namelen;
   2502 	int *name, t, v, error, ni;
   2503 	size_t sz;
   2504 
   2505 	if (logp == NULL || *logp == NULL)
   2506 		return;
   2507 	log = *logp;
   2508 
   2509 	error = sysctl_lock(NULL, NULL, 0);
   2510 	if (error)
   2511 		return;
   2512 
   2513 	memset(&node, 0, sizeof(node));
   2514 
   2515 	while (log->log_left < log->log_size) {
   2516 		KASSERT((log->log_left + 3 < log->log_size) &&
   2517 			(log->log_left + log->log_num[log->log_left + 2] <=
   2518 			 log->log_size));
   2519 		v = log->log_num[log->log_left++];
   2520 		t = log->log_num[log->log_left++];
   2521 		namelen = log->log_num[log->log_left++];
   2522 		name = &log->log_num[log->log_left];
   2523 
   2524 		node.sysctl_num = name[namelen - 1];
   2525 		node.sysctl_flags = SYSCTL_VERSION|t;
   2526 		node.sysctl_ver = v;
   2527 
   2528 		rnode = log->log_root;
   2529 		error = sysctl_locate(NULL, &name[0], namelen, &rnode, &ni);
   2530 		if (error == 0) {
   2531 			name[namelen - 1] = CTL_DESTROY;
   2532 			rnode = rnode->sysctl_parent;
   2533 			sz = 0;
   2534 			(void)sysctl_destroy(&name[namelen - 1], 1, NULL,
   2535 					     &sz, &node, sizeof(node),
   2536 					     &name[0], NULL, rnode);
   2537 		}
   2538 
   2539 		log->log_left += namelen;
   2540 	}
   2541 
   2542 	KASSERT(log->log_size == log->log_left);
   2543 	free(log->log_num, M_SYSCTLDATA);
   2544 	free(log, M_SYSCTLDATA);
   2545 	*logp = NULL;
   2546 
   2547 	sysctl_unlock(NULL);
   2548 }
   2549 
   2550 /*
   2551  * ********************************************************************
   2552  * old_sysctl -- A routine to bridge old-style internal calls to the
   2553  * new infrastructure.
   2554  * ********************************************************************
   2555  */
   2556 int
   2557 old_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp,
   2558 	   void *newp, size_t newlen, struct lwp *l)
   2559 {
   2560 	int error;
   2561 	size_t oldlen = 0;
   2562 	size_t savelen;
   2563 
   2564 	if (oldlenp) {
   2565 		oldlen = *oldlenp;
   2566 	}
   2567 	savelen = oldlen;
   2568 
   2569 	error = sysctl_lock(l, oldp, savelen);
   2570 	if (error)
   2571 		return (error);
   2572 	error = sysctl_dispatch(name, namelen, oldp, &oldlen,
   2573 				newp, newlen, name, l, NULL);
   2574 	sysctl_unlock(l);
   2575 	if (error == 0 && oldp != NULL && savelen < oldlen)
   2576 		error = ENOMEM;
   2577 
   2578 	if (oldlenp) {
   2579 		*oldlenp = oldlen;
   2580 	}
   2581 
   2582 	return (error);
   2583 }
   2584 
   2585 /*
   2586  * ********************************************************************
   2587  * Section 4: Generic helper routines
   2588  * ********************************************************************
   2589  * "helper" routines that can do more finely grained access control,
   2590  * construct structures from disparate information, create the
   2591  * appearance of more nodes and sub-trees, etc.  for example, if
   2592  * CTL_PROC wanted a helper function, it could respond to a CTL_QUERY
   2593  * with a dynamically created list of nodes that represented the
   2594  * currently running processes at that instant.
   2595  * ********************************************************************
   2596  */
   2597 
   2598 /*
   2599  * first, a few generic helpers that provide:
   2600  *
   2601  * sysctl_needfunc()		a readonly interface that emits a warning
   2602  * sysctl_notavail()		returns EOPNOTSUPP (generic error)
   2603  * sysctl_null()		an empty return buffer with no error
   2604  */
   2605 int
   2606 sysctl_needfunc(SYSCTLFN_ARGS)
   2607 {
   2608 	int error;
   2609 
   2610 	printf("!!SYSCTL_NEEDFUNC!!\n");
   2611 
   2612 	if (newp != NULL || namelen != 0)
   2613 		return (EOPNOTSUPP);
   2614 
   2615 	error = 0;
   2616 	if (oldp != NULL)
   2617 		error = sysctl_copyout(l, rnode->sysctl_data, oldp,
   2618 				       MIN(rnode->sysctl_size, *oldlenp));
   2619 	*oldlenp = rnode->sysctl_size;
   2620 
   2621 	return (error);
   2622 }
   2623 
   2624 int
   2625 sysctl_notavail(SYSCTLFN_ARGS)
   2626 {
   2627 
   2628 	if (namelen == 1 && name[0] == CTL_QUERY)
   2629 		return (sysctl_query(SYSCTLFN_CALL(rnode)));
   2630 
   2631 	return (EOPNOTSUPP);
   2632 }
   2633 
   2634 int
   2635 sysctl_null(SYSCTLFN_ARGS)
   2636 {
   2637 
   2638 	*oldlenp = 0;
   2639 
   2640 	return (0);
   2641 }
   2642 
   2643 /*
   2644  * ********************************************************************
   2645  * Section 5: The machinery that makes it all go
   2646  * ********************************************************************
   2647  * Memory "manglement" routines.  Not much to this, eh?
   2648  * ********************************************************************
   2649  */
   2650 static int
   2651 sysctl_alloc(struct sysctlnode *p, int x)
   2652 {
   2653 	int i;
   2654 	struct sysctlnode *n;
   2655 
   2656 	assert(p->sysctl_child == NULL);
   2657 
   2658 	if (x == 1)
   2659 		n = malloc(sizeof(struct sysctlnode),
   2660 		       M_SYSCTLNODE, M_WAITOK|M_CANFAIL);
   2661 	else
   2662 		n = malloc(SYSCTL_DEFSIZE * sizeof(struct sysctlnode),
   2663 		       M_SYSCTLNODE, M_WAITOK|M_CANFAIL);
   2664 	if (n == NULL)
   2665 		return (ENOMEM);
   2666 
   2667 	if (x == 1) {
   2668 		memset(n, 0, sizeof(struct sysctlnode));
   2669 		p->sysctl_csize = 1;
   2670 	} else {
   2671 		memset(n, 0, SYSCTL_DEFSIZE * sizeof(struct sysctlnode));
   2672 		p->sysctl_csize = SYSCTL_DEFSIZE;
   2673 	}
   2674 	p->sysctl_clen = 0;
   2675 
   2676 	for (i = 0; i < p->sysctl_csize; i++)
   2677 		n[i].sysctl_parent = p;
   2678 
   2679 	p->sysctl_child = n;
   2680 	return (0);
   2681 }
   2682 
   2683 static int
   2684 sysctl_realloc(struct sysctlnode *p)
   2685 {
   2686 	int i, j;
   2687 	struct sysctlnode *n;
   2688 
   2689 	assert(p->sysctl_csize == p->sysctl_clen);
   2690 
   2691 	/*
   2692 	 * how many do we have...how many should we make?
   2693 	 */
   2694 	i = p->sysctl_clen;
   2695 	n = malloc(2 * i * sizeof(struct sysctlnode), M_SYSCTLNODE,
   2696 		   M_WAITOK|M_CANFAIL);
   2697 	if (n == NULL)
   2698 		return (ENOMEM);
   2699 
   2700 	/*
   2701 	 * move old children over...initialize new children
   2702 	 */
   2703 	memcpy(n, p->sysctl_child, i * sizeof(struct sysctlnode));
   2704 	memset(&n[i], 0, i * sizeof(struct sysctlnode));
   2705 	p->sysctl_csize = 2 * i;
   2706 
   2707 	/*
   2708 	 * reattach moved (and new) children to parent; if a moved
   2709 	 * child node has children, reattach the parent pointers of
   2710 	 * grandchildren
   2711 	 */
   2712         for (i = 0; i < p->sysctl_csize; i++) {
   2713                 n[i].sysctl_parent = p;
   2714 		if (n[i].sysctl_child != NULL) {
   2715 			for (j = 0; j < n[i].sysctl_csize; j++)
   2716 				n[i].sysctl_child[j].sysctl_parent = &n[i];
   2717 		}
   2718 	}
   2719 
   2720 	/*
   2721 	 * get out with the old and in with the new
   2722 	 */
   2723 	free(p->sysctl_child, M_SYSCTLNODE);
   2724 	p->sysctl_child = n;
   2725 
   2726 	return (0);
   2727 }
   2728 
   2729 static int
   2730 sysctl_log_realloc(struct sysctllog *log)
   2731 {
   2732 	int *n, s, d;
   2733 
   2734 	s = log->log_size * 2;
   2735 	d = log->log_size;
   2736 
   2737 	n = malloc(s * sizeof(int), M_SYSCTLDATA, M_WAITOK|M_CANFAIL);
   2738 	if (n == NULL)
   2739 		return (-1);
   2740 
   2741 	memset(n, 0, s * sizeof(int));
   2742 	memcpy(&n[d], log->log_num, d * sizeof(int));
   2743 	free(log->log_num, M_SYSCTLDATA);
   2744 	log->log_num = n;
   2745 	if (d)
   2746 		log->log_left += d;
   2747 	else
   2748 		log->log_left = s;
   2749 	log->log_size = s;
   2750 
   2751 	return (0);
   2752 }
   2753 
   2754 /*
   2755  * ********************************************************************
   2756  * Section 6: Conversion between API versions wrt the sysctlnode
   2757  * ********************************************************************
   2758  */
   2759 static int
   2760 sysctl_cvt_in(struct lwp *l, int *vp, const void *i, size_t sz,
   2761 	      struct sysctlnode *node)
   2762 {
   2763 	int error, flags;
   2764 
   2765 	if (i == NULL || sz < sizeof(flags))
   2766 		return (EINVAL);
   2767 
   2768 	error = sysctl_copyin(l, i, &flags, sizeof(flags));
   2769 	if (error)
   2770 		return (error);
   2771 
   2772 #if (SYSCTL_VERSION != SYSCTL_VERS_1)
   2773 #error sysctl_cvt_in: no support for SYSCTL_VERSION
   2774 #endif /*  (SYSCTL_VERSION != SYSCTL_VERS_1) */
   2775 
   2776 	if (sz == sizeof(*node) &&
   2777 	    SYSCTL_VERS(flags) == SYSCTL_VERSION) {
   2778 		error = sysctl_copyin(l, i, node, sizeof(*node));
   2779 		if (error)
   2780 			return (error);
   2781 		*vp = SYSCTL_VERSION;
   2782 		return (0);
   2783 	}
   2784 
   2785 	return (EINVAL);
   2786 }
   2787 
   2788 static int
   2789 sysctl_cvt_out(struct lwp *l, int v, const struct sysctlnode *i,
   2790 	       void *ovp, size_t left, size_t *szp)
   2791 {
   2792 	size_t sz = sizeof(*i);
   2793 	const void *src = i;
   2794 	int error;
   2795 
   2796 	switch (v) {
   2797 	case SYSCTL_VERS_0:
   2798 		return (EINVAL);
   2799 
   2800 #if (SYSCTL_VERSION != SYSCTL_VERS_1)
   2801 #error sysctl_cvt_out: no support for SYSCTL_VERSION
   2802 #endif /*  (SYSCTL_VERSION != SYSCTL_VERS_1) */
   2803 
   2804 	case SYSCTL_VERSION:
   2805 		/* nothing more to do here */
   2806 		break;
   2807 	}
   2808 
   2809 	if (ovp != NULL && left >= sz) {
   2810 		error = sysctl_copyout(l, src, ovp, sz);
   2811 		if (error)
   2812 			return (error);
   2813 	}
   2814 
   2815 	if (szp != NULL)
   2816 		*szp = sz;
   2817 
   2818 	return (0);
   2819 }
   2820