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