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