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