Home | History | Annotate | Line # | Download | only in kern
kern_sysctl.c revision 1.199
      1 /*	$NetBSD: kern_sysctl.c,v 1.199 2006/07/30 17:38:19 elad Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 2003 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Andrew Brown.
      9  *
     10  * Redistribution and use in source and binary forms, with or without
     11  * modification, are permitted provided that the following conditions
     12  * are met:
     13  * 1. Redistributions of source code must retain the above copyright
     14  *    notice, this list of conditions and the following disclaimer.
     15  * 2. Redistributions in binary form must reproduce the above copyright
     16  *    notice, this list of conditions and the following disclaimer in the
     17  *    documentation and/or other materials provided with the distribution.
     18  * 3. All advertising materials mentioning features or use of this software
     19  *    must display the following acknowledgement:
     20  *      This product includes software developed by the NetBSD
     21  *      Foundation, Inc. and its contributors.
     22  * 4. Neither the name of The NetBSD Foundation nor the names of its
     23  *    contributors may be used to endorse or promote products derived
     24  *    from this software without specific prior written permission.
     25  *
     26  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     27  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     28  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     29  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     30  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     31  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     32  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     33  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     34  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     35  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     36  * POSSIBILITY OF SUCH DAMAGE.
     37  */
     38 
     39 /*-
     40  * Copyright (c) 1982, 1986, 1989, 1993
     41  *	The Regents of the University of California.  All rights reserved.
     42  *
     43  * This code is derived from software contributed to Berkeley by
     44  * Mike Karels at Berkeley Software Design, Inc.
     45  *
     46  * Redistribution and use in source and binary forms, with or without
     47  * modification, are permitted provided that the following conditions
     48  * are met:
     49  * 1. Redistributions of source code must retain the above copyright
     50  *    notice, this list of conditions and the following disclaimer.
     51  * 2. Redistributions in binary form must reproduce the above copyright
     52  *    notice, this list of conditions and the following disclaimer in the
     53  *    documentation and/or other materials provided with the distribution.
     54  * 3. Neither the name of the University nor the names of its contributors
     55  *    may be used to endorse or promote products derived from this software
     56  *    without specific prior written permission.
     57  *
     58  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     59  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     60  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     61  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     62  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     63  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     64  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     65  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     66  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     67  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     68  * SUCH DAMAGE.
     69  *
     70  *	@(#)kern_sysctl.c	8.9 (Berkeley) 5/20/95
     71  */
     72 
     73 /*
     74  * sysctl system call.
     75  */
     76 
     77 #include <sys/cdefs.h>
     78 __KERNEL_RCSID(0, "$NetBSD: kern_sysctl.c,v 1.199 2006/07/30 17:38:19 elad Exp $");
     79 
     80 #include "opt_defcorename.h"
     81 #include "ksyms.h"
     82 
     83 #include <sys/param.h>
     84 #define __COMPAT_SYSCTL
     85 #include <sys/sysctl.h>
     86 #include <sys/systm.h>
     87 #include <sys/buf.h>
     88 #include <sys/ksyms.h>
     89 #include <sys/malloc.h>
     90 #include <sys/mount.h>
     91 #include <sys/sa.h>
     92 #include <sys/syscallargs.h>
     93 #include <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 = (rnode->sysctl_flags & CTLFLAG_READWRITE) ? 1 : 0;
   1442 
   1443 	/*
   1444 	 * it appears not to be writable at this time, so if someone
   1445 	 * tried to write to it, we must tell them to go away
   1446 	 */
   1447 	if (!rw && newp != NULL)
   1448 		return (EPERM);
   1449 
   1450 	/*
   1451 	 * step one, copy out the stuff we have presently
   1452 	 */
   1453 	if (rnode->sysctl_flags & CTLFLAG_IMMEDIATE) {
   1454 		/*
   1455 		 * note that we discard const here because we are
   1456 		 * modifying the contents of the node (which is okay
   1457 		 * because it's ours)
   1458 		 */
   1459 		switch (SYSCTL_TYPE(rnode->sysctl_flags)) {
   1460 		case CTLTYPE_INT:
   1461 			d = __UNCONST(&rnode->sysctl_idata);
   1462 			break;
   1463 		case CTLTYPE_QUAD:
   1464 			d = __UNCONST(&rnode->sysctl_qdata);
   1465 			break;
   1466 		default:
   1467 			return (EINVAL);
   1468 		}
   1469 	} else
   1470 		d = rnode->sysctl_data;
   1471 	if (SYSCTL_TYPE(rnode->sysctl_flags) == CTLTYPE_STRING)
   1472 		sz = strlen(d) + 1; /* XXX@@@ possible fault here */
   1473 	else
   1474 		sz = rnode->sysctl_size;
   1475 	if (oldp != NULL)
   1476 		error = sysctl_copyout(l, d, oldp, MIN(sz, *oldlenp));
   1477 	if (error)
   1478 		return (error);
   1479 	*oldlenp = sz;
   1480 
   1481 	/*
   1482 	 * are we done?
   1483 	 */
   1484 	if (newp == NULL || newlen == 0)
   1485 		return (0);
   1486 
   1487 	/*
   1488 	 * hmm...not done.  must now "copy in" new value.  re-adjust
   1489 	 * sz to maximum value (strings are "weird").
   1490 	 */
   1491 	sz = rnode->sysctl_size;
   1492 	switch (SYSCTL_TYPE(rnode->sysctl_flags)) {
   1493 	case CTLTYPE_INT:
   1494 	case CTLTYPE_QUAD:
   1495 	case CTLTYPE_STRUCT:
   1496 		/*
   1497 		 * these data must be *exactly* the same size coming
   1498 		 * in.
   1499 		 */
   1500 		if (newlen != sz)
   1501 			return (EINVAL);
   1502 		error = sysctl_copyin(l, newp, d, sz);
   1503 		break;
   1504 	case CTLTYPE_STRING: {
   1505 		/*
   1506 		 * strings, on the other hand, can be shorter, and we
   1507 		 * let userland be sloppy about the trailing nul.
   1508 		 */
   1509 		char *newbuf;
   1510 
   1511 		/*
   1512 		 * too much new string?
   1513 		 */
   1514 		if (newlen > sz)
   1515 			return (EINVAL);
   1516 
   1517 		/*
   1518 		 * temporary copy of new inbound string
   1519 		 */
   1520 		len = MIN(sz, newlen);
   1521 		newbuf = malloc(len, M_SYSCTLDATA, M_WAITOK|M_CANFAIL);
   1522 		if (newbuf == NULL)
   1523 			return (ENOMEM);
   1524 		error = sysctl_copyin(l, newp, newbuf, len);
   1525 		if (error) {
   1526 			free(newbuf, M_SYSCTLDATA);
   1527 			return (error);
   1528 		}
   1529 
   1530 		/*
   1531 		 * did they null terminate it, or do we have space
   1532 		 * left to do it ourselves?
   1533 		 */
   1534 		if (newbuf[len - 1] != '\0' && len == sz) {
   1535 			free(newbuf, M_SYSCTLDATA);
   1536 			return (EINVAL);
   1537 		}
   1538 
   1539 		/*
   1540 		 * looks good, so pop it into place and zero the rest.
   1541 		 */
   1542 		if (len > 0)
   1543 			memcpy(d, newbuf, len);
   1544 		if (sz != len)
   1545 			memset((char*)d + len, 0, sz - len);
   1546 		free(newbuf, M_SYSCTLDATA);
   1547 		break;
   1548 	}
   1549 	default:
   1550 		return (EINVAL);
   1551 	}
   1552 
   1553 	return (error);
   1554 }
   1555 
   1556 /*
   1557  * sysctl_mmap -- Dispatches sysctl mmap requests to those nodes that
   1558  * purport to handle it.  This interface isn't fully fleshed out yet,
   1559  * unfortunately.
   1560  */
   1561 static int
   1562 sysctl_mmap(SYSCTLFN_ARGS)
   1563 {
   1564 	const struct sysctlnode *node;
   1565 	struct sysctlnode nnode;
   1566 	int error;
   1567 
   1568 	if (SYSCTL_VERS(rnode->sysctl_flags) != SYSCTL_VERSION) {
   1569 		printf("sysctl_mmap: rnode %p wrong version\n", rnode);
   1570 		return (EINVAL);
   1571 	}
   1572 
   1573 	/*
   1574 	 * let's just pretend that didn't happen, m'kay?
   1575 	 */
   1576 	if (l == NULL)
   1577 		return (EPERM);
   1578 
   1579 	/*
   1580 	 * is this a sysctlnode description of an mmap request?
   1581 	 */
   1582 	if (newp == NULL || newlen != sizeof(struct sysctlnode))
   1583 		return (EINVAL);
   1584 	error = sysctl_copyin(l, newp, &nnode, sizeof(nnode));
   1585 	if (error)
   1586 		return (error);
   1587 
   1588 	/*
   1589 	 * does the node they asked for exist?
   1590 	 */
   1591 	if (namelen != 1)
   1592 		return (EOPNOTSUPP);
   1593 	node = rnode;
   1594         error = sysctl_locate(l, &nnode.sysctl_num, 1, &node, NULL);
   1595 	if (error)
   1596 		return (error);
   1597 
   1598 	/*
   1599 	 * does this node that we have found purport to handle mmap?
   1600 	 */
   1601 	if (node->sysctl_func == NULL ||
   1602 	    !(node->sysctl_flags & CTLFLAG_MMAP))
   1603 		return (EOPNOTSUPP);
   1604 
   1605 	/*
   1606 	 * well...okay, they asked for it.
   1607 	 */
   1608 	return ((*node->sysctl_func)(SYSCTLFN_CALL(node)));
   1609 }
   1610 
   1611 int
   1612 sysctl_describe(SYSCTLFN_ARGS)
   1613 {
   1614 	struct sysctldesc *d;
   1615 	void *bf;
   1616 	size_t sz, left, tot;
   1617 	int i, error, v = -1;
   1618 	struct sysctlnode *node;
   1619 	struct sysctlnode dnode;
   1620 
   1621 	if (SYSCTL_VERS(rnode->sysctl_flags) != SYSCTL_VERSION) {
   1622 		printf("sysctl_query: rnode %p wrong version\n", rnode);
   1623 		return (EINVAL);
   1624 	}
   1625 
   1626 	if (SYSCTL_TYPE(rnode->sysctl_flags) != CTLTYPE_NODE)
   1627 		return (ENOTDIR);
   1628 	if (namelen != 1 || name[0] != CTL_DESCRIBE)
   1629 		return (EINVAL);
   1630 
   1631 	/*
   1632 	 * get ready...
   1633 	 */
   1634 	error = 0;
   1635 	d = bf = malloc(MAXDESCLEN, M_TEMP, M_WAITOK|M_CANFAIL);
   1636 	if (bf == NULL)
   1637 		return ENOMEM;
   1638 	tot = 0;
   1639 	node = rnode->sysctl_child;
   1640 	left = *oldlenp;
   1641 
   1642 	/*
   1643 	 * no request -> all descriptions at this level
   1644 	 * request with desc unset -> just this node
   1645 	 * request with desc set -> set descr for this node
   1646 	 */
   1647 	if (newp != NULL) {
   1648 		error = sysctl_cvt_in(l, &v, newp, newlen, &dnode);
   1649 		if (error)
   1650 			goto out;
   1651 		if (dnode.sysctl_desc != NULL) {
   1652 			/*
   1653 			 * processes cannot set descriptions above
   1654 			 * securelevel 0.  and must be root.  blah
   1655 			 * blah blah.  a couple more checks are made
   1656 			 * once we find the node we want.
   1657 			 */
   1658 			if (l != NULL) {
   1659 #ifndef SYSCTL_DISALLOW_CREATE
   1660 				if (securelevel > 0) {
   1661 					error = EPERM;
   1662 					goto out;
   1663 				}
   1664 				error = kauth_authorize_generic(l->l_cred,
   1665 				    KAUTH_GENERIC_ISSUSER, &l->l_acflag);
   1666 				if (error)
   1667 					goto out;
   1668 #else /* SYSCTL_DISALLOW_CREATE */
   1669 				error = EPERM;
   1670 				goto out;
   1671 #endif /* SYSCTL_DISALLOW_CREATE */
   1672 			}
   1673 
   1674 			/*
   1675 			 * find node and try to set the description on it
   1676 			 */
   1677 			for (i = 0; i < rnode->sysctl_clen; i++)
   1678 				if (node[i].sysctl_num == dnode.sysctl_num)
   1679 					break;
   1680 			if (i == rnode->sysctl_clen) {
   1681 				error = ENOENT;
   1682 				goto out;
   1683 			}
   1684 			node = &node[i];
   1685 
   1686 			/*
   1687 			 * did the caller specify a node version?
   1688 			 */
   1689 			if (dnode.sysctl_ver != 0 &&
   1690 			    dnode.sysctl_ver != node->sysctl_ver) {
   1691 				error = EINVAL;
   1692 				goto out;
   1693 			}
   1694 
   1695 			/*
   1696 			 * okay...some rules:
   1697 			 * (1) if setup is done and the tree is
   1698 			 *     read-only or the whole system is
   1699 			 *     read-only
   1700 			 * (2) no one can set a description on a
   1701 			 *     permanent node (it must be set when
   1702 			 *     using createv)
   1703 			 * (3) processes cannot *change* a description
   1704 			 * (4) processes *can*, however, set a
   1705 			 *     description on a read-only node so that
   1706 			 *     one can be created and then described
   1707 			 *     in two steps
   1708 			 * anything else come to mind?
   1709 			 */
   1710 			if ((sysctl_root.sysctl_flags & CTLFLAG_PERMANENT) &&
   1711 			    (!(sysctl_rootof(node)->sysctl_flags &
   1712 			       CTLFLAG_READWRITE) ||
   1713 			     !(sysctl_root.sysctl_flags & CTLFLAG_READWRITE))) {
   1714 				error = EPERM;
   1715 				goto out;
   1716 			}
   1717 			if (node->sysctl_flags & CTLFLAG_PERMANENT) {
   1718 				error = EPERM;
   1719 				goto out;
   1720 			}
   1721 			if (l != NULL && node->sysctl_desc != NULL) {
   1722 				error = EPERM;
   1723 				goto out;
   1724 			}
   1725 
   1726 			/*
   1727 			 * right, let's go ahead.  the first step is
   1728 			 * making the description into something the
   1729 			 * node can "own", if need be.
   1730 			 */
   1731 			if (l != NULL ||
   1732 			    dnode.sysctl_flags & CTLFLAG_OWNDESC) {
   1733 				char *nd, *k;
   1734 
   1735 				k = malloc(MAXDESCLEN, M_TEMP,
   1736 				    M_WAITOK|M_CANFAIL);
   1737 				if (k == NULL) {
   1738 					error = ENOMEM;
   1739 					goto out;
   1740 				}
   1741 				error = sysctl_copyinstr(l, dnode.sysctl_desc,
   1742 							 k, MAXDESCLEN, &sz);
   1743 				if (error) {
   1744 					free(k, M_TEMP);
   1745 					goto out;
   1746 				}
   1747 				nd = malloc(sz, M_SYSCTLDATA,
   1748 					    M_WAITOK|M_CANFAIL);
   1749 				if (nd == NULL) {
   1750 					free(k, M_TEMP);
   1751 					error = ENOMEM;
   1752 					goto out;
   1753 				}
   1754 				memcpy(nd, k, sz);
   1755 				dnode.sysctl_flags |= CTLFLAG_OWNDESC;
   1756 				dnode.sysctl_desc = nd;
   1757 				free(k, M_TEMP);
   1758 			}
   1759 
   1760 			/*
   1761 			 * now "release" the old description and
   1762 			 * attach the new one.  ta-da.
   1763 			 */
   1764 			if ((node->sysctl_flags & CTLFLAG_OWNDESC) &&
   1765 			    node->sysctl_desc != NULL)
   1766 				/*XXXUNCONST*/
   1767 				free(__UNCONST(node->sysctl_desc), M_SYSCTLDATA);
   1768 			node->sysctl_desc = dnode.sysctl_desc;
   1769 			node->sysctl_flags |=
   1770 				(dnode.sysctl_flags & CTLFLAG_OWNDESC);
   1771 
   1772 			/*
   1773 			 * now we "fall out" and into the loop which
   1774 			 * will copy the new description back out for
   1775 			 * those interested parties
   1776 			 */
   1777 		}
   1778 	}
   1779 
   1780 	/*
   1781 	 * scan for one description or just retrieve all descriptions
   1782 	 */
   1783 	for (i = 0; i < rnode->sysctl_clen; i++) {
   1784 		/*
   1785 		 * did they ask for the description of only one node?
   1786 		 */
   1787 		if (v != -1 && node[i].sysctl_num != dnode.sysctl_num)
   1788 			continue;
   1789 
   1790 		/*
   1791 		 * don't describe "private" nodes to non-suser users
   1792 		 */
   1793 		if ((node[i].sysctl_flags & CTLFLAG_PRIVATE) && (l != NULL) &&
   1794 		    !(kauth_authorize_generic(l->l_cred,
   1795 		    KAUTH_GENERIC_ISSUSER, &l->l_acflag)))
   1796 			continue;
   1797 
   1798 		/*
   1799 		 * is this description "valid"?
   1800 		 */
   1801 		memset(bf, 0, MAXDESCLEN);
   1802 		if (node[i].sysctl_desc == NULL)
   1803 			sz = 1;
   1804 		else if (copystr(node[i].sysctl_desc, &d->descr_str[0],
   1805 				 MAXDESCLEN - sizeof(*d), &sz) != 0) {
   1806 			/*
   1807 			 * erase possible partial description
   1808 			 */
   1809 			memset(bf, 0, MAXDESCLEN);
   1810 			sz = 1;
   1811 		}
   1812 
   1813 		/*
   1814 		 * we've got it, stuff it into the caller's buffer
   1815 		 */
   1816 		d->descr_num = node[i].sysctl_num;
   1817 		d->descr_ver = node[i].sysctl_ver;
   1818 		d->descr_len = sz; /* includes trailing nul */
   1819 		sz = (caddr_t)NEXT_DESCR(d) - (caddr_t)d;
   1820 		if (oldp != NULL && left >= sz) {
   1821 			error = sysctl_copyout(l, d, oldp, sz);
   1822 			if (error)
   1823 				goto out;
   1824 			left -= sz;
   1825 			oldp = (void *)__sysc_desc_adv(oldp, d->descr_len);
   1826 		}
   1827 		tot += sz;
   1828 
   1829 		/*
   1830 		 * if we get this far with v not "unset", they asked
   1831 		 * for a specific node and we found it
   1832 		 */
   1833 		if (v != -1)
   1834 			break;
   1835 	}
   1836 
   1837 	/*
   1838 	 * did we find it after all?
   1839 	 */
   1840 	if (v != -1 && tot == 0)
   1841 		error = ENOENT;
   1842 	else
   1843 		*oldlenp = tot;
   1844 
   1845 out:
   1846 	free(bf, M_TEMP);
   1847 	return (error);
   1848 }
   1849 
   1850 /*
   1851  * ********************************************************************
   1852  * Section 3: Create and destroy from inside the kernel
   1853  * ********************************************************************
   1854  * sysctl_createv() and sysctl_destroyv() are simpler-to-use
   1855  * interfaces for the kernel to fling new entries into the mib and rip
   1856  * them out later.  In the case of sysctl_createv(), the returned copy
   1857  * of the node (see sysctl_create()) will be translated back into a
   1858  * pointer to the actual node.
   1859  *
   1860  * Note that sysctl_createv() will return 0 if the create request
   1861  * matches an existing node (ala mkdir -p), and that sysctl_destroyv()
   1862  * will return 0 if the node to be destroyed already does not exist
   1863  * (aka rm -f) or if it is a parent of other nodes.
   1864  *
   1865  * This allows two (or more) different subsystems to assert sub-tree
   1866  * existence before populating their own nodes, and to remove their
   1867  * own nodes without orphaning the others when they are done.
   1868  * ********************************************************************
   1869  */
   1870 int
   1871 sysctl_createv(struct sysctllog **log, int cflags,
   1872 	       const struct sysctlnode **rnode, const struct sysctlnode **cnode,
   1873 	       int flags, int type, const char *namep, const char *descr,
   1874 	       sysctlfn func, u_quad_t qv, void *newp, size_t newlen,
   1875 	       ...)
   1876 {
   1877 	va_list ap;
   1878 	int error, ni, namelen, name[CTL_MAXNAME];
   1879 	const struct sysctlnode *root, *pnode;
   1880 	struct sysctlnode nnode, onode, *dnode;
   1881 	size_t sz;
   1882 
   1883 	/*
   1884 	 * where are we putting this?
   1885 	 */
   1886 	if (rnode != NULL && *rnode == NULL) {
   1887 		printf("sysctl_createv: rnode NULL\n");
   1888 		return (EINVAL);
   1889 	}
   1890 	root = rnode ? *rnode : NULL;
   1891 	if (cnode != NULL)
   1892 		*cnode = NULL;
   1893 	if (cflags != 0)
   1894 		return (EINVAL);
   1895 
   1896 	/*
   1897 	 * what is it?
   1898 	 */
   1899 	flags = SYSCTL_VERSION|SYSCTL_TYPE(type)|SYSCTL_FLAGS(flags);
   1900 	if (log != NULL)
   1901 		flags &= ~CTLFLAG_PERMANENT;
   1902 
   1903 	/*
   1904 	 * where do we put it?
   1905 	 */
   1906 	va_start(ap, newlen);
   1907 	namelen = 0;
   1908 	ni = -1;
   1909 	do {
   1910 		if (++ni == CTL_MAXNAME)
   1911 			return (ENAMETOOLONG);
   1912 		name[ni] = va_arg(ap, int);
   1913 		/*
   1914 		 * sorry, this is not supported from here
   1915 		 */
   1916 		if (name[ni] == CTL_CREATESYM)
   1917 			return (EINVAL);
   1918 	} while (name[ni] != CTL_EOL && name[ni] != CTL_CREATE);
   1919 	namelen = ni + (name[ni] == CTL_CREATE ? 1 : 0);
   1920 	va_end(ap);
   1921 
   1922 	/*
   1923 	 * what's it called
   1924 	 */
   1925 	if (strlcpy(nnode.sysctl_name, namep, sizeof(nnode.sysctl_name)) >=
   1926 	    sizeof(nnode.sysctl_name))
   1927 		return (ENAMETOOLONG);
   1928 
   1929 	/*
   1930 	 * cons up the description of the new node
   1931 	 */
   1932 	nnode.sysctl_num = name[namelen - 1];
   1933 	name[namelen - 1] = CTL_CREATE;
   1934 	nnode.sysctl_size = newlen;
   1935 	nnode.sysctl_flags = flags;
   1936 	if (type == CTLTYPE_NODE) {
   1937 		nnode.sysctl_csize = 0;
   1938 		nnode.sysctl_clen = 0;
   1939 		nnode.sysctl_child = NULL;
   1940 		if (flags & CTLFLAG_ALIAS)
   1941 			nnode.sysctl_alias = qv;
   1942 	} else if (flags & CTLFLAG_IMMEDIATE) {
   1943 		switch (type) {
   1944 		case CTLTYPE_INT:
   1945 			nnode.sysctl_idata = qv;
   1946 			break;
   1947 		case CTLTYPE_QUAD:
   1948 			nnode.sysctl_qdata = qv;
   1949 			break;
   1950 		default:
   1951 			return (EINVAL);
   1952 		}
   1953 	} else {
   1954 		nnode.sysctl_data = newp;
   1955 	}
   1956 	nnode.sysctl_func = func;
   1957 	nnode.sysctl_parent = NULL;
   1958 	nnode.sysctl_ver = 0;
   1959 
   1960 	/*
   1961 	 * initialize lock state -- we need locks if the main tree has
   1962 	 * been marked as complete, but since we could be called from
   1963 	 * either there, or from a device driver (say, at device
   1964 	 * insertion), or from an lkm (at lkm load time, say), we
   1965 	 * don't really want to "wait"...
   1966 	 */
   1967 	error = sysctl_lock(NULL, NULL, 0);
   1968 	if (error)
   1969 		return (error);
   1970 
   1971 	/*
   1972 	 * locate the prospective parent of the new node, and if we
   1973 	 * find it, add the new node.
   1974 	 */
   1975 	sz = sizeof(onode);
   1976 	pnode = root;
   1977 	error = sysctl_locate(NULL, &name[0], namelen - 1, &pnode, &ni);
   1978 	if (error) {
   1979 		printf("sysctl_createv: sysctl_locate(%s) returned %d\n",
   1980 		       nnode.sysctl_name, error);
   1981 		sysctl_unlock(NULL);
   1982 		return (error);
   1983 	}
   1984 	error = sysctl_create(&name[ni], namelen - ni, &onode, &sz,
   1985 			      &nnode, sizeof(nnode), &name[0], NULL,
   1986 			      pnode);
   1987 
   1988 	/*
   1989 	 * unfortunately the node we wanted to create is already
   1990 	 * there.  if the node that's already there is a reasonable
   1991 	 * facsimile of the node we wanted to create, just pretend
   1992 	 * (for the caller's benefit) that we managed to create the
   1993 	 * node they wanted.
   1994 	 */
   1995 	if (error == EEXIST) {
   1996 		/* name is the same as requested... */
   1997 		if (strcmp(nnode.sysctl_name, onode.sysctl_name) == 0 &&
   1998 		    /* they want the same function... */
   1999 		    nnode.sysctl_func == onode.sysctl_func &&
   2000 		    /* number is the same as requested, or... */
   2001 		    (nnode.sysctl_num == onode.sysctl_num ||
   2002 		     /* they didn't pick a number... */
   2003 		     nnode.sysctl_num == CTL_CREATE)) {
   2004 			/*
   2005 			 * collision here from trying to create
   2006 			 * something that already existed; let's give
   2007 			 * our customers a hand and tell them they got
   2008 			 * what they wanted.
   2009 			 */
   2010 #ifdef SYSCTL_DEBUG_CREATE
   2011 			printf("cleared\n");
   2012 #endif /* SYSCTL_DEBUG_CREATE */
   2013 			error = 0;
   2014 		}
   2015 	}
   2016 
   2017 	if (error == 0 &&
   2018 	    (cnode != NULL || log != NULL || descr != NULL)) {
   2019 		/*
   2020 		 * sysctl_create() gave us back a copy of the node,
   2021 		 * but we need to know where it actually is...
   2022 		 */
   2023 		pnode = root;
   2024 		error = sysctl_locate(NULL, &name[0], namelen - 1, &pnode, &ni);
   2025 
   2026 		/*
   2027 		 * manual scan of last layer so that aliased nodes
   2028 		 * aren't followed.
   2029 		 */
   2030 		if (error == 0) {
   2031 			for (ni = 0; ni < pnode->sysctl_clen; ni++)
   2032 				if (pnode->sysctl_child[ni].sysctl_num ==
   2033 				    onode.sysctl_num)
   2034 					break;
   2035 			if (ni < pnode->sysctl_clen)
   2036 				pnode = &pnode->sysctl_child[ni];
   2037 			else
   2038 				error = ENOENT;
   2039 		}
   2040 
   2041 		/*
   2042 		 * not expecting an error here, but...
   2043 		 */
   2044 		if (error == 0) {
   2045 			if (log != NULL)
   2046 				sysctl_log_add(log, pnode);
   2047 			if (cnode != NULL)
   2048 				*cnode = pnode;
   2049 			if (descr != NULL) {
   2050 				/*
   2051 				 * allow first caller to *set* a
   2052 				 * description actually to set it
   2053 				 *
   2054 				 * discard const here so we can attach
   2055 				 * the description
   2056 				 */
   2057 				dnode = __UNCONST(pnode);
   2058 				if (pnode->sysctl_desc != NULL)
   2059 					/* skip it...we've got one */;
   2060 				else if (flags & CTLFLAG_OWNDESC) {
   2061 					size_t l = strlen(descr) + 1;
   2062 					char *d = malloc(l, M_SYSCTLDATA,
   2063 							 M_WAITOK|M_CANFAIL);
   2064 					if (d != NULL) {
   2065 						memcpy(d, descr, l);
   2066 						dnode->sysctl_desc = d;
   2067 						dnode->sysctl_flags |=
   2068 						    CTLFLAG_OWNDESC;
   2069 					}
   2070 				} else
   2071 					dnode->sysctl_desc = descr;
   2072 			}
   2073 		} else {
   2074 			printf("sysctl_create succeeded but node not found?!\n");
   2075 			/*
   2076 			 *  confusing, but the create said it
   2077 			 * succeeded, so...
   2078 			 */
   2079 			error = 0;
   2080 		}
   2081 	}
   2082 
   2083 	/*
   2084 	 * now it should be safe to release the lock state.  note that
   2085 	 * the pointer to the newly created node being passed back may
   2086 	 * not be "good" for very long.
   2087 	 */
   2088 	sysctl_unlock(NULL);
   2089 
   2090 	if (error != 0) {
   2091 		printf("sysctl_createv: sysctl_create(%s) returned %d\n",
   2092 		       nnode.sysctl_name, error);
   2093 #if 0
   2094 		if (error != ENOENT)
   2095 			sysctl_dump(&onode);
   2096 #endif
   2097 	}
   2098 
   2099 	return (error);
   2100 }
   2101 
   2102 int
   2103 sysctl_destroyv(struct sysctlnode *rnode, ...)
   2104 {
   2105 	va_list ap;
   2106 	int error, name[CTL_MAXNAME], namelen, ni;
   2107 	const struct sysctlnode *pnode, *node;
   2108 	struct sysctlnode dnode, *onode;
   2109 	size_t sz;
   2110 
   2111 	va_start(ap, rnode);
   2112 	namelen = 0;
   2113 	ni = 0;
   2114 	do {
   2115 		if (ni == CTL_MAXNAME)
   2116 			return (ENAMETOOLONG);
   2117 		name[ni] = va_arg(ap, int);
   2118 	} while (name[ni++] != CTL_EOL);
   2119 	namelen = ni - 1;
   2120 	va_end(ap);
   2121 
   2122 	/*
   2123 	 * i can't imagine why we'd be destroying a node when the tree
   2124 	 * wasn't complete, but who knows?
   2125 	 */
   2126 	error = sysctl_lock(NULL, NULL, 0);
   2127 	if (error)
   2128 		return (error);
   2129 
   2130 	/*
   2131 	 * where is it?
   2132 	 */
   2133 	node = rnode;
   2134 	error = sysctl_locate(NULL, &name[0], namelen - 1, &node, &ni);
   2135 	if (error) {
   2136 		/* they want it gone and it's not there, so... */
   2137 		sysctl_unlock(NULL);
   2138 		return (error == ENOENT ? 0 : error);
   2139 	}
   2140 
   2141 	/*
   2142 	 * set up the deletion
   2143 	 */
   2144 	pnode = node;
   2145 	node = &dnode;
   2146 	memset(&dnode, 0, sizeof(dnode));
   2147 	dnode.sysctl_flags = SYSCTL_VERSION;
   2148 	dnode.sysctl_num = name[namelen - 1];
   2149 
   2150 	/*
   2151 	 * we found it, now let's nuke it
   2152 	 */
   2153 	name[namelen - 1] = CTL_DESTROY;
   2154 	sz = 0;
   2155 	error = sysctl_destroy(&name[namelen - 1], 1, NULL, &sz,
   2156 			       node, sizeof(*node), &name[0], NULL,
   2157 			       pnode);
   2158 	if (error == ENOTEMPTY) {
   2159 		/*
   2160 		 * think of trying to delete "foo" when "foo.bar"
   2161 		 * (which someone else put there) is still in
   2162 		 * existence
   2163 		 */
   2164 		error = 0;
   2165 
   2166 		/*
   2167 		 * dunno who put the description there, but if this
   2168 		 * node can ever be removed, we need to make sure the
   2169 		 * string doesn't go out of context.  that means we
   2170 		 * need to find the node that's still there (don't use
   2171 		 * sysctl_locate() because that follows aliasing).
   2172 		 */
   2173 		node = pnode->sysctl_child;
   2174 		for (ni = 0; ni < pnode->sysctl_clen; ni++)
   2175 			if (node[ni].sysctl_num == dnode.sysctl_num)
   2176 				break;
   2177 		node = (ni < pnode->sysctl_clen) ? &node[ni] : NULL;
   2178 
   2179 		/*
   2180 		 * if we found it, and this node has a description,
   2181 		 * and this node can be released, and it doesn't
   2182 		 * already own its own description...sigh.  :)
   2183 		 */
   2184 		if (node != NULL && node->sysctl_desc != NULL &&
   2185 		    !(node->sysctl_flags & CTLFLAG_PERMANENT) &&
   2186 		    !(node->sysctl_flags & CTLFLAG_OWNDESC)) {
   2187 			char *d;
   2188 
   2189 			sz = strlen(node->sysctl_desc) + 1;
   2190 			d = malloc(sz, M_SYSCTLDATA, M_WAITOK|M_CANFAIL);
   2191 			if (d != NULL) {
   2192 				/*
   2193 				 * discard const so that we can
   2194 				 * re-attach the description
   2195 				 */
   2196 				memcpy(d, node->sysctl_desc, sz);
   2197 				onode = __UNCONST(node);
   2198 				onode->sysctl_desc = d;
   2199 				onode->sysctl_flags |= CTLFLAG_OWNDESC;
   2200 			} else {
   2201 				/*
   2202 				 * XXX drop the description?  be
   2203 				 * afraid?  don't care?
   2204 				 */
   2205 			}
   2206 		}
   2207 	}
   2208 
   2209         sysctl_unlock(NULL);
   2210 
   2211 	return (error);
   2212 }
   2213 
   2214 #if 0
   2215 /*
   2216  * ********************************************************************
   2217  * the dump routine.  i haven't yet decided how (if at all) i'll call
   2218  * this from userland when it's in the kernel.
   2219  * ********************************************************************
   2220  */
   2221 static const char *
   2222 sf(int f)
   2223 {
   2224 	static char s[256];
   2225 	char *c;
   2226 
   2227 	s[0] = '\0';
   2228 	c = "";
   2229 
   2230 #define print_flag(_f, _s, _c, _q, _x) \
   2231 	if (((_f) & (__CONCAT(CTLFLAG_,_x))) == (__CONCAT(CTLFLAG_,_q))) { \
   2232 		strlcat((_s), (_c), sizeof(_s)); \
   2233 		strlcat((_s), __STRING(_q), sizeof(_s)); \
   2234 		(_c) = ","; \
   2235 		(_f) &= ~__CONCAT(CTLFLAG_,_x); \
   2236 	}
   2237 
   2238 	print_flag(f, s, c, READONLY,  READWRITE);
   2239 	print_flag(f, s, c, READWRITE, READWRITE);
   2240 	print_flag(f, s, c, ANYWRITE,  ANYWRITE);
   2241 	print_flag(f, s, c, PRIVATE,   PRIVATE);
   2242 	print_flag(f, s, c, PERMANENT, PERMANENT);
   2243 	print_flag(f, s, c, OWNDATA,   OWNDATA);
   2244 	print_flag(f, s, c, IMMEDIATE, IMMEDIATE);
   2245 	print_flag(f, s, c, HEX,       HEX);
   2246 	print_flag(f, s, c, ROOT,      ROOT);
   2247 	print_flag(f, s, c, ANYNUMBER, ANYNUMBER);
   2248 	print_flag(f, s, c, HIDDEN,    HIDDEN);
   2249 	print_flag(f, s, c, ALIAS,     ALIAS);
   2250 #undef print_flag
   2251 
   2252 	if (f) {
   2253 		char foo[9];
   2254 		snprintf(foo, sizeof(foo), "%x", f);
   2255 		strlcat(s, c, sizeof(s));
   2256 		strlcat(s, foo, sizeof(s));
   2257 	}
   2258 
   2259 	return (s);
   2260 }
   2261 
   2262 static const char *
   2263 st(int t)
   2264 {
   2265 
   2266 	switch (t) {
   2267 	case CTLTYPE_NODE:
   2268 		return "NODE";
   2269 	case CTLTYPE_INT:
   2270 		return "INT";
   2271 	case CTLTYPE_STRING:
   2272 		return "STRING";
   2273 	case CTLTYPE_QUAD:
   2274 		return "QUAD";
   2275 	case CTLTYPE_STRUCT:
   2276 		return "STRUCT";
   2277 	}
   2278 
   2279 	return "???";
   2280 }
   2281 
   2282 void
   2283 sysctl_dump(const struct sysctlnode *d)
   2284 {
   2285 	static char nmib[64], smib[256];
   2286 	static int indent;
   2287 	struct sysctlnode *n;
   2288 	char *np, *sp, tmp[20];
   2289 	int i;
   2290 
   2291 	if (d == NULL)
   2292 		return;
   2293 
   2294 	np = &nmib[strlen(nmib)];
   2295 	sp = &smib[strlen(smib)];
   2296 
   2297 	if (!(d->sysctl_flags & CTLFLAG_ROOT)) {
   2298 		snprintf(tmp, sizeof(tmp), "%d", d->sysctl_num);
   2299 		strcat(nmib, ".");
   2300 		strcat(smib, ".");
   2301 		strcat(nmib, tmp);
   2302 		strcat(smib, d->sysctl_name);
   2303 		printf("%s -> %s (%d)\n", &nmib[1], &smib[1],
   2304 		       SYSCTL_TYPE(d->sysctl_flags));
   2305 	}
   2306 
   2307 	if (1) {
   2308 		printf("%*s%p:\tsysctl_name  [%s]\n", indent, "",
   2309 		       d, d->sysctl_name);
   2310 		printf("%*s\t\tsysctl_num    %d\n",   indent, "",
   2311 		       d->sysctl_num);
   2312 		printf("%*s\t\tsysctl_flags  %x (flags=%x<%s> type=%d<%s> "
   2313 		       "size=%zu)\n",
   2314 		       indent, "", d->sysctl_flags,
   2315 		       SYSCTL_FLAGS(d->sysctl_flags),
   2316 		       sf(SYSCTL_FLAGS(d->sysctl_flags)),
   2317 		       SYSCTL_TYPE(d->sysctl_flags),
   2318 		       st(SYSCTL_TYPE(d->sysctl_flags)),
   2319 		       d->sysctl_size);
   2320 		if (SYSCTL_TYPE(d->sysctl_flags) == CTLTYPE_NODE) {
   2321 			printf("%*s\t\tsysctl_csize  %d\n",   indent, "",
   2322 			       d->sysctl_csize);
   2323 			printf("%*s\t\tsysctl_clen   %d\n",   indent, "",
   2324 			       d->sysctl_clen);
   2325 			printf("%*s\t\tsysctl_child  %p\n",   indent, "",
   2326 			       d->sysctl_child);
   2327 		} else
   2328 			printf("%*s\t\tsysctl_data   %p\n",   indent, "",
   2329 			       d->sysctl_data);
   2330 		printf("%*s\t\tsysctl_func   %p\n",   indent, "",
   2331 		       d->sysctl_func);
   2332 		printf("%*s\t\tsysctl_parent %p\n",   indent, "",
   2333 		       d->sysctl_parent);
   2334 		printf("%*s\t\tsysctl_ver    %d\n",   indent, "",
   2335 		       d->sysctl_ver);
   2336 	}
   2337 
   2338 	if (SYSCTL_TYPE(d->sysctl_flags) == CTLTYPE_NODE) {
   2339 		indent += 8;
   2340 		n = d->sysctl_child;
   2341 		for (i = 0; i < d->sysctl_clen; i++) {
   2342 			sysctl_dump(&n[i]);
   2343 		}
   2344 		indent -= 8;
   2345 	}
   2346 
   2347 	np[0] = '\0';
   2348 	sp[0] = '\0';
   2349 }
   2350 #endif /* 0 */
   2351 
   2352 /*
   2353  * ********************************************************************
   2354  * Deletes an entire n-ary tree.  Not recommended unless you know why
   2355  * you're doing it.  Personally, I don't know why you'd even think
   2356  * about it.
   2357  * ********************************************************************
   2358  */
   2359 void
   2360 sysctl_free(struct sysctlnode *rnode)
   2361 {
   2362 	struct sysctlnode *node, *pnode;
   2363 
   2364 	if (rnode == NULL)
   2365 		rnode = &sysctl_root;
   2366 
   2367 	if (SYSCTL_VERS(rnode->sysctl_flags) != SYSCTL_VERSION) {
   2368 		printf("sysctl_free: rnode %p wrong version\n", rnode);
   2369 		return;
   2370 	}
   2371 
   2372 	pnode = rnode;
   2373 
   2374 	node = pnode->sysctl_child;
   2375 	do {
   2376 		while (node != NULL && pnode->sysctl_csize > 0) {
   2377 			while (node <
   2378 			       &pnode->sysctl_child[pnode->sysctl_clen] &&
   2379 			       (SYSCTL_TYPE(node->sysctl_flags) !=
   2380 				CTLTYPE_NODE ||
   2381 				node->sysctl_csize == 0)) {
   2382 				if (SYSCTL_FLAGS(node->sysctl_flags) &
   2383 				    CTLFLAG_OWNDATA) {
   2384 					if (node->sysctl_data != NULL) {
   2385 						free(node->sysctl_data,
   2386 						     M_SYSCTLDATA);
   2387 						node->sysctl_data = NULL;
   2388 					}
   2389 				}
   2390 				if (SYSCTL_FLAGS(node->sysctl_flags) &
   2391 				    CTLFLAG_OWNDESC) {
   2392 					if (node->sysctl_desc != NULL) {
   2393 						/*XXXUNCONST*/
   2394 						free(__UNCONST(node->sysctl_desc),
   2395 						     M_SYSCTLDATA);
   2396 						node->sysctl_desc = NULL;
   2397 					}
   2398 				}
   2399 				node++;
   2400 			}
   2401 			if (node < &pnode->sysctl_child[pnode->sysctl_clen]) {
   2402 				pnode = node;
   2403 				node = node->sysctl_child;
   2404 			} else
   2405 				break;
   2406 		}
   2407 		if (pnode->sysctl_child != NULL)
   2408 			free(pnode->sysctl_child, M_SYSCTLNODE);
   2409 		pnode->sysctl_clen = 0;
   2410 		pnode->sysctl_csize = 0;
   2411 		pnode->sysctl_child = NULL;
   2412 		node = pnode;
   2413 		pnode = node->sysctl_parent;
   2414 	} while (pnode != NULL && node != rnode);
   2415 }
   2416 
   2417 int
   2418 sysctl_log_add(struct sysctllog **logp, const struct sysctlnode *node)
   2419 {
   2420 	int name[CTL_MAXNAME], namelen, i;
   2421 	const struct sysctlnode *pnode;
   2422 	struct sysctllog *log;
   2423 
   2424 	if (node->sysctl_flags & CTLFLAG_PERMANENT)
   2425 		return (0);
   2426 
   2427 	if (logp == NULL)
   2428 		return (0);
   2429 
   2430 	if (*logp == NULL) {
   2431 		log = malloc(sizeof(struct sysctllog),
   2432 		       M_SYSCTLDATA, M_WAITOK|M_CANFAIL);
   2433 		if (log == NULL) {
   2434 			/* XXX print error message? */
   2435 			return (-1);
   2436 		}
   2437 		log->log_num = malloc(16 * sizeof(int),
   2438 		       M_SYSCTLDATA, M_WAITOK|M_CANFAIL);
   2439 		if (log->log_num == NULL) {
   2440 			/* XXX print error message? */
   2441 			free(log, M_SYSCTLDATA);
   2442 			return (-1);
   2443 		}
   2444 		memset(log->log_num, 0, 16 * sizeof(int));
   2445 		log->log_root = NULL;
   2446 		log->log_size = 16;
   2447 		log->log_left = 16;
   2448 		*logp = log;
   2449 	} else
   2450 		log = *logp;
   2451 
   2452 	/*
   2453 	 * check that the root is proper.  it's okay to record the
   2454 	 * address of the root of a tree.  it's the only thing that's
   2455 	 * guaranteed not to shift around as nodes come and go.
   2456 	 */
   2457 	if (log->log_root == NULL)
   2458 		log->log_root = sysctl_rootof(node);
   2459 	else if (log->log_root != sysctl_rootof(node)) {
   2460 		printf("sysctl: log %p root mismatch (%p)\n",
   2461 		       log->log_root, sysctl_rootof(node));
   2462 		return (-1);
   2463 	}
   2464 
   2465 	/*
   2466 	 * we will copy out name in reverse order
   2467 	 */
   2468 	for (pnode = node, namelen = 0;
   2469 	     pnode != NULL && !(pnode->sysctl_flags & CTLFLAG_ROOT);
   2470 	     pnode = pnode->sysctl_parent)
   2471 		name[namelen++] = pnode->sysctl_num;
   2472 
   2473 	/*
   2474 	 * do we have space?
   2475 	 */
   2476 	if (log->log_left < (namelen + 3))
   2477 		sysctl_log_realloc(log);
   2478 	if (log->log_left < (namelen + 3))
   2479 		return (-1);
   2480 
   2481 	/*
   2482 	 * stuff name in, then namelen, then node type, and finally,
   2483 	 * the version for non-node nodes.
   2484 	 */
   2485 	for (i = 0; i < namelen; i++)
   2486 		log->log_num[--log->log_left] = name[i];
   2487 	log->log_num[--log->log_left] = namelen;
   2488 	log->log_num[--log->log_left] = SYSCTL_TYPE(node->sysctl_flags);
   2489 	if (log->log_num[log->log_left] != CTLTYPE_NODE)
   2490 		log->log_num[--log->log_left] = node->sysctl_ver;
   2491 	else
   2492 		log->log_num[--log->log_left] = 0;
   2493 
   2494 	return (0);
   2495 }
   2496 
   2497 void
   2498 sysctl_teardown(struct sysctllog **logp)
   2499 {
   2500 	const struct sysctlnode *rnode;
   2501 	struct sysctlnode node;
   2502 	struct sysctllog *log;
   2503 	uint namelen;
   2504 	int *name, t, v, error, ni;
   2505 	size_t sz;
   2506 
   2507 	if (logp == NULL || *logp == NULL)
   2508 		return;
   2509 	log = *logp;
   2510 
   2511 	error = sysctl_lock(NULL, NULL, 0);
   2512 	if (error)
   2513 		return;
   2514 
   2515 	memset(&node, 0, sizeof(node));
   2516 
   2517 	while (log->log_left < log->log_size) {
   2518 		KASSERT((log->log_left + 3 < log->log_size) &&
   2519 			(log->log_left + log->log_num[log->log_left + 2] <=
   2520 			 log->log_size));
   2521 		v = log->log_num[log->log_left++];
   2522 		t = log->log_num[log->log_left++];
   2523 		namelen = log->log_num[log->log_left++];
   2524 		name = &log->log_num[log->log_left];
   2525 
   2526 		node.sysctl_num = name[namelen - 1];
   2527 		node.sysctl_flags = SYSCTL_VERSION|t;
   2528 		node.sysctl_ver = v;
   2529 
   2530 		rnode = log->log_root;
   2531 		error = sysctl_locate(NULL, &name[0], namelen, &rnode, &ni);
   2532 		if (error == 0) {
   2533 			name[namelen - 1] = CTL_DESTROY;
   2534 			rnode = rnode->sysctl_parent;
   2535 			sz = 0;
   2536 			(void)sysctl_destroy(&name[namelen - 1], 1, NULL,
   2537 					     &sz, &node, sizeof(node),
   2538 					     &name[0], NULL, rnode);
   2539 		}
   2540 
   2541 		log->log_left += namelen;
   2542 	}
   2543 
   2544 	KASSERT(log->log_size == log->log_left);
   2545 	free(log->log_num, M_SYSCTLDATA);
   2546 	free(log, M_SYSCTLDATA);
   2547 	*logp = NULL;
   2548 
   2549 	sysctl_unlock(NULL);
   2550 }
   2551 
   2552 /*
   2553  * ********************************************************************
   2554  * old_sysctl -- A routine to bridge old-style internal calls to the
   2555  * new infrastructure.
   2556  * ********************************************************************
   2557  */
   2558 int
   2559 old_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp,
   2560 	   void *newp, size_t newlen, struct lwp *l)
   2561 {
   2562 	int error;
   2563 	size_t oldlen = 0;
   2564 	size_t savelen;
   2565 
   2566 	if (oldlenp) {
   2567 		oldlen = *oldlenp;
   2568 	}
   2569 	savelen = oldlen;
   2570 
   2571 	error = sysctl_lock(l, oldp, savelen);
   2572 	if (error)
   2573 		return (error);
   2574 	error = sysctl_dispatch(name, namelen, oldp, &oldlen,
   2575 				newp, newlen, name, l, NULL);
   2576 	sysctl_unlock(l);
   2577 	if (error == 0 && oldp != NULL && savelen < oldlen)
   2578 		error = ENOMEM;
   2579 
   2580 	if (oldlenp) {
   2581 		*oldlenp = oldlen;
   2582 	}
   2583 
   2584 	return (error);
   2585 }
   2586 
   2587 /*
   2588  * ********************************************************************
   2589  * Section 4: Generic helper routines
   2590  * ********************************************************************
   2591  * "helper" routines that can do more finely grained access control,
   2592  * construct structures from disparate information, create the
   2593  * appearance of more nodes and sub-trees, etc.  for example, if
   2594  * CTL_PROC wanted a helper function, it could respond to a CTL_QUERY
   2595  * with a dynamically created list of nodes that represented the
   2596  * currently running processes at that instant.
   2597  * ********************************************************************
   2598  */
   2599 
   2600 /*
   2601  * first, a few generic helpers that provide:
   2602  *
   2603  * sysctl_needfunc()		a readonly interface that emits a warning
   2604  * sysctl_notavail()		returns EOPNOTSUPP (generic error)
   2605  * sysctl_null()		an empty return buffer with no error
   2606  */
   2607 int
   2608 sysctl_needfunc(SYSCTLFN_ARGS)
   2609 {
   2610 	int error;
   2611 
   2612 	printf("!!SYSCTL_NEEDFUNC!!\n");
   2613 
   2614 	if (newp != NULL || namelen != 0)
   2615 		return (EOPNOTSUPP);
   2616 
   2617 	error = 0;
   2618 	if (oldp != NULL)
   2619 		error = sysctl_copyout(l, rnode->sysctl_data, oldp,
   2620 				       MIN(rnode->sysctl_size, *oldlenp));
   2621 	*oldlenp = rnode->sysctl_size;
   2622 
   2623 	return (error);
   2624 }
   2625 
   2626 int
   2627 sysctl_notavail(SYSCTLFN_ARGS)
   2628 {
   2629 
   2630 	if (namelen == 1 && name[0] == CTL_QUERY)
   2631 		return (sysctl_query(SYSCTLFN_CALL(rnode)));
   2632 
   2633 	return (EOPNOTSUPP);
   2634 }
   2635 
   2636 int
   2637 sysctl_null(SYSCTLFN_ARGS)
   2638 {
   2639 
   2640 	*oldlenp = 0;
   2641 
   2642 	return (0);
   2643 }
   2644 
   2645 /*
   2646  * ********************************************************************
   2647  * Section 5: The machinery that makes it all go
   2648  * ********************************************************************
   2649  * Memory "manglement" routines.  Not much to this, eh?
   2650  * ********************************************************************
   2651  */
   2652 static int
   2653 sysctl_alloc(struct sysctlnode *p, int x)
   2654 {
   2655 	int i;
   2656 	struct sysctlnode *n;
   2657 
   2658 	assert(p->sysctl_child == NULL);
   2659 
   2660 	if (x == 1)
   2661 		n = malloc(sizeof(struct sysctlnode),
   2662 		       M_SYSCTLNODE, M_WAITOK|M_CANFAIL);
   2663 	else
   2664 		n = malloc(SYSCTL_DEFSIZE * sizeof(struct sysctlnode),
   2665 		       M_SYSCTLNODE, M_WAITOK|M_CANFAIL);
   2666 	if (n == NULL)
   2667 		return (ENOMEM);
   2668 
   2669 	if (x == 1) {
   2670 		memset(n, 0, sizeof(struct sysctlnode));
   2671 		p->sysctl_csize = 1;
   2672 	} else {
   2673 		memset(n, 0, SYSCTL_DEFSIZE * sizeof(struct sysctlnode));
   2674 		p->sysctl_csize = SYSCTL_DEFSIZE;
   2675 	}
   2676 	p->sysctl_clen = 0;
   2677 
   2678 	for (i = 0; i < p->sysctl_csize; i++)
   2679 		n[i].sysctl_parent = p;
   2680 
   2681 	p->sysctl_child = n;
   2682 	return (0);
   2683 }
   2684 
   2685 static int
   2686 sysctl_realloc(struct sysctlnode *p)
   2687 {
   2688 	int i, j;
   2689 	struct sysctlnode *n;
   2690 
   2691 	assert(p->sysctl_csize == p->sysctl_clen);
   2692 
   2693 	/*
   2694 	 * how many do we have...how many should we make?
   2695 	 */
   2696 	i = p->sysctl_clen;
   2697 	n = malloc(2 * i * sizeof(struct sysctlnode), M_SYSCTLNODE,
   2698 		   M_WAITOK|M_CANFAIL);
   2699 	if (n == NULL)
   2700 		return (ENOMEM);
   2701 
   2702 	/*
   2703 	 * move old children over...initialize new children
   2704 	 */
   2705 	memcpy(n, p->sysctl_child, i * sizeof(struct sysctlnode));
   2706 	memset(&n[i], 0, i * sizeof(struct sysctlnode));
   2707 	p->sysctl_csize = 2 * i;
   2708 
   2709 	/*
   2710 	 * reattach moved (and new) children to parent; if a moved
   2711 	 * child node has children, reattach the parent pointers of
   2712 	 * grandchildren
   2713 	 */
   2714         for (i = 0; i < p->sysctl_csize; i++) {
   2715                 n[i].sysctl_parent = p;
   2716 		if (n[i].sysctl_child != NULL) {
   2717 			for (j = 0; j < n[i].sysctl_csize; j++)
   2718 				n[i].sysctl_child[j].sysctl_parent = &n[i];
   2719 		}
   2720 	}
   2721 
   2722 	/*
   2723 	 * get out with the old and in with the new
   2724 	 */
   2725 	free(p->sysctl_child, M_SYSCTLNODE);
   2726 	p->sysctl_child = n;
   2727 
   2728 	return (0);
   2729 }
   2730 
   2731 static int
   2732 sysctl_log_realloc(struct sysctllog *log)
   2733 {
   2734 	int *n, s, d;
   2735 
   2736 	s = log->log_size * 2;
   2737 	d = log->log_size;
   2738 
   2739 	n = malloc(s * sizeof(int), M_SYSCTLDATA, M_WAITOK|M_CANFAIL);
   2740 	if (n == NULL)
   2741 		return (-1);
   2742 
   2743 	memset(n, 0, s * sizeof(int));
   2744 	memcpy(&n[d], log->log_num, d * sizeof(int));
   2745 	free(log->log_num, M_SYSCTLDATA);
   2746 	log->log_num = n;
   2747 	if (d)
   2748 		log->log_left += d;
   2749 	else
   2750 		log->log_left = s;
   2751 	log->log_size = s;
   2752 
   2753 	return (0);
   2754 }
   2755 
   2756 /*
   2757  * ********************************************************************
   2758  * Section 6: Conversion between API versions wrt the sysctlnode
   2759  * ********************************************************************
   2760  */
   2761 static int
   2762 sysctl_cvt_in(struct lwp *l, int *vp, const void *i, size_t sz,
   2763 	      struct sysctlnode *node)
   2764 {
   2765 	int error, flags;
   2766 
   2767 	if (i == NULL || sz < sizeof(flags))
   2768 		return (EINVAL);
   2769 
   2770 	error = sysctl_copyin(l, i, &flags, sizeof(flags));
   2771 	if (error)
   2772 		return (error);
   2773 
   2774 #if (SYSCTL_VERSION != SYSCTL_VERS_1)
   2775 #error sysctl_cvt_in: no support for SYSCTL_VERSION
   2776 #endif /*  (SYSCTL_VERSION != SYSCTL_VERS_1) */
   2777 
   2778 	if (sz == sizeof(*node) &&
   2779 	    SYSCTL_VERS(flags) == SYSCTL_VERSION) {
   2780 		error = sysctl_copyin(l, i, node, sizeof(*node));
   2781 		if (error)
   2782 			return (error);
   2783 		*vp = SYSCTL_VERSION;
   2784 		return (0);
   2785 	}
   2786 
   2787 	return (EINVAL);
   2788 }
   2789 
   2790 static int
   2791 sysctl_cvt_out(struct lwp *l, int v, const struct sysctlnode *i,
   2792 	       void *ovp, size_t left, size_t *szp)
   2793 {
   2794 	size_t sz = sizeof(*i);
   2795 	const void *src = i;
   2796 	int error;
   2797 
   2798 	switch (v) {
   2799 	case SYSCTL_VERS_0:
   2800 		return (EINVAL);
   2801 
   2802 #if (SYSCTL_VERSION != SYSCTL_VERS_1)
   2803 #error sysctl_cvt_out: no support for SYSCTL_VERSION
   2804 #endif /*  (SYSCTL_VERSION != SYSCTL_VERS_1) */
   2805 
   2806 	case SYSCTL_VERSION:
   2807 		/* nothing more to do here */
   2808 		break;
   2809 	}
   2810 
   2811 	if (ovp != NULL && left >= sz) {
   2812 		error = sysctl_copyout(l, src, ovp, sz);
   2813 		if (error)
   2814 			return (error);
   2815 	}
   2816 
   2817 	if (szp != NULL)
   2818 		*szp = sz;
   2819 
   2820 	return (0);
   2821 }
   2822