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