xref: /freebsd-13-stable/sys/kern/kern_sysctl.c (revision dcd7286d902774428c08b179a72bfdcd4556ec06)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Mike Karels at Berkeley Software Design, Inc.
9  *
10  * Quite extensively rewritten by Poul-Henning Kamp of the FreeBSD
11  * project, to make these variables more userfriendly.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  * 3. Neither the name of the University nor the names of its contributors
22  *    may be used to endorse or promote products derived from this software
23  *    without specific prior written permission.
24  *
25  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
26  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
28  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
29  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
31  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
32  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
33  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
34  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35  * SUCH DAMAGE.
36  *
37  *	@(#)kern_sysctl.c	8.4 (Berkeley) 4/14/94
38  */
39 
40 #include <sys/cdefs.h>
41 #include "opt_capsicum.h"
42 #include "opt_ddb.h"
43 #include "opt_ktrace.h"
44 #include "opt_sysctl.h"
45 
46 #include <sys/param.h>
47 #include <sys/fail.h>
48 #include <sys/systm.h>
49 #include <sys/capsicum.h>
50 #include <sys/kernel.h>
51 #include <sys/limits.h>
52 #include <sys/sysctl.h>
53 #include <sys/malloc.h>
54 #include <sys/priv.h>
55 #include <sys/proc.h>
56 #include <sys/jail.h>
57 #include <sys/kdb.h>
58 #include <sys/lock.h>
59 #include <sys/mutex.h>
60 #include <sys/rmlock.h>
61 #include <sys/sbuf.h>
62 #include <sys/sx.h>
63 #include <sys/sysproto.h>
64 #include <sys/uio.h>
65 #ifdef KTRACE
66 #include <sys/ktrace.h>
67 #endif
68 
69 #ifdef DDB
70 #include <ddb/ddb.h>
71 #include <ddb/db_lex.h>
72 #endif
73 
74 #include <net/vnet.h>
75 
76 #include <security/mac/mac_framework.h>
77 
78 #include <vm/vm.h>
79 #include <vm/vm_extern.h>
80 
81 static MALLOC_DEFINE(M_SYSCTL, "sysctl", "sysctl internal magic");
82 static MALLOC_DEFINE(M_SYSCTLOID, "sysctloid", "sysctl dynamic oids");
83 static MALLOC_DEFINE(M_SYSCTLTMP, "sysctltmp", "sysctl temp output buffer");
84 
85 /*
86  * The sysctllock protects the MIB tree.  It also protects sysctl
87  * contexts used with dynamic sysctls.  The sysctl_register_oid() and
88  * sysctl_unregister_oid() routines require the sysctllock to already
89  * be held, so the sysctl_wlock() and sysctl_wunlock() routines are
90  * provided for the few places in the kernel which need to use that
91  * API rather than using the dynamic API.  Use of the dynamic API is
92  * strongly encouraged for most code.
93  *
94  * The sysctlmemlock is used to limit the amount of user memory wired for
95  * sysctl requests.  This is implemented by serializing any userland
96  * sysctl requests larger than a single page via an exclusive lock.
97  *
98  * The sysctlstringlock is used to protect concurrent access to writable
99  * string nodes in sysctl_handle_string().
100  */
101 static struct rmlock sysctllock;
102 static struct sx __exclusive_cache_line sysctlmemlock;
103 static struct sx sysctlstringlock;
104 
105 #define	SYSCTL_WLOCK()		rm_wlock(&sysctllock)
106 #define	SYSCTL_WUNLOCK()	rm_wunlock(&sysctllock)
107 #define	SYSCTL_RLOCK(tracker)	rm_rlock(&sysctllock, (tracker))
108 #define	SYSCTL_RUNLOCK(tracker)	rm_runlock(&sysctllock, (tracker))
109 #define	SYSCTL_WLOCKED()	rm_wowned(&sysctllock)
110 #define	SYSCTL_ASSERT_LOCKED()	rm_assert(&sysctllock, RA_LOCKED)
111 #define	SYSCTL_ASSERT_WLOCKED()	rm_assert(&sysctllock, RA_WLOCKED)
112 #define	SYSCTL_ASSERT_RLOCKED()	rm_assert(&sysctllock, RA_RLOCKED)
113 #define	SYSCTL_INIT()		rm_init_flags(&sysctllock, "sysctl lock", \
114 				    RM_SLEEPABLE)
115 #define	SYSCTL_SLEEP(ch, wmesg, timo)					\
116 				rm_sleep(ch, &sysctllock, 0, wmesg, timo)
117 
118 static int sysctl_root(SYSCTL_HANDLER_ARGS);
119 
120 /* Root list */
121 struct sysctl_oid_list sysctl__children = SLIST_HEAD_INITIALIZER(&sysctl__children);
122 
123 static char*	sysctl_escape_name(const char*);
124 static int	sysctl_remove_oid_locked(struct sysctl_oid *oidp, int del,
125 		    int recurse);
126 static int	sysctl_old_kernel(struct sysctl_req *, const void *, size_t);
127 static int	sysctl_new_kernel(struct sysctl_req *, void *, size_t);
128 static int	name2oid(const char *, int *, int *, struct sysctl_oid **);
129 
130 static struct sysctl_oid *
sysctl_find_oidname(const char * name,struct sysctl_oid_list * list)131 sysctl_find_oidname(const char *name, struct sysctl_oid_list *list)
132 {
133 	struct sysctl_oid *oidp;
134 
135 	SYSCTL_ASSERT_LOCKED();
136 	SYSCTL_FOREACH(oidp, list) {
137 		if (strcmp(oidp->oid_name, name) == 0) {
138 			return (oidp);
139 		}
140 	}
141 	return (NULL);
142 }
143 
144 static struct sysctl_oid *
sysctl_find_oidnamelen(const char * name,size_t len,struct sysctl_oid_list * list)145 sysctl_find_oidnamelen(const char *name, size_t len,
146     struct sysctl_oid_list *list)
147 {
148 	struct sysctl_oid *oidp;
149 
150 	SYSCTL_ASSERT_LOCKED();
151 	SYSCTL_FOREACH(oidp, list) {
152 		if (strncmp(oidp->oid_name, name, len) == 0 &&
153 		    oidp->oid_name[len] == '\0')
154 			return (oidp);
155 	}
156 	return (NULL);
157 }
158 
159 /*
160  * Initialization of the MIB tree.
161  *
162  * Order by number in each list.
163  */
164 void
sysctl_wlock(void)165 sysctl_wlock(void)
166 {
167 
168 	SYSCTL_WLOCK();
169 }
170 
171 void
sysctl_wunlock(void)172 sysctl_wunlock(void)
173 {
174 
175 	SYSCTL_WUNLOCK();
176 }
177 
178 static int
sysctl_root_handler_locked(struct sysctl_oid * oid,void * arg1,intmax_t arg2,struct sysctl_req * req,struct rm_priotracker * tracker)179 sysctl_root_handler_locked(struct sysctl_oid *oid, void *arg1, intmax_t arg2,
180     struct sysctl_req *req, struct rm_priotracker *tracker)
181 {
182 	int error;
183 
184 	if (oid->oid_kind & CTLFLAG_DYN)
185 		atomic_add_int(&oid->oid_running, 1);
186 
187 	if (tracker != NULL)
188 		SYSCTL_RUNLOCK(tracker);
189 	else
190 		SYSCTL_WUNLOCK();
191 
192 	/*
193 	 * Treat set CTLFLAG_NEEDGIANT and unset CTLFLAG_MPSAFE flags the same,
194 	 * untill we're ready to remove all traces of Giant from sysctl(9).
195 	 */
196 	if ((oid->oid_kind & CTLFLAG_NEEDGIANT) ||
197 	    (!(oid->oid_kind & CTLFLAG_MPSAFE)))
198 		mtx_lock(&Giant);
199 	error = oid->oid_handler(oid, arg1, arg2, req);
200 	if ((oid->oid_kind & CTLFLAG_NEEDGIANT) ||
201 	    (!(oid->oid_kind & CTLFLAG_MPSAFE)))
202 		mtx_unlock(&Giant);
203 
204 	KFAIL_POINT_ERROR(_debug_fail_point, sysctl_running, error);
205 
206 	if (tracker != NULL)
207 		SYSCTL_RLOCK(tracker);
208 	else
209 		SYSCTL_WLOCK();
210 
211 	if (oid->oid_kind & CTLFLAG_DYN) {
212 		if (atomic_fetchadd_int(&oid->oid_running, -1) == 1 &&
213 		    (oid->oid_kind & CTLFLAG_DYING) != 0)
214 			wakeup(&oid->oid_running);
215 	}
216 
217 	return (error);
218 }
219 
220 static void
sysctl_load_tunable_by_oid_locked(struct sysctl_oid * oidp)221 sysctl_load_tunable_by_oid_locked(struct sysctl_oid *oidp)
222 {
223 	struct sysctl_req req;
224 	struct sysctl_oid *curr;
225 	char *penv = NULL;
226 	char path[96];
227 	ssize_t rem = sizeof(path);
228 	ssize_t len;
229 	uint8_t data[512] __aligned(sizeof(uint64_t));
230 	int size;
231 	int error;
232 
233 	path[--rem] = 0;
234 
235 	for (curr = oidp; curr != NULL; curr = SYSCTL_PARENT(curr)) {
236 		len = strlen(curr->oid_name);
237 		rem -= len;
238 		if (curr != oidp)
239 			rem -= 1;
240 		if (rem < 0) {
241 			printf("OID path exceeds %d bytes\n", (int)sizeof(path));
242 			return;
243 		}
244 		memcpy(path + rem, curr->oid_name, len);
245 		if (curr != oidp)
246 			path[rem + len] = '.';
247 	}
248 
249 	memset(&req, 0, sizeof(req));
250 
251 	req.td = curthread;
252 	req.oldfunc = sysctl_old_kernel;
253 	req.newfunc = sysctl_new_kernel;
254 	req.lock = REQ_UNWIRED;
255 
256 	switch (oidp->oid_kind & CTLTYPE) {
257 	case CTLTYPE_INT:
258 		if (getenv_array(path + rem, data, sizeof(data), &size,
259 		    sizeof(int), GETENV_SIGNED) == 0)
260 			return;
261 		req.newlen = size;
262 		req.newptr = data;
263 		break;
264 	case CTLTYPE_UINT:
265 		if (getenv_array(path + rem, data, sizeof(data), &size,
266 		    sizeof(int), GETENV_UNSIGNED) == 0)
267 			return;
268 		req.newlen = size;
269 		req.newptr = data;
270 		break;
271 	case CTLTYPE_LONG:
272 		if (getenv_array(path + rem, data, sizeof(data), &size,
273 		    sizeof(long), GETENV_SIGNED) == 0)
274 			return;
275 		req.newlen = size;
276 		req.newptr = data;
277 		break;
278 	case CTLTYPE_ULONG:
279 		if (getenv_array(path + rem, data, sizeof(data), &size,
280 		    sizeof(long), GETENV_UNSIGNED) == 0)
281 			return;
282 		req.newlen = size;
283 		req.newptr = data;
284 		break;
285 	case CTLTYPE_S8:
286 		if (getenv_array(path + rem, data, sizeof(data), &size,
287 		    sizeof(int8_t), GETENV_SIGNED) == 0)
288 			return;
289 		req.newlen = size;
290 		req.newptr = data;
291 		break;
292 	case CTLTYPE_S16:
293 		if (getenv_array(path + rem, data, sizeof(data), &size,
294 		    sizeof(int16_t), GETENV_SIGNED) == 0)
295 			return;
296 		req.newlen = size;
297 		req.newptr = data;
298 		break;
299 	case CTLTYPE_S32:
300 		if (getenv_array(path + rem, data, sizeof(data), &size,
301 		    sizeof(int32_t), GETENV_SIGNED) == 0)
302 			return;
303 		req.newlen = size;
304 		req.newptr = data;
305 		break;
306 	case CTLTYPE_S64:
307 		if (getenv_array(path + rem, data, sizeof(data), &size,
308 		    sizeof(int64_t), GETENV_SIGNED) == 0)
309 			return;
310 		req.newlen = size;
311 		req.newptr = data;
312 		break;
313 	case CTLTYPE_U8:
314 		if (getenv_array(path + rem, data, sizeof(data), &size,
315 		    sizeof(uint8_t), GETENV_UNSIGNED) == 0)
316 			return;
317 		req.newlen = size;
318 		req.newptr = data;
319 		break;
320 	case CTLTYPE_U16:
321 		if (getenv_array(path + rem, data, sizeof(data), &size,
322 		    sizeof(uint16_t), GETENV_UNSIGNED) == 0)
323 			return;
324 		req.newlen = size;
325 		req.newptr = data;
326 		break;
327 	case CTLTYPE_U32:
328 		if (getenv_array(path + rem, data, sizeof(data), &size,
329 		    sizeof(uint32_t), GETENV_UNSIGNED) == 0)
330 			return;
331 		req.newlen = size;
332 		req.newptr = data;
333 		break;
334 	case CTLTYPE_U64:
335 		if (getenv_array(path + rem, data, sizeof(data), &size,
336 		    sizeof(uint64_t), GETENV_UNSIGNED) == 0)
337 			return;
338 		req.newlen = size;
339 		req.newptr = data;
340 		break;
341 	case CTLTYPE_STRING:
342 		penv = kern_getenv(path + rem);
343 		if (penv == NULL)
344 			return;
345 		req.newlen = strlen(penv);
346 		req.newptr = penv;
347 		break;
348 	default:
349 		return;
350 	}
351 	error = sysctl_root_handler_locked(oidp, oidp->oid_arg1,
352 	    oidp->oid_arg2, &req, NULL);
353 	if (error != 0)
354 		printf("Setting sysctl %s failed: %d\n", path + rem, error);
355 	if (penv != NULL)
356 		freeenv(penv);
357 }
358 
359 /*
360  * Locate the path to a given oid.  Returns the length of the resulting path,
361  * or -1 if the oid was not found.  nodes must have room for CTL_MAXNAME
362  * elements and be NULL initialized.
363  */
364 static int
sysctl_search_oid(struct sysctl_oid ** nodes,struct sysctl_oid * needle)365 sysctl_search_oid(struct sysctl_oid **nodes, struct sysctl_oid *needle)
366 {
367 	int indx;
368 
369 	SYSCTL_ASSERT_LOCKED();
370 	indx = 0;
371 	while (indx < CTL_MAXNAME && indx >= 0) {
372 		if (nodes[indx] == NULL && indx == 0)
373 			nodes[indx] = SLIST_FIRST(&sysctl__children);
374 		else if (nodes[indx] == NULL)
375 			nodes[indx] = SLIST_FIRST(&nodes[indx - 1]->oid_children);
376 		else
377 			nodes[indx] = SLIST_NEXT(nodes[indx], oid_link);
378 
379 		if (nodes[indx] == needle)
380 			return (indx + 1);
381 
382 		if (nodes[indx] == NULL) {
383 			indx--;
384 			continue;
385 		}
386 
387 		if ((nodes[indx]->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
388 			indx++;
389 			continue;
390 		}
391 	}
392 	return (-1);
393 }
394 
395 static void
sysctl_warn_reuse(const char * func,struct sysctl_oid * leaf)396 sysctl_warn_reuse(const char *func, struct sysctl_oid *leaf)
397 {
398 	struct sysctl_oid *nodes[CTL_MAXNAME];
399 	char buf[128];
400 	struct sbuf sb;
401 	int rc, i;
402 
403 	(void)sbuf_new(&sb, buf, sizeof(buf), SBUF_FIXEDLEN | SBUF_INCLUDENUL);
404 	sbuf_set_drain(&sb, sbuf_printf_drain, NULL);
405 
406 	sbuf_printf(&sb, "%s: can't re-use a leaf (", func);
407 
408 	memset(nodes, 0, sizeof(nodes));
409 	rc = sysctl_search_oid(nodes, leaf);
410 	if (rc > 0) {
411 		for (i = 0; i < rc; i++)
412 			sbuf_printf(&sb, "%s%.*s", nodes[i]->oid_name,
413 			    i != (rc - 1), ".");
414 	} else {
415 		sbuf_printf(&sb, "%s", leaf->oid_name);
416 	}
417 	sbuf_printf(&sb, ")!\n");
418 
419 	(void)sbuf_finish(&sb);
420 }
421 
422 #ifdef SYSCTL_DEBUG
423 static int
sysctl_reuse_test(SYSCTL_HANDLER_ARGS)424 sysctl_reuse_test(SYSCTL_HANDLER_ARGS)
425 {
426 	struct rm_priotracker tracker;
427 
428 	SYSCTL_RLOCK(&tracker);
429 	sysctl_warn_reuse(__func__, oidp);
430 	SYSCTL_RUNLOCK(&tracker);
431 	return (0);
432 }
433 SYSCTL_PROC(_sysctl, OID_AUTO, reuse_test,
434     CTLTYPE_STRING | CTLFLAG_RD | CTLFLAG_MPSAFE, 0, 0, sysctl_reuse_test, "-",
435     "");
436 #endif
437 
438 void
sysctl_register_oid(struct sysctl_oid * oidp)439 sysctl_register_oid(struct sysctl_oid *oidp)
440 {
441 	struct sysctl_oid_list *parent = oidp->oid_parent;
442 	struct sysctl_oid *p;
443 	struct sysctl_oid *q;
444 	int oid_number;
445 	int timeout = 2;
446 
447 	/*
448 	 * First check if another oid with the same name already
449 	 * exists in the parent's list.
450 	 */
451 	SYSCTL_ASSERT_WLOCKED();
452 	p = sysctl_find_oidname(oidp->oid_name, parent);
453 	if (p != NULL) {
454 		if ((p->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
455 			p->oid_refcnt++;
456 			return;
457 		} else {
458 			sysctl_warn_reuse(__func__, p);
459 			return;
460 		}
461 	}
462 	/* get current OID number */
463 	oid_number = oidp->oid_number;
464 
465 #if (OID_AUTO >= 0)
466 #error "OID_AUTO is expected to be a negative value"
467 #endif
468 	/*
469 	 * Any negative OID number qualifies as OID_AUTO. Valid OID
470 	 * numbers should always be positive.
471 	 *
472 	 * NOTE: DO NOT change the starting value here, change it in
473 	 * <sys/sysctl.h>, and make sure it is at least 256 to
474 	 * accommodate e.g. net.inet.raw as a static sysctl node.
475 	 */
476 	if (oid_number < 0) {
477 		static int newoid;
478 
479 		/*
480 		 * By decrementing the next OID number we spend less
481 		 * time inserting the OIDs into a sorted list.
482 		 */
483 		if (--newoid < CTL_AUTO_START)
484 			newoid = 0x7fffffff;
485 
486 		oid_number = newoid;
487 	}
488 
489 	/*
490 	 * Insert the OID into the parent's list sorted by OID number.
491 	 */
492 retry:
493 	q = NULL;
494 	SLIST_FOREACH(p, parent, oid_link) {
495 		/* check if the current OID number is in use */
496 		if (oid_number == p->oid_number) {
497 			/* get the next valid OID number */
498 			if (oid_number < CTL_AUTO_START ||
499 			    oid_number == 0x7fffffff) {
500 				/* wraparound - restart */
501 				oid_number = CTL_AUTO_START;
502 				/* don't loop forever */
503 				if (!timeout--)
504 					panic("sysctl: Out of OID numbers\n");
505 				goto retry;
506 			} else {
507 				oid_number++;
508 			}
509 		} else if (oid_number < p->oid_number)
510 			break;
511 		q = p;
512 	}
513 	/* check for non-auto OID number collision */
514 	if (oidp->oid_number >= 0 && oidp->oid_number < CTL_AUTO_START &&
515 	    oid_number >= CTL_AUTO_START) {
516 		printf("sysctl: OID number(%d) is already in use for '%s'\n",
517 		    oidp->oid_number, oidp->oid_name);
518 	}
519 	/* update the OID number, if any */
520 	oidp->oid_number = oid_number;
521 	if (q != NULL)
522 		SLIST_INSERT_AFTER(q, oidp, oid_link);
523 	else
524 		SLIST_INSERT_HEAD(parent, oidp, oid_link);
525 
526 	if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE &&
527 	    (oidp->oid_kind & CTLFLAG_TUN) != 0 &&
528 	    (oidp->oid_kind & CTLFLAG_NOFETCH) == 0) {
529 		/* only fetch value once */
530 		oidp->oid_kind |= CTLFLAG_NOFETCH;
531 		/* try to fetch value from kernel environment */
532 		sysctl_load_tunable_by_oid_locked(oidp);
533 	}
534 }
535 
536 void
sysctl_register_disabled_oid(struct sysctl_oid * oidp)537 sysctl_register_disabled_oid(struct sysctl_oid *oidp)
538 {
539 
540 	/*
541 	 * Mark the leaf as dormant if it's not to be immediately enabled.
542 	 * We do not disable nodes as they can be shared between modules
543 	 * and it is always safe to access a node.
544 	 */
545 	KASSERT((oidp->oid_kind & CTLFLAG_DORMANT) == 0,
546 	    ("internal flag is set in oid_kind"));
547 	if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
548 		oidp->oid_kind |= CTLFLAG_DORMANT;
549 	sysctl_register_oid(oidp);
550 }
551 
552 void
sysctl_enable_oid(struct sysctl_oid * oidp)553 sysctl_enable_oid(struct sysctl_oid *oidp)
554 {
555 
556 	SYSCTL_ASSERT_WLOCKED();
557 	if ((oidp->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
558 		KASSERT((oidp->oid_kind & CTLFLAG_DORMANT) == 0,
559 		    ("sysctl node is marked as dormant"));
560 		return;
561 	}
562 	KASSERT((oidp->oid_kind & CTLFLAG_DORMANT) != 0,
563 	    ("enabling already enabled sysctl oid"));
564 	oidp->oid_kind &= ~CTLFLAG_DORMANT;
565 }
566 
567 void
sysctl_unregister_oid(struct sysctl_oid * oidp)568 sysctl_unregister_oid(struct sysctl_oid *oidp)
569 {
570 	struct sysctl_oid *p;
571 	int error;
572 
573 	SYSCTL_ASSERT_WLOCKED();
574 	if (oidp->oid_number == OID_AUTO) {
575 		error = EINVAL;
576 	} else {
577 		error = ENOENT;
578 		SLIST_FOREACH(p, oidp->oid_parent, oid_link) {
579 			if (p == oidp) {
580 				SLIST_REMOVE(oidp->oid_parent, oidp,
581 				    sysctl_oid, oid_link);
582 				error = 0;
583 				break;
584 			}
585 		}
586 	}
587 
588 	/*
589 	 * This can happen when a module fails to register and is
590 	 * being unloaded afterwards.  It should not be a panic()
591 	 * for normal use.
592 	 */
593 	if (error) {
594 		printf("%s: failed(%d) to unregister sysctl(%s)\n",
595 		    __func__, error, oidp->oid_name);
596 	}
597 }
598 
599 /* Initialize a new context to keep track of dynamically added sysctls. */
600 int
sysctl_ctx_init(struct sysctl_ctx_list * c)601 sysctl_ctx_init(struct sysctl_ctx_list *c)
602 {
603 
604 	if (c == NULL) {
605 		return (EINVAL);
606 	}
607 
608 	/*
609 	 * No locking here, the caller is responsible for not adding
610 	 * new nodes to a context until after this function has
611 	 * returned.
612 	 */
613 	TAILQ_INIT(c);
614 	return (0);
615 }
616 
617 /* Free the context, and destroy all dynamic oids registered in this context */
618 int
sysctl_ctx_free(struct sysctl_ctx_list * clist)619 sysctl_ctx_free(struct sysctl_ctx_list *clist)
620 {
621 	struct sysctl_ctx_entry *e, *e1;
622 	int error;
623 
624 	error = 0;
625 	/*
626 	 * First perform a "dry run" to check if it's ok to remove oids.
627 	 * XXX FIXME
628 	 * XXX This algorithm is a hack. But I don't know any
629 	 * XXX better solution for now...
630 	 */
631 	SYSCTL_WLOCK();
632 	TAILQ_FOREACH(e, clist, link) {
633 		error = sysctl_remove_oid_locked(e->entry, 0, 0);
634 		if (error)
635 			break;
636 	}
637 	/*
638 	 * Restore deregistered entries, either from the end,
639 	 * or from the place where error occurred.
640 	 * e contains the entry that was not unregistered
641 	 */
642 	if (error)
643 		e1 = TAILQ_PREV(e, sysctl_ctx_list, link);
644 	else
645 		e1 = TAILQ_LAST(clist, sysctl_ctx_list);
646 	while (e1 != NULL) {
647 		sysctl_register_oid(e1->entry);
648 		e1 = TAILQ_PREV(e1, sysctl_ctx_list, link);
649 	}
650 	if (error) {
651 		SYSCTL_WUNLOCK();
652 		return(EBUSY);
653 	}
654 	/* Now really delete the entries */
655 	e = TAILQ_FIRST(clist);
656 	while (e != NULL) {
657 		e1 = TAILQ_NEXT(e, link);
658 		error = sysctl_remove_oid_locked(e->entry, 1, 0);
659 		if (error)
660 			panic("sysctl_remove_oid: corrupt tree, entry: %s",
661 			    e->entry->oid_name);
662 		free(e, M_SYSCTLOID);
663 		e = e1;
664 	}
665 	SYSCTL_WUNLOCK();
666 	return (error);
667 }
668 
669 /* Add an entry to the context */
670 struct sysctl_ctx_entry *
sysctl_ctx_entry_add(struct sysctl_ctx_list * clist,struct sysctl_oid * oidp)671 sysctl_ctx_entry_add(struct sysctl_ctx_list *clist, struct sysctl_oid *oidp)
672 {
673 	struct sysctl_ctx_entry *e;
674 
675 	SYSCTL_ASSERT_WLOCKED();
676 	if (clist == NULL || oidp == NULL)
677 		return(NULL);
678 	e = malloc(sizeof(struct sysctl_ctx_entry), M_SYSCTLOID, M_WAITOK);
679 	e->entry = oidp;
680 	TAILQ_INSERT_HEAD(clist, e, link);
681 	return (e);
682 }
683 
684 /* Find an entry in the context */
685 struct sysctl_ctx_entry *
sysctl_ctx_entry_find(struct sysctl_ctx_list * clist,struct sysctl_oid * oidp)686 sysctl_ctx_entry_find(struct sysctl_ctx_list *clist, struct sysctl_oid *oidp)
687 {
688 	struct sysctl_ctx_entry *e;
689 
690 	SYSCTL_ASSERT_WLOCKED();
691 	if (clist == NULL || oidp == NULL)
692 		return(NULL);
693 	TAILQ_FOREACH(e, clist, link) {
694 		if(e->entry == oidp)
695 			return(e);
696 	}
697 	return (e);
698 }
699 
700 /*
701  * Delete an entry from the context.
702  * NOTE: this function doesn't free oidp! You have to remove it
703  * with sysctl_remove_oid().
704  */
705 int
sysctl_ctx_entry_del(struct sysctl_ctx_list * clist,struct sysctl_oid * oidp)706 sysctl_ctx_entry_del(struct sysctl_ctx_list *clist, struct sysctl_oid *oidp)
707 {
708 	struct sysctl_ctx_entry *e;
709 
710 	if (clist == NULL || oidp == NULL)
711 		return (EINVAL);
712 	SYSCTL_WLOCK();
713 	e = sysctl_ctx_entry_find(clist, oidp);
714 	if (e != NULL) {
715 		TAILQ_REMOVE(clist, e, link);
716 		SYSCTL_WUNLOCK();
717 		free(e, M_SYSCTLOID);
718 		return (0);
719 	} else {
720 		SYSCTL_WUNLOCK();
721 		return (ENOENT);
722 	}
723 }
724 
725 /*
726  * Remove dynamically created sysctl trees.
727  * oidp - top of the tree to be removed
728  * del - if 0 - just deregister, otherwise free up entries as well
729  * recurse - if != 0 traverse the subtree to be deleted
730  */
731 int
sysctl_remove_oid(struct sysctl_oid * oidp,int del,int recurse)732 sysctl_remove_oid(struct sysctl_oid *oidp, int del, int recurse)
733 {
734 	int error;
735 
736 	SYSCTL_WLOCK();
737 	error = sysctl_remove_oid_locked(oidp, del, recurse);
738 	SYSCTL_WUNLOCK();
739 	return (error);
740 }
741 
742 int
sysctl_remove_name(struct sysctl_oid * parent,const char * name,int del,int recurse)743 sysctl_remove_name(struct sysctl_oid *parent, const char *name,
744     int del, int recurse)
745 {
746 	struct sysctl_oid *p, *tmp;
747 	int error;
748 
749 	error = ENOENT;
750 	SYSCTL_WLOCK();
751 	SLIST_FOREACH_SAFE(p, SYSCTL_CHILDREN(parent), oid_link, tmp) {
752 		if (strcmp(p->oid_name, name) == 0) {
753 			error = sysctl_remove_oid_locked(p, del, recurse);
754 			break;
755 		}
756 	}
757 	SYSCTL_WUNLOCK();
758 
759 	return (error);
760 }
761 
762 /*
763  * Duplicate the provided string, escaping any illegal characters.  The result
764  * must be freed when no longer in use.
765  *
766  * The list of illegal characters is ".".
767  */
768 static char*
sysctl_escape_name(const char * orig)769 sysctl_escape_name(const char* orig)
770 {
771 	int i, s = 0, d = 0, nillegals = 0;
772 	char *new;
773 
774 	/* First count the number of illegal characters */
775 	for (i = 0; orig[i] != '\0'; i++) {
776 		if (orig[i] == '.')
777 			nillegals++;
778 	}
779 
780 	/* Allocate storage for new string */
781 	new = malloc(i + 2 * nillegals + 1, M_SYSCTLOID, M_WAITOK);
782 
783 	/* Copy the name, escaping characters as we go */
784 	while (orig[s] != '\0') {
785 		if (orig[s] == '.') {
786 			/* %25 is the hexadecimal representation of '.' */
787 			new[d++] = '%';
788 			new[d++] = '2';
789 			new[d++] = '5';
790 			s++;
791 		} else {
792 			new[d++] = orig[s++];
793 		}
794 	}
795 
796 	/* Finally, nul-terminate */
797 	new[d] = '\0';
798 
799 	return (new);
800 }
801 
802 static int
sysctl_remove_oid_locked(struct sysctl_oid * oidp,int del,int recurse)803 sysctl_remove_oid_locked(struct sysctl_oid *oidp, int del, int recurse)
804 {
805 	struct sysctl_oid *p, *tmp;
806 	int error;
807 
808 	SYSCTL_ASSERT_WLOCKED();
809 	if (oidp == NULL)
810 		return(EINVAL);
811 	if ((oidp->oid_kind & CTLFLAG_DYN) == 0) {
812 		printf("Warning: can't remove non-dynamic nodes (%s)!\n",
813 		    oidp->oid_name);
814 		return (EINVAL);
815 	}
816 	/*
817 	 * WARNING: normal method to do this should be through
818 	 * sysctl_ctx_free(). Use recursing as the last resort
819 	 * method to purge your sysctl tree of leftovers...
820 	 * However, if some other code still references these nodes,
821 	 * it will panic.
822 	 */
823 	if ((oidp->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
824 		if (oidp->oid_refcnt == 1) {
825 			SLIST_FOREACH_SAFE(p,
826 			    SYSCTL_CHILDREN(oidp), oid_link, tmp) {
827 				if (!recurse) {
828 					printf("Warning: failed attempt to "
829 					    "remove oid %s with child %s\n",
830 					    oidp->oid_name, p->oid_name);
831 					return (ENOTEMPTY);
832 				}
833 				error = sysctl_remove_oid_locked(p, del,
834 				    recurse);
835 				if (error)
836 					return (error);
837 			}
838 		}
839 	}
840 	if (oidp->oid_refcnt > 1 ) {
841 		oidp->oid_refcnt--;
842 	} else {
843 		if (oidp->oid_refcnt == 0) {
844 			printf("Warning: bad oid_refcnt=%u (%s)!\n",
845 				oidp->oid_refcnt, oidp->oid_name);
846 			return (EINVAL);
847 		}
848 		sysctl_unregister_oid(oidp);
849 		if (del) {
850 			/*
851 			 * Wait for all threads running the handler to drain.
852 			 * This preserves the previous behavior when the
853 			 * sysctl lock was held across a handler invocation,
854 			 * and is necessary for module unload correctness.
855 			 */
856 			while (oidp->oid_running > 0) {
857 				oidp->oid_kind |= CTLFLAG_DYING;
858 				SYSCTL_SLEEP(&oidp->oid_running, "oidrm", 0);
859 			}
860 			if (oidp->oid_descr)
861 				free(__DECONST(char *, oidp->oid_descr),
862 				    M_SYSCTLOID);
863 			if (oidp->oid_label)
864 				free(__DECONST(char *, oidp->oid_label),
865 				    M_SYSCTLOID);
866 			free(__DECONST(char *, oidp->oid_name), M_SYSCTLOID);
867 			free(oidp, M_SYSCTLOID);
868 		}
869 	}
870 	return (0);
871 }
872 /*
873  * Create new sysctls at run time.
874  * clist may point to a valid context initialized with sysctl_ctx_init().
875  */
876 struct sysctl_oid *
sysctl_add_oid(struct sysctl_ctx_list * clist,struct sysctl_oid_list * parent,int number,const char * name,int kind,void * arg1,intmax_t arg2,int (* handler)(SYSCTL_HANDLER_ARGS),const char * fmt,const char * descr,const char * label)877 sysctl_add_oid(struct sysctl_ctx_list *clist, struct sysctl_oid_list *parent,
878 	int number, const char *name, int kind, void *arg1, intmax_t arg2,
879 	int (*handler)(SYSCTL_HANDLER_ARGS), const char *fmt, const char *descr,
880 	const char *label)
881 {
882 	struct sysctl_oid *oidp;
883 	char *escaped;
884 
885 	/* You have to hook up somewhere.. */
886 	if (parent == NULL)
887 		return(NULL);
888 	escaped = sysctl_escape_name(name);
889 	/* Check if the node already exists, otherwise create it */
890 	SYSCTL_WLOCK();
891 	oidp = sysctl_find_oidname(escaped, parent);
892 	if (oidp != NULL) {
893 		free(escaped, M_SYSCTLOID);
894 		if ((oidp->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
895 			oidp->oid_refcnt++;
896 			/* Update the context */
897 			if (clist != NULL)
898 				sysctl_ctx_entry_add(clist, oidp);
899 			SYSCTL_WUNLOCK();
900 			return (oidp);
901 		} else {
902 			sysctl_warn_reuse(__func__, oidp);
903 			SYSCTL_WUNLOCK();
904 			return (NULL);
905 		}
906 	}
907 	oidp = malloc(sizeof(struct sysctl_oid), M_SYSCTLOID, M_WAITOK|M_ZERO);
908 	oidp->oid_parent = parent;
909 	SLIST_INIT(&oidp->oid_children);
910 	oidp->oid_number = number;
911 	oidp->oid_refcnt = 1;
912 	oidp->oid_name = escaped;
913 	oidp->oid_handler = handler;
914 	oidp->oid_kind = CTLFLAG_DYN | kind;
915 	oidp->oid_arg1 = arg1;
916 	oidp->oid_arg2 = arg2;
917 	oidp->oid_fmt = fmt;
918 	if (descr != NULL)
919 		oidp->oid_descr = strdup(descr, M_SYSCTLOID);
920 	if (label != NULL)
921 		oidp->oid_label = strdup(label, M_SYSCTLOID);
922 	/* Update the context, if used */
923 	if (clist != NULL)
924 		sysctl_ctx_entry_add(clist, oidp);
925 	/* Register this oid */
926 	sysctl_register_oid(oidp);
927 	SYSCTL_WUNLOCK();
928 	return (oidp);
929 }
930 
931 /*
932  * Rename an existing oid.
933  */
934 void
sysctl_rename_oid(struct sysctl_oid * oidp,const char * name)935 sysctl_rename_oid(struct sysctl_oid *oidp, const char *name)
936 {
937 	char *newname;
938 	char *oldname;
939 
940 	newname = strdup(name, M_SYSCTLOID);
941 	SYSCTL_WLOCK();
942 	oldname = __DECONST(char *, oidp->oid_name);
943 	oidp->oid_name = newname;
944 	SYSCTL_WUNLOCK();
945 	free(oldname, M_SYSCTLOID);
946 }
947 
948 /*
949  * Reparent an existing oid.
950  */
951 int
sysctl_move_oid(struct sysctl_oid * oid,struct sysctl_oid_list * parent)952 sysctl_move_oid(struct sysctl_oid *oid, struct sysctl_oid_list *parent)
953 {
954 	struct sysctl_oid *oidp;
955 
956 	SYSCTL_WLOCK();
957 	if (oid->oid_parent == parent) {
958 		SYSCTL_WUNLOCK();
959 		return (0);
960 	}
961 	oidp = sysctl_find_oidname(oid->oid_name, parent);
962 	if (oidp != NULL) {
963 		SYSCTL_WUNLOCK();
964 		return (EEXIST);
965 	}
966 	sysctl_unregister_oid(oid);
967 	oid->oid_parent = parent;
968 	oid->oid_number = OID_AUTO;
969 	sysctl_register_oid(oid);
970 	SYSCTL_WUNLOCK();
971 	return (0);
972 }
973 
974 /*
975  * Register the kernel's oids on startup.
976  */
977 SET_DECLARE(sysctl_set, struct sysctl_oid);
978 
979 static void
sysctl_register_all(void * arg)980 sysctl_register_all(void *arg)
981 {
982 	struct sysctl_oid **oidp;
983 
984 	sx_init(&sysctlmemlock, "sysctl mem");
985 	sx_init(&sysctlstringlock, "sysctl string handler");
986 	SYSCTL_INIT();
987 	SYSCTL_WLOCK();
988 	SET_FOREACH(oidp, sysctl_set)
989 		sysctl_register_oid(*oidp);
990 	SYSCTL_WUNLOCK();
991 }
992 SYSINIT(sysctl, SI_SUB_KMEM, SI_ORDER_FIRST, sysctl_register_all, NULL);
993 
994 /*
995  * "Staff-functions"
996  *
997  * These functions implement a presently undocumented interface
998  * used by the sysctl program to walk the tree, and get the type
999  * so it can print the value.
1000  * This interface is under work and consideration, and should probably
1001  * be killed with a big axe by the first person who can find the time.
1002  * (be aware though, that the proper interface isn't as obvious as it
1003  * may seem, there are various conflicting requirements.
1004  *
1005  * {CTL_SYSCTL, CTL_SYSCTL_DEBUG}		printf the entire MIB-tree.
1006  * {CTL_SYSCTL, CTL_SYSCTL_NAME, ...}		return the name of the "..."
1007  *						OID.
1008  * {CTL_SYSCTL, CTL_SYSCTL_NEXT, ...}		return the next OID, honoring
1009  *						CTLFLAG_SKIP.
1010  * {CTL_SYSCTL, CTL_SYSCTL_NAME2OID}		return the OID of the name in
1011  *						"new"
1012  * {CTL_SYSCTL, CTL_SYSCTL_OIDFMT, ...}		return the kind & format info
1013  *						for the "..." OID.
1014  * {CTL_SYSCTL, CTL_SYSCTL_OIDDESCR, ...}	return the description of the
1015  *						"..." OID.
1016  * {CTL_SYSCTL, CTL_SYSCTL_OIDLABEL, ...}	return the aggregation label of
1017  *						the "..." OID.
1018  * {CTL_SYSCTL, CTL_SYSCTL_NEXTNOSKIP, ...}	return the next OID, ignoring
1019  *						CTLFLAG_SKIP.
1020  */
1021 
1022 #ifdef SYSCTL_DEBUG
1023 static void
sysctl_sysctl_debug_dump_node(struct sysctl_oid_list * l,int i)1024 sysctl_sysctl_debug_dump_node(struct sysctl_oid_list *l, int i)
1025 {
1026 	int k;
1027 	struct sysctl_oid *oidp;
1028 
1029 	SYSCTL_ASSERT_LOCKED();
1030 	SYSCTL_FOREACH(oidp, l) {
1031 		for (k=0; k<i; k++)
1032 			printf(" ");
1033 
1034 		printf("%d %s ", oidp->oid_number, oidp->oid_name);
1035 
1036 		printf("%c%c",
1037 			oidp->oid_kind & CTLFLAG_RD ? 'R':' ',
1038 			oidp->oid_kind & CTLFLAG_WR ? 'W':' ');
1039 
1040 		if (oidp->oid_handler)
1041 			printf(" *Handler");
1042 
1043 		switch (oidp->oid_kind & CTLTYPE) {
1044 			case CTLTYPE_NODE:
1045 				printf(" Node\n");
1046 				if (!oidp->oid_handler) {
1047 					sysctl_sysctl_debug_dump_node(
1048 					    SYSCTL_CHILDREN(oidp), i + 2);
1049 				}
1050 				break;
1051 			case CTLTYPE_INT:    printf(" Int\n"); break;
1052 			case CTLTYPE_UINT:   printf(" u_int\n"); break;
1053 			case CTLTYPE_LONG:   printf(" Long\n"); break;
1054 			case CTLTYPE_ULONG:  printf(" u_long\n"); break;
1055 			case CTLTYPE_STRING: printf(" String\n"); break;
1056 			case CTLTYPE_S8:     printf(" int8_t\n"); break;
1057 			case CTLTYPE_S16:    printf(" int16_t\n"); break;
1058 			case CTLTYPE_S32:    printf(" int32_t\n"); break;
1059 			case CTLTYPE_S64:    printf(" int64_t\n"); break;
1060 			case CTLTYPE_U8:     printf(" uint8_t\n"); break;
1061 			case CTLTYPE_U16:    printf(" uint16_t\n"); break;
1062 			case CTLTYPE_U32:    printf(" uint32_t\n"); break;
1063 			case CTLTYPE_U64:    printf(" uint64_t\n"); break;
1064 			case CTLTYPE_OPAQUE: printf(" Opaque/struct\n"); break;
1065 			default:	     printf("\n");
1066 		}
1067 	}
1068 }
1069 
1070 static int
sysctl_sysctl_debug(SYSCTL_HANDLER_ARGS)1071 sysctl_sysctl_debug(SYSCTL_HANDLER_ARGS)
1072 {
1073 	struct rm_priotracker tracker;
1074 	int error;
1075 
1076 	error = priv_check(req->td, PRIV_SYSCTL_DEBUG);
1077 	if (error)
1078 		return (error);
1079 	SYSCTL_RLOCK(&tracker);
1080 	sysctl_sysctl_debug_dump_node(&sysctl__children, 0);
1081 	SYSCTL_RUNLOCK(&tracker);
1082 	return (ENOENT);
1083 }
1084 
1085 SYSCTL_PROC(_sysctl, CTL_SYSCTL_DEBUG, debug, CTLTYPE_STRING | CTLFLAG_RD |
1086     CTLFLAG_MPSAFE, 0, 0, sysctl_sysctl_debug, "-", "");
1087 #endif
1088 
1089 static int
sysctl_sysctl_name(SYSCTL_HANDLER_ARGS)1090 sysctl_sysctl_name(SYSCTL_HANDLER_ARGS)
1091 {
1092 	int *name = (int *) arg1;
1093 	u_int namelen = arg2;
1094 	int error;
1095 	struct sysctl_oid *oid;
1096 	struct sysctl_oid_list *lsp = &sysctl__children, *lsp2;
1097 	struct rm_priotracker tracker;
1098 	char buf[10];
1099 
1100 	error = sysctl_wire_old_buffer(req, 0);
1101 	if (error)
1102 		return (error);
1103 
1104 	SYSCTL_RLOCK(&tracker);
1105 	while (namelen) {
1106 		if (!lsp) {
1107 			snprintf(buf,sizeof(buf),"%d",*name);
1108 			if (req->oldidx)
1109 				error = SYSCTL_OUT(req, ".", 1);
1110 			if (!error)
1111 				error = SYSCTL_OUT(req, buf, strlen(buf));
1112 			if (error)
1113 				goto out;
1114 			namelen--;
1115 			name++;
1116 			continue;
1117 		}
1118 		lsp2 = NULL;
1119 		SLIST_FOREACH(oid, lsp, oid_link) {
1120 			if (oid->oid_number != *name)
1121 				continue;
1122 
1123 			if (req->oldidx)
1124 				error = SYSCTL_OUT(req, ".", 1);
1125 			if (!error)
1126 				error = SYSCTL_OUT(req, oid->oid_name,
1127 					strlen(oid->oid_name));
1128 			if (error)
1129 				goto out;
1130 
1131 			namelen--;
1132 			name++;
1133 
1134 			if ((oid->oid_kind & CTLTYPE) != CTLTYPE_NODE)
1135 				break;
1136 
1137 			if (oid->oid_handler)
1138 				break;
1139 
1140 			lsp2 = SYSCTL_CHILDREN(oid);
1141 			break;
1142 		}
1143 		lsp = lsp2;
1144 	}
1145 	error = SYSCTL_OUT(req, "", 1);
1146  out:
1147 	SYSCTL_RUNLOCK(&tracker);
1148 	return (error);
1149 }
1150 
1151 /*
1152  * XXXRW/JA: Shouldn't return name data for nodes that we don't permit in
1153  * capability mode.
1154  */
1155 static SYSCTL_NODE(_sysctl, CTL_SYSCTL_NAME, name, CTLFLAG_RD |
1156     CTLFLAG_MPSAFE | CTLFLAG_CAPRD, sysctl_sysctl_name, "");
1157 
1158 enum sysctl_iter_action {
1159 	ITER_SIBLINGS,	/* Not matched, continue iterating siblings */
1160 	ITER_CHILDREN,	/* Node has children we need to iterate over them */
1161 	ITER_FOUND,	/* Matching node was found */
1162 };
1163 
1164 /*
1165  * Tries to find the next node for @name and @namelen.
1166  *
1167  * Returns next action to take.
1168  */
1169 static enum sysctl_iter_action
sysctl_sysctl_next_node(struct sysctl_oid * oidp,int * name,unsigned int namelen,bool honor_skip)1170 sysctl_sysctl_next_node(struct sysctl_oid *oidp, int *name, unsigned int namelen,
1171     bool honor_skip)
1172 {
1173 
1174 	if ((oidp->oid_kind & CTLFLAG_DORMANT) != 0)
1175 		return (ITER_SIBLINGS);
1176 
1177 	if (honor_skip && (oidp->oid_kind & CTLFLAG_SKIP) != 0)
1178 		return (ITER_SIBLINGS);
1179 
1180 	if (namelen == 0) {
1181 		/*
1182 		 * We have reached a node with a full name match and are
1183 		 * looking for the next oid in its children.
1184 		 *
1185 		 * For CTL_SYSCTL_NEXTNOSKIP we are done.
1186 		 *
1187 		 * For CTL_SYSCTL_NEXT we skip CTLTYPE_NODE (unless it
1188 		 * has a handler) and move on to the children.
1189 		 */
1190 		if (!honor_skip)
1191 			return (ITER_FOUND);
1192 		if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
1193 			return (ITER_FOUND);
1194 		/* If node does not have an iterator, treat it as leaf */
1195 		if (oidp->oid_handler)
1196 			return (ITER_FOUND);
1197 
1198 		/* Report oid as a node to iterate */
1199 		return (ITER_CHILDREN);
1200 	}
1201 
1202 	/*
1203 	 * No match yet. Continue seeking the given name.
1204 	 *
1205 	 * We are iterating in order by oid_number, so skip oids lower
1206 	 * than the one we are looking for.
1207 	 *
1208 	 * When the current oid_number is higher than the one we seek,
1209 	 * that means we have reached the next oid in the sequence and
1210 	 * should return it.
1211 	 *
1212 	 * If the oid_number matches the name at this level then we
1213 	 * have to find a node to continue searching at the next level.
1214 	 */
1215 	if (oidp->oid_number < *name)
1216 		return (ITER_SIBLINGS);
1217 	if (oidp->oid_number > *name) {
1218 		/*
1219 		 * We have reached the next oid.
1220 		 *
1221 		 * For CTL_SYSCTL_NEXTNOSKIP we are done.
1222 		 *
1223 		 * For CTL_SYSCTL_NEXT we skip CTLTYPE_NODE (unless it
1224 		 * has a handler) and move on to the children.
1225 		 */
1226 		if (!honor_skip)
1227 			return (ITER_FOUND);
1228 		if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
1229 			return (ITER_FOUND);
1230 		/* If node does not have an iterator, treat it as leaf */
1231 		if (oidp->oid_handler)
1232 			return (ITER_FOUND);
1233 		return (ITER_CHILDREN);
1234 	}
1235 
1236 	/* match at a current level */
1237 	if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
1238 		return (ITER_SIBLINGS);
1239 	if (oidp->oid_handler)
1240 		return (ITER_SIBLINGS);
1241 
1242 	return (ITER_CHILDREN);
1243 }
1244 
1245 /*
1246  * Recursively walk the sysctl subtree at lsp until we find the given name.
1247  * Returns true and fills in next oid data in @next and @len if oid is found.
1248  */
1249 static bool
sysctl_sysctl_next_action(struct sysctl_oid_list * lsp,int * name,u_int namelen,int * next,int * len,int level,bool honor_skip)1250 sysctl_sysctl_next_action(struct sysctl_oid_list *lsp, int *name, u_int namelen,
1251     int *next, int *len, int level, bool honor_skip)
1252 {
1253 	struct sysctl_oid *oidp;
1254 	bool success = false;
1255 	enum sysctl_iter_action action;
1256 
1257 	SYSCTL_ASSERT_LOCKED();
1258 	SLIST_FOREACH(oidp, lsp, oid_link) {
1259 		action = sysctl_sysctl_next_node(oidp, name, namelen, honor_skip);
1260 		if (action == ITER_SIBLINGS)
1261 			continue;
1262 		if (action == ITER_FOUND) {
1263 			success = true;
1264 			break;
1265 		}
1266 		KASSERT((action== ITER_CHILDREN), ("ret(%d)!=ITER_CHILDREN", action));
1267 
1268 		lsp = SYSCTL_CHILDREN(oidp);
1269 		if (namelen == 0) {
1270 			success = sysctl_sysctl_next_action(lsp, NULL, 0,
1271 			    next + 1, len, level + 1, honor_skip);
1272 		} else {
1273 			success = sysctl_sysctl_next_action(lsp, name + 1, namelen - 1,
1274 			    next + 1, len, level + 1, honor_skip);
1275 			if (!success) {
1276 
1277 				/*
1278 				 * We maintain the invariant that current node oid
1279 				 * is >= the oid provided in @name.
1280 				 * As there are no usable children at this node,
1281 				 *  current node oid is strictly > than the requested
1282 				 *  oid.
1283 				 * Hence, reduce namelen to 0 to allow for picking first
1284 				 *  nodes/leafs in the next node in list.
1285 				 */
1286 				namelen = 0;
1287 			}
1288 		}
1289 		if (success)
1290 			break;
1291 	}
1292 
1293 	if (success) {
1294 		*next = oidp->oid_number;
1295 		if (level > *len)
1296 			*len = level;
1297 	}
1298 
1299 	return (success);
1300 }
1301 
1302 static int
sysctl_sysctl_next(SYSCTL_HANDLER_ARGS)1303 sysctl_sysctl_next(SYSCTL_HANDLER_ARGS)
1304 {
1305 	int *name = (int *) arg1;
1306 	u_int namelen = arg2;
1307 	int len, error;
1308 	bool success;
1309 	struct sysctl_oid_list *lsp = &sysctl__children;
1310 	struct rm_priotracker tracker;
1311 	int next[CTL_MAXNAME];
1312 
1313 	len = 0;
1314 	SYSCTL_RLOCK(&tracker);
1315 	success = sysctl_sysctl_next_action(lsp, name, namelen, next, &len, 1,
1316 	    oidp->oid_number == CTL_SYSCTL_NEXT);
1317 	SYSCTL_RUNLOCK(&tracker);
1318 	if (!success)
1319 		return (ENOENT);
1320 	error = SYSCTL_OUT(req, next, len * sizeof (int));
1321 	return (error);
1322 }
1323 
1324 /*
1325  * XXXRW/JA: Shouldn't return next data for nodes that we don't permit in
1326  * capability mode.
1327  */
1328 static SYSCTL_NODE(_sysctl, CTL_SYSCTL_NEXT, next, CTLFLAG_RD |
1329     CTLFLAG_MPSAFE | CTLFLAG_CAPRD, sysctl_sysctl_next, "");
1330 
1331 static SYSCTL_NODE(_sysctl, CTL_SYSCTL_NEXTNOSKIP, nextnoskip, CTLFLAG_RD |
1332     CTLFLAG_MPSAFE | CTLFLAG_CAPRD, sysctl_sysctl_next, "");
1333 
1334 static int
name2oid(const char * name,int * oid,int * len,struct sysctl_oid ** oidpp)1335 name2oid(const char *name, int *oid, int *len, struct sysctl_oid **oidpp)
1336 {
1337 	struct sysctl_oid *oidp;
1338 	struct sysctl_oid_list *lsp = &sysctl__children;
1339 	const char *n;
1340 
1341 	SYSCTL_ASSERT_LOCKED();
1342 
1343 	for (*len = 0; *len < CTL_MAXNAME;) {
1344 		n = strchrnul(name, '.');
1345 		oidp = sysctl_find_oidnamelen(name, n - name, lsp);
1346 		if (oidp == NULL)
1347 			return (ENOENT);
1348 		*oid++ = oidp->oid_number;
1349 		(*len)++;
1350 
1351 		name = n;
1352 		if (*name == '.')
1353 			name++;
1354 		if (*name == '\0') {
1355 			if (oidpp)
1356 				*oidpp = oidp;
1357 			return (0);
1358 		}
1359 
1360 		if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
1361 			break;
1362 
1363 		if (oidp->oid_handler)
1364 			break;
1365 
1366 		lsp = SYSCTL_CHILDREN(oidp);
1367 	}
1368 	return (ENOENT);
1369 }
1370 
1371 static int
sysctl_sysctl_name2oid(SYSCTL_HANDLER_ARGS)1372 sysctl_sysctl_name2oid(SYSCTL_HANDLER_ARGS)
1373 {
1374 	char *p;
1375 	int error, oid[CTL_MAXNAME], len = 0;
1376 	struct sysctl_oid *op = NULL;
1377 	struct rm_priotracker tracker;
1378 	char buf[32];
1379 
1380 	if (!req->newlen)
1381 		return (ENOENT);
1382 	if (req->newlen >= MAXPATHLEN)	/* XXX arbitrary, undocumented */
1383 		return (ENAMETOOLONG);
1384 
1385 	p = buf;
1386 	if (req->newlen >= sizeof(buf))
1387 		p = malloc(req->newlen+1, M_SYSCTL, M_WAITOK);
1388 
1389 	error = SYSCTL_IN(req, p, req->newlen);
1390 	if (error) {
1391 		if (p != buf)
1392 			free(p, M_SYSCTL);
1393 		return (error);
1394 	}
1395 
1396 	p [req->newlen] = '\0';
1397 
1398 	SYSCTL_RLOCK(&tracker);
1399 	error = name2oid(p, oid, &len, &op);
1400 	SYSCTL_RUNLOCK(&tracker);
1401 
1402 	if (p != buf)
1403 		free(p, M_SYSCTL);
1404 
1405 	if (error)
1406 		return (error);
1407 
1408 	error = SYSCTL_OUT(req, oid, len * sizeof *oid);
1409 	return (error);
1410 }
1411 
1412 /*
1413  * XXXRW/JA: Shouldn't return name2oid data for nodes that we don't permit in
1414  * capability mode.
1415  */
1416 SYSCTL_PROC(_sysctl, CTL_SYSCTL_NAME2OID, name2oid, CTLTYPE_INT | CTLFLAG_RW |
1417     CTLFLAG_ANYBODY | CTLFLAG_MPSAFE | CTLFLAG_CAPRW, 0, 0,
1418     sysctl_sysctl_name2oid, "I", "");
1419 
1420 static int
sysctl_sysctl_oidfmt(SYSCTL_HANDLER_ARGS)1421 sysctl_sysctl_oidfmt(SYSCTL_HANDLER_ARGS)
1422 {
1423 	struct sysctl_oid *oid;
1424 	struct rm_priotracker tracker;
1425 	int error;
1426 
1427 	error = sysctl_wire_old_buffer(req, 0);
1428 	if (error)
1429 		return (error);
1430 
1431 	SYSCTL_RLOCK(&tracker);
1432 	error = sysctl_find_oid(arg1, arg2, &oid, NULL, req);
1433 	if (error)
1434 		goto out;
1435 
1436 	if (oid->oid_fmt == NULL) {
1437 		error = ENOENT;
1438 		goto out;
1439 	}
1440 	error = SYSCTL_OUT(req, &oid->oid_kind, sizeof(oid->oid_kind));
1441 	if (error)
1442 		goto out;
1443 	error = SYSCTL_OUT(req, oid->oid_fmt, strlen(oid->oid_fmt) + 1);
1444  out:
1445 	SYSCTL_RUNLOCK(&tracker);
1446 	return (error);
1447 }
1448 
1449 static SYSCTL_NODE(_sysctl, CTL_SYSCTL_OIDFMT, oidfmt, CTLFLAG_RD |
1450     CTLFLAG_MPSAFE | CTLFLAG_CAPRD, sysctl_sysctl_oidfmt, "");
1451 
1452 static int
sysctl_sysctl_oiddescr(SYSCTL_HANDLER_ARGS)1453 sysctl_sysctl_oiddescr(SYSCTL_HANDLER_ARGS)
1454 {
1455 	struct sysctl_oid *oid;
1456 	struct rm_priotracker tracker;
1457 	int error;
1458 
1459 	error = sysctl_wire_old_buffer(req, 0);
1460 	if (error)
1461 		return (error);
1462 
1463 	SYSCTL_RLOCK(&tracker);
1464 	error = sysctl_find_oid(arg1, arg2, &oid, NULL, req);
1465 	if (error)
1466 		goto out;
1467 
1468 	if (oid->oid_descr == NULL) {
1469 		error = ENOENT;
1470 		goto out;
1471 	}
1472 	error = SYSCTL_OUT(req, oid->oid_descr, strlen(oid->oid_descr) + 1);
1473  out:
1474 	SYSCTL_RUNLOCK(&tracker);
1475 	return (error);
1476 }
1477 
1478 static SYSCTL_NODE(_sysctl, CTL_SYSCTL_OIDDESCR, oiddescr, CTLFLAG_RD |
1479     CTLFLAG_MPSAFE|CTLFLAG_CAPRD, sysctl_sysctl_oiddescr, "");
1480 
1481 static int
sysctl_sysctl_oidlabel(SYSCTL_HANDLER_ARGS)1482 sysctl_sysctl_oidlabel(SYSCTL_HANDLER_ARGS)
1483 {
1484 	struct sysctl_oid *oid;
1485 	struct rm_priotracker tracker;
1486 	int error;
1487 
1488 	error = sysctl_wire_old_buffer(req, 0);
1489 	if (error)
1490 		return (error);
1491 
1492 	SYSCTL_RLOCK(&tracker);
1493 	error = sysctl_find_oid(arg1, arg2, &oid, NULL, req);
1494 	if (error)
1495 		goto out;
1496 
1497 	if (oid->oid_label == NULL) {
1498 		error = ENOENT;
1499 		goto out;
1500 	}
1501 	error = SYSCTL_OUT(req, oid->oid_label, strlen(oid->oid_label) + 1);
1502  out:
1503 	SYSCTL_RUNLOCK(&tracker);
1504 	return (error);
1505 }
1506 
1507 static SYSCTL_NODE(_sysctl, CTL_SYSCTL_OIDLABEL, oidlabel, CTLFLAG_RD |
1508     CTLFLAG_MPSAFE | CTLFLAG_CAPRD, sysctl_sysctl_oidlabel, "");
1509 
1510 /*
1511  * Default "handler" functions.
1512  */
1513 
1514 /*
1515  * Handle a bool.
1516  * Two cases:
1517  *     a variable:  point arg1 at it.
1518  *     a constant:  pass it in arg2.
1519  */
1520 
1521 int
sysctl_handle_bool(SYSCTL_HANDLER_ARGS)1522 sysctl_handle_bool(SYSCTL_HANDLER_ARGS)
1523 {
1524 	uint8_t temp;
1525 	int error;
1526 
1527 	/*
1528 	 * Attempt to get a coherent snapshot by making a copy of the data.
1529 	 */
1530 	if (arg1)
1531 		temp = *(bool *)arg1 ? 1 : 0;
1532 	else
1533 		temp = arg2 ? 1 : 0;
1534 
1535 	error = SYSCTL_OUT(req, &temp, sizeof(temp));
1536 	if (error || !req->newptr)
1537 		return (error);
1538 
1539 	if (!arg1)
1540 		error = EPERM;
1541 	else {
1542 		error = SYSCTL_IN(req, &temp, sizeof(temp));
1543 		if (!error)
1544 			*(bool *)arg1 = temp ? 1 : 0;
1545 	}
1546 	return (error);
1547 }
1548 
1549 /*
1550  * Handle an int8_t, signed or unsigned.
1551  * Two cases:
1552  *     a variable:  point arg1 at it.
1553  *     a constant:  pass it in arg2.
1554  */
1555 
1556 int
sysctl_handle_8(SYSCTL_HANDLER_ARGS)1557 sysctl_handle_8(SYSCTL_HANDLER_ARGS)
1558 {
1559 	int8_t tmpout;
1560 	int error = 0;
1561 
1562 	/*
1563 	 * Attempt to get a coherent snapshot by making a copy of the data.
1564 	 */
1565 	if (arg1)
1566 		tmpout = *(int8_t *)arg1;
1567 	else
1568 		tmpout = arg2;
1569 	error = SYSCTL_OUT(req, &tmpout, sizeof(tmpout));
1570 
1571 	if (error || !req->newptr)
1572 		return (error);
1573 
1574 	if (!arg1)
1575 		error = EPERM;
1576 	else
1577 		error = SYSCTL_IN(req, arg1, sizeof(tmpout));
1578 	return (error);
1579 }
1580 
1581 /*
1582  * Handle an int16_t, signed or unsigned.
1583  * Two cases:
1584  *     a variable:  point arg1 at it.
1585  *     a constant:  pass it in arg2.
1586  */
1587 
1588 int
sysctl_handle_16(SYSCTL_HANDLER_ARGS)1589 sysctl_handle_16(SYSCTL_HANDLER_ARGS)
1590 {
1591 	int16_t tmpout;
1592 	int error = 0;
1593 
1594 	/*
1595 	 * Attempt to get a coherent snapshot by making a copy of the data.
1596 	 */
1597 	if (arg1)
1598 		tmpout = *(int16_t *)arg1;
1599 	else
1600 		tmpout = arg2;
1601 	error = SYSCTL_OUT(req, &tmpout, sizeof(tmpout));
1602 
1603 	if (error || !req->newptr)
1604 		return (error);
1605 
1606 	if (!arg1)
1607 		error = EPERM;
1608 	else
1609 		error = SYSCTL_IN(req, arg1, sizeof(tmpout));
1610 	return (error);
1611 }
1612 
1613 /*
1614  * Handle an int32_t, signed or unsigned.
1615  * Two cases:
1616  *     a variable:  point arg1 at it.
1617  *     a constant:  pass it in arg2.
1618  */
1619 
1620 int
sysctl_handle_32(SYSCTL_HANDLER_ARGS)1621 sysctl_handle_32(SYSCTL_HANDLER_ARGS)
1622 {
1623 	int32_t tmpout;
1624 	int error = 0;
1625 
1626 	/*
1627 	 * Attempt to get a coherent snapshot by making a copy of the data.
1628 	 */
1629 	if (arg1)
1630 		tmpout = *(int32_t *)arg1;
1631 	else
1632 		tmpout = arg2;
1633 	error = SYSCTL_OUT(req, &tmpout, sizeof(tmpout));
1634 
1635 	if (error || !req->newptr)
1636 		return (error);
1637 
1638 	if (!arg1)
1639 		error = EPERM;
1640 	else
1641 		error = SYSCTL_IN(req, arg1, sizeof(tmpout));
1642 	return (error);
1643 }
1644 
1645 /*
1646  * Handle an int, signed or unsigned.
1647  * Two cases:
1648  *     a variable:  point arg1 at it.
1649  *     a constant:  pass it in arg2.
1650  */
1651 
1652 int
sysctl_handle_int(SYSCTL_HANDLER_ARGS)1653 sysctl_handle_int(SYSCTL_HANDLER_ARGS)
1654 {
1655 	int tmpout, error = 0;
1656 
1657 	/*
1658 	 * Attempt to get a coherent snapshot by making a copy of the data.
1659 	 */
1660 	if (arg1)
1661 		tmpout = *(int *)arg1;
1662 	else
1663 		tmpout = arg2;
1664 	error = SYSCTL_OUT(req, &tmpout, sizeof(int));
1665 
1666 	if (error || !req->newptr)
1667 		return (error);
1668 
1669 	if (!arg1)
1670 		error = EPERM;
1671 	else
1672 		error = SYSCTL_IN(req, arg1, sizeof(int));
1673 	return (error);
1674 }
1675 
1676 /*
1677  * Based on on sysctl_handle_int() convert milliseconds into ticks.
1678  * Note: this is used by TCP.
1679  */
1680 
1681 int
sysctl_msec_to_ticks(SYSCTL_HANDLER_ARGS)1682 sysctl_msec_to_ticks(SYSCTL_HANDLER_ARGS)
1683 {
1684 	int error, s, tt;
1685 
1686 	tt = *(int *)arg1;
1687 	s = (int)((int64_t)tt * 1000 / hz);
1688 
1689 	error = sysctl_handle_int(oidp, &s, 0, req);
1690 	if (error || !req->newptr)
1691 		return (error);
1692 
1693 	tt = (int)((int64_t)s * hz / 1000);
1694 	if (tt < 1)
1695 		return (EINVAL);
1696 
1697 	*(int *)arg1 = tt;
1698 	return (0);
1699 }
1700 
1701 /*
1702  * Handle a long, signed or unsigned.
1703  * Two cases:
1704  *     a variable:  point arg1 at it.
1705  *     a constant:  pass it in arg2.
1706  */
1707 
1708 int
sysctl_handle_long(SYSCTL_HANDLER_ARGS)1709 sysctl_handle_long(SYSCTL_HANDLER_ARGS)
1710 {
1711 	int error = 0;
1712 	long tmplong;
1713 #ifdef SCTL_MASK32
1714 	int tmpint;
1715 #endif
1716 
1717 	/*
1718 	 * Attempt to get a coherent snapshot by making a copy of the data.
1719 	 */
1720 	if (arg1)
1721 		tmplong = *(long *)arg1;
1722 	else
1723 		tmplong = arg2;
1724 #ifdef SCTL_MASK32
1725 	if (req->flags & SCTL_MASK32) {
1726 		tmpint = tmplong;
1727 		error = SYSCTL_OUT(req, &tmpint, sizeof(int));
1728 	} else
1729 #endif
1730 		error = SYSCTL_OUT(req, &tmplong, sizeof(long));
1731 
1732 	if (error || !req->newptr)
1733 		return (error);
1734 
1735 	if (!arg1)
1736 		error = EPERM;
1737 #ifdef SCTL_MASK32
1738 	else if (req->flags & SCTL_MASK32) {
1739 		error = SYSCTL_IN(req, &tmpint, sizeof(int));
1740 		*(long *)arg1 = (long)tmpint;
1741 	}
1742 #endif
1743 	else
1744 		error = SYSCTL_IN(req, arg1, sizeof(long));
1745 	return (error);
1746 }
1747 
1748 /*
1749  * Handle a 64 bit int, signed or unsigned.
1750  * Two cases:
1751  *     a variable:  point arg1 at it.
1752  *     a constant:  pass it in arg2.
1753  */
1754 int
sysctl_handle_64(SYSCTL_HANDLER_ARGS)1755 sysctl_handle_64(SYSCTL_HANDLER_ARGS)
1756 {
1757 	int error = 0;
1758 	uint64_t tmpout;
1759 
1760 	/*
1761 	 * Attempt to get a coherent snapshot by making a copy of the data.
1762 	 */
1763 	if (arg1)
1764 		tmpout = *(uint64_t *)arg1;
1765 	else
1766 		tmpout = arg2;
1767 	error = SYSCTL_OUT(req, &tmpout, sizeof(uint64_t));
1768 
1769 	if (error || !req->newptr)
1770 		return (error);
1771 
1772 	if (!arg1)
1773 		error = EPERM;
1774 	else
1775 		error = SYSCTL_IN(req, arg1, sizeof(uint64_t));
1776 	return (error);
1777 }
1778 
1779 /*
1780  * Handle our generic '\0' terminated 'C' string.
1781  * Two cases:
1782  * 	a variable string:  point arg1 at it, arg2 is max length.
1783  * 	a constant string:  point arg1 at it, arg2 is zero.
1784  */
1785 
1786 int
sysctl_handle_string(SYSCTL_HANDLER_ARGS)1787 sysctl_handle_string(SYSCTL_HANDLER_ARGS)
1788 {
1789 	char *tmparg;
1790 	int error = 0;
1791 
1792 	/*
1793 	 * If the sysctl isn't writable and isn't a preallocated tunable that
1794 	 * can be modified by kenv(2), microoptimise and treat it as a
1795 	 * read-only string.
1796 	 * A zero-length buffer indicates a fixed size read-only
1797 	 * string.  In ddb, don't worry about trying to make a malloced
1798 	 * snapshot.
1799 	 */
1800 	if ((oidp->oid_kind & (CTLFLAG_WR | CTLFLAG_TUN)) == 0 ||
1801 	    arg2 == 0 || kdb_active) {
1802 		size_t outlen;
1803 
1804 		if (arg2 == 0)
1805 			outlen = arg2 = strlen(arg1) + 1;
1806 		else
1807 			outlen = strnlen(arg1, arg2 - 1) + 1;
1808 
1809 		tmparg = req->oldptr != NULL ? arg1 : NULL;
1810 		error = SYSCTL_OUT(req, tmparg, outlen);
1811 	} else {
1812 		size_t outlen;
1813 
1814 		if (req->oldptr != NULL) {
1815 			tmparg = malloc(arg2, M_SYSCTLTMP, M_WAITOK);
1816 			sx_slock(&sysctlstringlock);
1817 			memcpy(tmparg, arg1, arg2);
1818 			sx_sunlock(&sysctlstringlock);
1819 			outlen = strnlen(tmparg, arg2 - 1) + 1;
1820 		} else {
1821 			tmparg = NULL;
1822 			sx_slock(&sysctlstringlock);
1823 			outlen = strnlen(arg1, arg2 - 1) + 1;
1824 			sx_sunlock(&sysctlstringlock);
1825 		}
1826 		error = SYSCTL_OUT(req, tmparg, outlen);
1827 		free(tmparg, M_SYSCTLTMP);
1828 	}
1829 	if (error || !req->newptr)
1830 		return (error);
1831 
1832 	if (req->newlen - req->newidx >= arg2 ||
1833 	    req->newlen - req->newidx < 0) {
1834 		error = EINVAL;
1835 	} else if (req->newlen - req->newidx == 0) {
1836 		sx_xlock(&sysctlstringlock);
1837 		((char *)arg1)[0] = '\0';
1838 		sx_xunlock(&sysctlstringlock);
1839 	} else if (req->newfunc == sysctl_new_kernel) {
1840 		arg2 = req->newlen - req->newidx;
1841 		sx_xlock(&sysctlstringlock);
1842 		error = SYSCTL_IN(req, arg1, arg2);
1843 		if (error == 0) {
1844 			((char *)arg1)[arg2] = '\0';
1845 			req->newidx += arg2;
1846 		}
1847 		sx_xunlock(&sysctlstringlock);
1848 	} else {
1849 		arg2 = req->newlen - req->newidx;
1850 		tmparg = malloc(arg2, M_SYSCTLTMP, M_WAITOK);
1851 
1852 		error = SYSCTL_IN(req, tmparg, arg2);
1853 		if (error) {
1854 			free(tmparg, M_SYSCTLTMP);
1855 			return (error);
1856 		}
1857 
1858 		sx_xlock(&sysctlstringlock);
1859 		memcpy(arg1, tmparg, arg2);
1860 		((char *)arg1)[arg2] = '\0';
1861 		sx_xunlock(&sysctlstringlock);
1862 		free(tmparg, M_SYSCTLTMP);
1863 		req->newidx += arg2;
1864 	}
1865 	return (error);
1866 }
1867 
1868 /*
1869  * Handle any kind of opaque data.
1870  * arg1 points to it, arg2 is the size.
1871  */
1872 
1873 int
sysctl_handle_opaque(SYSCTL_HANDLER_ARGS)1874 sysctl_handle_opaque(SYSCTL_HANDLER_ARGS)
1875 {
1876 	int error, tries;
1877 	u_int generation;
1878 	struct sysctl_req req2;
1879 
1880 	/*
1881 	 * Attempt to get a coherent snapshot, by using the thread
1882 	 * pre-emption counter updated from within mi_switch() to
1883 	 * determine if we were pre-empted during a bcopy() or
1884 	 * copyout(). Make 3 attempts at doing this before giving up.
1885 	 * If we encounter an error, stop immediately.
1886 	 */
1887 	tries = 0;
1888 	req2 = *req;
1889 retry:
1890 	generation = curthread->td_generation;
1891 	error = SYSCTL_OUT(req, arg1, arg2);
1892 	if (error)
1893 		return (error);
1894 	tries++;
1895 	if (generation != curthread->td_generation && tries < 3) {
1896 		*req = req2;
1897 		goto retry;
1898 	}
1899 
1900 	error = SYSCTL_IN(req, arg1, arg2);
1901 
1902 	return (error);
1903 }
1904 
1905 /*
1906  * Based on on sysctl_handle_int() convert microseconds to a sbintime.
1907  */
1908 int
sysctl_usec_to_sbintime(SYSCTL_HANDLER_ARGS)1909 sysctl_usec_to_sbintime(SYSCTL_HANDLER_ARGS)
1910 {
1911 	int error;
1912 	int64_t tt;
1913 	sbintime_t sb;
1914 
1915 	tt = *(int64_t *)arg1;
1916 	sb = sbttous(tt);
1917 
1918 	error = sysctl_handle_64(oidp, &sb, 0, req);
1919 	if (error || !req->newptr)
1920 		return (error);
1921 
1922 	tt = ustosbt(sb);
1923 	*(int64_t *)arg1 = tt;
1924 
1925 	return (0);
1926 }
1927 
1928 /*
1929  * Based on on sysctl_handle_int() convert milliseconds to a sbintime.
1930  */
1931 int
sysctl_msec_to_sbintime(SYSCTL_HANDLER_ARGS)1932 sysctl_msec_to_sbintime(SYSCTL_HANDLER_ARGS)
1933 {
1934 	int error;
1935 	int64_t tt;
1936 	sbintime_t sb;
1937 
1938 	tt = *(int64_t *)arg1;
1939 	sb = sbttoms(tt);
1940 
1941 	error = sysctl_handle_64(oidp, &sb, 0, req);
1942 	if (error || !req->newptr)
1943 		return (error);
1944 
1945 	tt = mstosbt(sb);
1946 	*(int64_t *)arg1 = tt;
1947 
1948 	return (0);
1949 }
1950 
1951 /*
1952  * Convert seconds to a struct timeval.  Intended for use with
1953  * intervals and thus does not permit negative seconds.
1954  */
1955 int
sysctl_sec_to_timeval(SYSCTL_HANDLER_ARGS)1956 sysctl_sec_to_timeval(SYSCTL_HANDLER_ARGS)
1957 {
1958 	struct timeval *tv;
1959 	int error, secs;
1960 
1961 	tv = arg1;
1962 	secs = tv->tv_sec;
1963 
1964 	error = sysctl_handle_int(oidp, &secs, 0, req);
1965 	if (error || req->newptr == NULL)
1966 		return (error);
1967 
1968 	if (secs < 0)
1969 		return (EINVAL);
1970 	tv->tv_sec = secs;
1971 
1972 	return (0);
1973 }
1974 
1975 /*
1976  * Transfer functions to/from kernel space.
1977  * XXX: rather untested at this point
1978  */
1979 static int
sysctl_old_kernel(struct sysctl_req * req,const void * p,size_t l)1980 sysctl_old_kernel(struct sysctl_req *req, const void *p, size_t l)
1981 {
1982 	size_t i = 0;
1983 
1984 	if (req->oldptr) {
1985 		i = l;
1986 		if (req->oldlen <= req->oldidx)
1987 			i = 0;
1988 		else
1989 			if (i > req->oldlen - req->oldidx)
1990 				i = req->oldlen - req->oldidx;
1991 		if (i > 0)
1992 			bcopy(p, (char *)req->oldptr + req->oldidx, i);
1993 	}
1994 	req->oldidx += l;
1995 	if (req->oldptr && i != l)
1996 		return (ENOMEM);
1997 	return (0);
1998 }
1999 
2000 static int
sysctl_new_kernel(struct sysctl_req * req,void * p,size_t l)2001 sysctl_new_kernel(struct sysctl_req *req, void *p, size_t l)
2002 {
2003 	if (!req->newptr)
2004 		return (0);
2005 	if (req->newlen - req->newidx < l)
2006 		return (EINVAL);
2007 	bcopy((const char *)req->newptr + req->newidx, p, l);
2008 	req->newidx += l;
2009 	return (0);
2010 }
2011 
2012 int
kernel_sysctl(struct thread * td,int * name,u_int namelen,void * old,size_t * oldlenp,void * new,size_t newlen,size_t * retval,int flags)2013 kernel_sysctl(struct thread *td, int *name, u_int namelen, void *old,
2014     size_t *oldlenp, void *new, size_t newlen, size_t *retval, int flags)
2015 {
2016 	int error = 0;
2017 	struct sysctl_req req;
2018 
2019 	bzero(&req, sizeof req);
2020 
2021 	req.td = td;
2022 	req.flags = flags;
2023 
2024 	if (oldlenp) {
2025 		req.oldlen = *oldlenp;
2026 	}
2027 	req.validlen = req.oldlen;
2028 
2029 	if (old) {
2030 		req.oldptr= old;
2031 	}
2032 
2033 	if (new != NULL) {
2034 		req.newlen = newlen;
2035 		req.newptr = new;
2036 	}
2037 
2038 	req.oldfunc = sysctl_old_kernel;
2039 	req.newfunc = sysctl_new_kernel;
2040 	req.lock = REQ_UNWIRED;
2041 
2042 	error = sysctl_root(0, name, namelen, &req);
2043 
2044 	if (req.lock == REQ_WIRED && req.validlen > 0)
2045 		vsunlock(req.oldptr, req.validlen);
2046 
2047 	if (error && error != ENOMEM)
2048 		return (error);
2049 
2050 	if (retval) {
2051 		if (req.oldptr && req.oldidx > req.validlen)
2052 			*retval = req.validlen;
2053 		else
2054 			*retval = req.oldidx;
2055 	}
2056 	return (error);
2057 }
2058 
2059 int
kernel_sysctlbyname(struct thread * td,char * name,void * old,size_t * oldlenp,void * new,size_t newlen,size_t * retval,int flags)2060 kernel_sysctlbyname(struct thread *td, char *name, void *old, size_t *oldlenp,
2061     void *new, size_t newlen, size_t *retval, int flags)
2062 {
2063         int oid[CTL_MAXNAME];
2064         size_t oidlen, plen;
2065 	int error;
2066 
2067 	oid[0] = CTL_SYSCTL;
2068 	oid[1] = CTL_SYSCTL_NAME2OID;
2069 	oidlen = sizeof(oid);
2070 
2071 	error = kernel_sysctl(td, oid, 2, oid, &oidlen,
2072 	    (void *)name, strlen(name), &plen, flags);
2073 	if (error)
2074 		return (error);
2075 
2076 	error = kernel_sysctl(td, oid, plen / sizeof(int), old, oldlenp,
2077 	    new, newlen, retval, flags);
2078 	return (error);
2079 }
2080 
2081 /*
2082  * Transfer function to/from user space.
2083  */
2084 static int
sysctl_old_user(struct sysctl_req * req,const void * p,size_t l)2085 sysctl_old_user(struct sysctl_req *req, const void *p, size_t l)
2086 {
2087 	size_t i, len, origidx;
2088 	int error;
2089 
2090 	origidx = req->oldidx;
2091 	req->oldidx += l;
2092 	if (req->oldptr == NULL)
2093 		return (0);
2094 	/*
2095 	 * If we have not wired the user supplied buffer and we are currently
2096 	 * holding locks, drop a witness warning, as it's possible that
2097 	 * write operations to the user page can sleep.
2098 	 */
2099 	if (req->lock != REQ_WIRED)
2100 		WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2101 		    "sysctl_old_user()");
2102 	i = l;
2103 	len = req->validlen;
2104 	if (len <= origidx)
2105 		i = 0;
2106 	else {
2107 		if (i > len - origidx)
2108 			i = len - origidx;
2109 		if (req->lock == REQ_WIRED) {
2110 			error = copyout_nofault(p, (char *)req->oldptr +
2111 			    origidx, i);
2112 		} else
2113 			error = copyout(p, (char *)req->oldptr + origidx, i);
2114 		if (error != 0)
2115 			return (error);
2116 	}
2117 	if (i < l)
2118 		return (ENOMEM);
2119 	return (0);
2120 }
2121 
2122 static int
sysctl_new_user(struct sysctl_req * req,void * p,size_t l)2123 sysctl_new_user(struct sysctl_req *req, void *p, size_t l)
2124 {
2125 	int error;
2126 
2127 	if (!req->newptr)
2128 		return (0);
2129 	if (req->newlen - req->newidx < l)
2130 		return (EINVAL);
2131 	WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
2132 	    "sysctl_new_user()");
2133 	error = copyin((const char *)req->newptr + req->newidx, p, l);
2134 	req->newidx += l;
2135 	return (error);
2136 }
2137 
2138 /*
2139  * Wire the user space destination buffer.  If set to a value greater than
2140  * zero, the len parameter limits the maximum amount of wired memory.
2141  */
2142 int
sysctl_wire_old_buffer(struct sysctl_req * req,size_t len)2143 sysctl_wire_old_buffer(struct sysctl_req *req, size_t len)
2144 {
2145 	int ret;
2146 	size_t wiredlen;
2147 
2148 	wiredlen = (len > 0 && len < req->oldlen) ? len : req->oldlen;
2149 	ret = 0;
2150 	if (req->lock != REQ_WIRED && req->oldptr &&
2151 	    req->oldfunc == sysctl_old_user) {
2152 		if (wiredlen != 0) {
2153 			ret = vslock(req->oldptr, wiredlen);
2154 			if (ret != 0) {
2155 				if (ret != ENOMEM)
2156 					return (ret);
2157 				wiredlen = 0;
2158 			}
2159 		}
2160 		req->lock = REQ_WIRED;
2161 		req->validlen = wiredlen;
2162 	}
2163 	return (0);
2164 }
2165 
2166 int
sysctl_find_oid(int * name,u_int namelen,struct sysctl_oid ** noid,int * nindx,struct sysctl_req * req)2167 sysctl_find_oid(int *name, u_int namelen, struct sysctl_oid **noid,
2168     int *nindx, struct sysctl_req *req)
2169 {
2170 	struct sysctl_oid_list *lsp;
2171 	struct sysctl_oid *oid;
2172 	int indx;
2173 
2174 	SYSCTL_ASSERT_LOCKED();
2175 	lsp = &sysctl__children;
2176 	indx = 0;
2177 	while (indx < CTL_MAXNAME) {
2178 		SLIST_FOREACH(oid, lsp, oid_link) {
2179 			if (oid->oid_number == name[indx])
2180 				break;
2181 		}
2182 		if (oid == NULL)
2183 			return (ENOENT);
2184 
2185 		indx++;
2186 		if ((oid->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
2187 			if (oid->oid_handler != NULL || indx == namelen) {
2188 				*noid = oid;
2189 				if (nindx != NULL)
2190 					*nindx = indx;
2191 				KASSERT((oid->oid_kind & CTLFLAG_DYING) == 0,
2192 				    ("%s found DYING node %p", __func__, oid));
2193 				return (0);
2194 			}
2195 			lsp = SYSCTL_CHILDREN(oid);
2196 		} else if (indx == namelen) {
2197 			if ((oid->oid_kind & CTLFLAG_DORMANT) != 0)
2198 				return (ENOENT);
2199 			*noid = oid;
2200 			if (nindx != NULL)
2201 				*nindx = indx;
2202 			KASSERT((oid->oid_kind & CTLFLAG_DYING) == 0,
2203 			    ("%s found DYING node %p", __func__, oid));
2204 			return (0);
2205 		} else {
2206 			return (ENOTDIR);
2207 		}
2208 	}
2209 	return (ENOENT);
2210 }
2211 
2212 /*
2213  * Traverse our tree, and find the right node, execute whatever it points
2214  * to, and return the resulting error code.
2215  */
2216 
2217 static int
sysctl_root(SYSCTL_HANDLER_ARGS)2218 sysctl_root(SYSCTL_HANDLER_ARGS)
2219 {
2220 	struct sysctl_oid *oid;
2221 	struct rm_priotracker tracker;
2222 	int error, indx, lvl;
2223 
2224 	SYSCTL_RLOCK(&tracker);
2225 
2226 	error = sysctl_find_oid(arg1, arg2, &oid, &indx, req);
2227 	if (error)
2228 		goto out;
2229 
2230 	if ((oid->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
2231 		/*
2232 		 * You can't call a sysctl when it's a node, but has
2233 		 * no handler.  Inform the user that it's a node.
2234 		 * The indx may or may not be the same as namelen.
2235 		 */
2236 		if (oid->oid_handler == NULL) {
2237 			error = EISDIR;
2238 			goto out;
2239 		}
2240 	}
2241 
2242 	/* Is this sysctl writable? */
2243 	if (req->newptr && !(oid->oid_kind & CTLFLAG_WR)) {
2244 		error = EPERM;
2245 		goto out;
2246 	}
2247 
2248 	KASSERT(req->td != NULL, ("sysctl_root(): req->td == NULL"));
2249 
2250 #ifdef CAPABILITY_MODE
2251 	/*
2252 	 * If the process is in capability mode, then don't permit reading or
2253 	 * writing unless specifically granted for the node.
2254 	 */
2255 	if (IN_CAPABILITY_MODE(req->td)) {
2256 		if ((req->oldptr && !(oid->oid_kind & CTLFLAG_CAPRD)) ||
2257 		    (req->newptr && !(oid->oid_kind & CTLFLAG_CAPWR))) {
2258 			error = EPERM;
2259 			goto out;
2260 		}
2261 	}
2262 #endif
2263 
2264 	/* Is this sysctl sensitive to securelevels? */
2265 	if (req->newptr && (oid->oid_kind & CTLFLAG_SECURE)) {
2266 		lvl = (oid->oid_kind & CTLMASK_SECURE) >> CTLSHIFT_SECURE;
2267 		error = securelevel_gt(req->td->td_ucred, lvl);
2268 		if (error)
2269 			goto out;
2270 	}
2271 
2272 	/* Is this sysctl writable by only privileged users? */
2273 	if (req->newptr && !(oid->oid_kind & CTLFLAG_ANYBODY)) {
2274 		int priv;
2275 
2276 		if (oid->oid_kind & CTLFLAG_PRISON)
2277 			priv = PRIV_SYSCTL_WRITEJAIL;
2278 #ifdef VIMAGE
2279 		else if ((oid->oid_kind & CTLFLAG_VNET) &&
2280 		     prison_owns_vnet(req->td->td_ucred))
2281 			priv = PRIV_SYSCTL_WRITEJAIL;
2282 #endif
2283 		else
2284 			priv = PRIV_SYSCTL_WRITE;
2285 		error = priv_check(req->td, priv);
2286 		if (error)
2287 			goto out;
2288 	}
2289 
2290 	if (!oid->oid_handler) {
2291 		error = EINVAL;
2292 		goto out;
2293 	}
2294 
2295 	if ((oid->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
2296 		arg1 = (int *)arg1 + indx;
2297 		arg2 -= indx;
2298 	} else {
2299 		arg1 = oid->oid_arg1;
2300 		arg2 = oid->oid_arg2;
2301 	}
2302 #ifdef MAC
2303 	error = mac_system_check_sysctl(req->td->td_ucred, oid, arg1, arg2,
2304 	    req);
2305 	if (error != 0)
2306 		goto out;
2307 #endif
2308 #ifdef VIMAGE
2309 	if ((oid->oid_kind & CTLFLAG_VNET) && arg1 != NULL)
2310 		arg1 = (void *)(curvnet->vnet_data_base + (uintptr_t)arg1);
2311 #endif
2312 	error = sysctl_root_handler_locked(oid, arg1, arg2, req, &tracker);
2313 
2314 out:
2315 	SYSCTL_RUNLOCK(&tracker);
2316 	return (error);
2317 }
2318 
2319 #ifndef _SYS_SYSPROTO_H_
2320 struct sysctl_args {
2321 	int	*name;
2322 	u_int	namelen;
2323 	void	*old;
2324 	size_t	*oldlenp;
2325 	void	*new;
2326 	size_t	newlen;
2327 };
2328 #endif
2329 int
sys___sysctl(struct thread * td,struct sysctl_args * uap)2330 sys___sysctl(struct thread *td, struct sysctl_args *uap)
2331 {
2332 	int error, i, name[CTL_MAXNAME];
2333 	size_t j;
2334 
2335 	if (uap->namelen > CTL_MAXNAME || uap->namelen < 2)
2336 		return (EINVAL);
2337 
2338  	error = copyin(uap->name, &name, uap->namelen * sizeof(int));
2339  	if (error)
2340 		return (error);
2341 
2342 	error = userland_sysctl(td, name, uap->namelen,
2343 		uap->old, uap->oldlenp, 0,
2344 		uap->new, uap->newlen, &j, 0);
2345 	if (error && error != ENOMEM)
2346 		return (error);
2347 	if (uap->oldlenp) {
2348 		i = copyout(&j, uap->oldlenp, sizeof(j));
2349 		if (i)
2350 			return (i);
2351 	}
2352 	return (error);
2353 }
2354 
2355 int
kern___sysctlbyname(struct thread * td,const char * oname,size_t namelen,void * old,size_t * oldlenp,void * new,size_t newlen,size_t * retval,int flags,bool inkernel)2356 kern___sysctlbyname(struct thread *td, const char *oname, size_t namelen,
2357     void *old, size_t *oldlenp, void *new, size_t newlen, size_t *retval,
2358     int flags, bool inkernel)
2359 {
2360 	int oid[CTL_MAXNAME];
2361 	char namebuf[16];
2362 	char *name;
2363 	size_t oidlen;
2364 	int error;
2365 
2366 	if (namelen > MAXPATHLEN || namelen == 0)
2367 		return (EINVAL);
2368 	name = namebuf;
2369 	if (namelen > sizeof(namebuf))
2370 		name = malloc(namelen, M_SYSCTL, M_WAITOK);
2371 	error = copyin(oname, name, namelen);
2372 	if (error != 0)
2373 		goto out;
2374 
2375 	oid[0] = CTL_SYSCTL;
2376 	oid[1] = CTL_SYSCTL_NAME2OID;
2377 	oidlen = sizeof(oid);
2378 	error = kernel_sysctl(td, oid, 2, oid, &oidlen, (void *)name, namelen,
2379 	    retval, flags);
2380 	if (error != 0)
2381 		goto out;
2382 	error = userland_sysctl(td, oid, *retval / sizeof(int), old, oldlenp,
2383 	    inkernel, new, newlen, retval, flags);
2384 
2385 out:
2386 	if (namelen > sizeof(namebuf))
2387 		free(name, M_SYSCTL);
2388 	return (error);
2389 }
2390 
2391 #ifndef	_SYS_SYSPROTO_H_
2392 struct __sysctlbyname_args {
2393 	const char	*name;
2394 	size_t	namelen;
2395 	void	*old;
2396 	size_t	*oldlenp;
2397 	void	*new;
2398 	size_t	newlen;
2399 };
2400 #endif
2401 int
sys___sysctlbyname(struct thread * td,struct __sysctlbyname_args * uap)2402 sys___sysctlbyname(struct thread *td, struct __sysctlbyname_args *uap)
2403 {
2404 	size_t rv;
2405 	int error;
2406 
2407 	error = kern___sysctlbyname(td, uap->name, uap->namelen, uap->old,
2408 	    uap->oldlenp, uap->new, uap->newlen, &rv, 0, 0);
2409 	if (error != 0)
2410 		return (error);
2411 	if (uap->oldlenp != NULL)
2412 		error = copyout(&rv, uap->oldlenp, sizeof(rv));
2413 
2414 	return (error);
2415 }
2416 
2417 /*
2418  * This is used from various compatibility syscalls too.  That's why name
2419  * must be in kernel space.
2420  */
2421 int
userland_sysctl(struct thread * td,int * name,u_int namelen,void * old,size_t * oldlenp,int inkernel,const void * new,size_t newlen,size_t * retval,int flags)2422 userland_sysctl(struct thread *td, int *name, u_int namelen, void *old,
2423     size_t *oldlenp, int inkernel, const void *new, size_t newlen,
2424     size_t *retval, int flags)
2425 {
2426 	int error = 0, memlocked;
2427 	struct sysctl_req req;
2428 
2429 	bzero(&req, sizeof req);
2430 
2431 	req.td = td;
2432 	req.flags = flags;
2433 
2434 	if (oldlenp) {
2435 		if (inkernel) {
2436 			req.oldlen = *oldlenp;
2437 		} else {
2438 			error = copyin(oldlenp, &req.oldlen, sizeof(*oldlenp));
2439 			if (error)
2440 				return (error);
2441 		}
2442 	}
2443 	req.validlen = req.oldlen;
2444 	req.oldptr = old;
2445 
2446 	if (new != NULL) {
2447 		req.newlen = newlen;
2448 		req.newptr = new;
2449 	}
2450 
2451 	req.oldfunc = sysctl_old_user;
2452 	req.newfunc = sysctl_new_user;
2453 	req.lock = REQ_UNWIRED;
2454 
2455 #ifdef KTRACE
2456 	if (KTRPOINT(curthread, KTR_SYSCTL))
2457 		ktrsysctl(name, namelen);
2458 #endif
2459 	memlocked = 0;
2460 	if (req.oldptr && req.oldlen > 4 * PAGE_SIZE) {
2461 		memlocked = 1;
2462 		sx_xlock(&sysctlmemlock);
2463 	}
2464 	CURVNET_SET(TD_TO_VNET(td));
2465 
2466 	for (;;) {
2467 		req.oldidx = 0;
2468 		req.newidx = 0;
2469 		error = sysctl_root(0, name, namelen, &req);
2470 		if (error != EAGAIN)
2471 			break;
2472 		kern_yield(PRI_USER);
2473 	}
2474 
2475 	CURVNET_RESTORE();
2476 
2477 	if (req.lock == REQ_WIRED && req.validlen > 0)
2478 		vsunlock(req.oldptr, req.validlen);
2479 	if (memlocked)
2480 		sx_xunlock(&sysctlmemlock);
2481 
2482 	if (error && error != ENOMEM)
2483 		return (error);
2484 
2485 	if (retval) {
2486 		if (req.oldptr && req.oldidx > req.validlen)
2487 			*retval = req.validlen;
2488 		else
2489 			*retval = req.oldidx;
2490 	}
2491 	return (error);
2492 }
2493 
2494 /*
2495  * Drain into a sysctl struct.  The user buffer should be wired if a page
2496  * fault would cause issue.
2497  */
2498 static int
sbuf_sysctl_drain(void * arg,const char * data,int len)2499 sbuf_sysctl_drain(void *arg, const char *data, int len)
2500 {
2501 	struct sysctl_req *req = arg;
2502 	int error;
2503 
2504 	error = SYSCTL_OUT(req, data, len);
2505 	KASSERT(error >= 0, ("Got unexpected negative value %d", error));
2506 	return (error == 0 ? len : -error);
2507 }
2508 
2509 struct sbuf *
sbuf_new_for_sysctl(struct sbuf * s,char * buf,int length,struct sysctl_req * req)2510 sbuf_new_for_sysctl(struct sbuf *s, char *buf, int length,
2511     struct sysctl_req *req)
2512 {
2513 
2514 	/* Supply a default buffer size if none given. */
2515 	if (buf == NULL && length == 0)
2516 		length = 64;
2517 	s = sbuf_new(s, buf, length, SBUF_FIXEDLEN | SBUF_INCLUDENUL);
2518 	sbuf_set_drain(s, sbuf_sysctl_drain, req);
2519 	return (s);
2520 }
2521 
2522 #ifdef DDB
2523 
2524 /* The current OID the debugger is working with */
2525 static struct sysctl_oid *g_ddb_oid;
2526 
2527 /* The current flags specified by the user */
2528 static int g_ddb_sysctl_flags;
2529 
2530 /* Check to see if the last sysctl printed */
2531 static int g_ddb_sysctl_printed;
2532 
2533 static const int ctl_sign[CTLTYPE+1] = {
2534 	[CTLTYPE_INT] = 1,
2535 	[CTLTYPE_LONG] = 1,
2536 	[CTLTYPE_S8] = 1,
2537 	[CTLTYPE_S16] = 1,
2538 	[CTLTYPE_S32] = 1,
2539 	[CTLTYPE_S64] = 1,
2540 };
2541 
2542 static const int ctl_size[CTLTYPE+1] = {
2543 	[CTLTYPE_INT] = sizeof(int),
2544 	[CTLTYPE_UINT] = sizeof(u_int),
2545 	[CTLTYPE_LONG] = sizeof(long),
2546 	[CTLTYPE_ULONG] = sizeof(u_long),
2547 	[CTLTYPE_S8] = sizeof(int8_t),
2548 	[CTLTYPE_S16] = sizeof(int16_t),
2549 	[CTLTYPE_S32] = sizeof(int32_t),
2550 	[CTLTYPE_S64] = sizeof(int64_t),
2551 	[CTLTYPE_U8] = sizeof(uint8_t),
2552 	[CTLTYPE_U16] = sizeof(uint16_t),
2553 	[CTLTYPE_U32] = sizeof(uint32_t),
2554 	[CTLTYPE_U64] = sizeof(uint64_t),
2555 };
2556 
2557 #define DB_SYSCTL_NAME_ONLY	0x001	/* Compare with -N */
2558 #define DB_SYSCTL_VALUE_ONLY	0x002	/* Compare with -n */
2559 #define DB_SYSCTL_OPAQUE	0x004	/* Compare with -o */
2560 #define DB_SYSCTL_HEX		0x008	/* Compare with -x */
2561 
2562 #define DB_SYSCTL_SAFE_ONLY	0x100	/* Only simple types */
2563 
2564 static const char db_sysctl_modifs[] = {
2565 	'N', 'n', 'o', 'x',
2566 };
2567 
2568 static const int db_sysctl_modif_values[] = {
2569 	DB_SYSCTL_NAME_ONLY, DB_SYSCTL_VALUE_ONLY,
2570 	DB_SYSCTL_OPAQUE, DB_SYSCTL_HEX,
2571 };
2572 
2573 /* Handlers considered safe to print while recursing */
2574 static int (* const db_safe_handlers[])(SYSCTL_HANDLER_ARGS) = {
2575 	sysctl_handle_bool,
2576 	sysctl_handle_8,
2577 	sysctl_handle_16,
2578 	sysctl_handle_32,
2579 	sysctl_handle_64,
2580 	sysctl_handle_int,
2581 	sysctl_handle_long,
2582 	sysctl_handle_string,
2583 	sysctl_handle_opaque,
2584 };
2585 
2586 /*
2587  * Use in place of sysctl_old_kernel to print sysctl values.
2588  *
2589  * Compare to the output handling in show_var from sbin/sysctl/sysctl.c
2590  */
2591 static int
sysctl_old_ddb(struct sysctl_req * req,const void * ptr,size_t len)2592 sysctl_old_ddb(struct sysctl_req *req, const void *ptr, size_t len)
2593 {
2594 	const u_char *val, *p;
2595 	const char *sep1;
2596 	size_t intlen, slen;
2597 	uintmax_t umv;
2598 	intmax_t mv;
2599 	int sign, ctltype, hexlen, xflag, error;
2600 
2601 	/* Suppress false-positive GCC uninitialized variable warnings */
2602 	mv = 0;
2603 	umv = 0;
2604 
2605 	slen = len;
2606 	val = p = ptr;
2607 
2608 	if (ptr == NULL) {
2609 		error = 0;
2610 		goto out;
2611 	}
2612 
2613 	/* We are going to print */
2614 	g_ddb_sysctl_printed = 1;
2615 
2616 	xflag = g_ddb_sysctl_flags & DB_SYSCTL_HEX;
2617 
2618 	ctltype = (g_ddb_oid->oid_kind & CTLTYPE);
2619 	sign = ctl_sign[ctltype];
2620 	intlen = ctl_size[ctltype];
2621 
2622 	switch (ctltype) {
2623 	case CTLTYPE_NODE:
2624 	case CTLTYPE_STRING:
2625 		db_printf("%.*s", (int) len, (const char *) p);
2626 		error = 0;
2627 		goto out;
2628 
2629 	case CTLTYPE_INT:
2630 	case CTLTYPE_UINT:
2631 	case CTLTYPE_LONG:
2632 	case CTLTYPE_ULONG:
2633 	case CTLTYPE_S8:
2634 	case CTLTYPE_S16:
2635 	case CTLTYPE_S32:
2636 	case CTLTYPE_S64:
2637 	case CTLTYPE_U8:
2638 	case CTLTYPE_U16:
2639 	case CTLTYPE_U32:
2640 	case CTLTYPE_U64:
2641 		hexlen = 2 + (intlen * CHAR_BIT + 3) / 4;
2642 		sep1 = "";
2643 		while (len >= intlen) {
2644 			switch (ctltype) {
2645 			case CTLTYPE_INT:
2646 			case CTLTYPE_UINT:
2647 				umv = *(const u_int *)p;
2648 				mv = *(const int *)p;
2649 				break;
2650 			case CTLTYPE_LONG:
2651 			case CTLTYPE_ULONG:
2652 				umv = *(const u_long *)p;
2653 				mv = *(const long *)p;
2654 				break;
2655 			case CTLTYPE_S8:
2656 			case CTLTYPE_U8:
2657 				umv = *(const uint8_t *)p;
2658 				mv = *(const int8_t *)p;
2659 				break;
2660 			case CTLTYPE_S16:
2661 			case CTLTYPE_U16:
2662 				umv = *(const uint16_t *)p;
2663 				mv = *(const int16_t *)p;
2664 				break;
2665 			case CTLTYPE_S32:
2666 			case CTLTYPE_U32:
2667 				umv = *(const uint32_t *)p;
2668 				mv = *(const int32_t *)p;
2669 				break;
2670 			case CTLTYPE_S64:
2671 			case CTLTYPE_U64:
2672 				umv = *(const uint64_t *)p;
2673 				mv = *(const int64_t *)p;
2674 				break;
2675 			}
2676 
2677 			db_printf("%s", sep1);
2678 			if (xflag)
2679 				db_printf("%#0*jx", hexlen, umv);
2680 			else if (!sign)
2681 				db_printf("%ju", umv);
2682 			else if (g_ddb_oid->oid_fmt[1] == 'K') {
2683 				/* Kelvins are currently unsupported. */
2684 				error = EOPNOTSUPP;
2685 				goto out;
2686 			} else
2687 				db_printf("%jd", mv);
2688 
2689 			sep1 = " ";
2690 			len -= intlen;
2691 			p += intlen;
2692 		}
2693 		error = 0;
2694 		goto out;
2695 
2696 	case CTLTYPE_OPAQUE:
2697 		/* TODO: Support struct functions. */
2698 
2699 		/* FALLTHROUGH */
2700 	default:
2701 		db_printf("Format:%s Length:%zu Dump:0x",
2702 		    g_ddb_oid->oid_fmt, len);
2703 		while (len-- && (xflag || p < val + 16))
2704 			db_printf("%02x", *p++);
2705 		if (!xflag && len > 16)
2706 			db_printf("...");
2707 		error = 0;
2708 		goto out;
2709 	}
2710 
2711 out:
2712 	req->oldidx += slen;
2713 	return (error);
2714 }
2715 
2716 /*
2717  * Avoid setting new sysctl values from the debugger
2718  */
2719 static int
sysctl_new_ddb(struct sysctl_req * req,void * p,size_t l)2720 sysctl_new_ddb(struct sysctl_req *req, void *p, size_t l)
2721 {
2722 
2723 	if (!req->newptr)
2724 		return (0);
2725 
2726 	/* Changing sysctls from the debugger is currently unsupported */
2727 	return (EPERM);
2728 }
2729 
2730 /*
2731  * Run a sysctl handler with the DDB oldfunc and newfunc attached.
2732  * Instead of copying any output to a buffer we'll dump it right to
2733  * the console.
2734  */
2735 static int
db_sysctl(struct sysctl_oid * oidp,int * name,u_int namelen,void * old,size_t * oldlenp,size_t * retval,int flags)2736 db_sysctl(struct sysctl_oid *oidp, int *name, u_int namelen,
2737     void *old, size_t *oldlenp, size_t *retval, int flags)
2738 {
2739 	struct sysctl_req req;
2740 	int error;
2741 
2742 	/* Setup the request */
2743 	bzero(&req, sizeof req);
2744 	req.td = kdb_thread;
2745 	req.oldfunc = sysctl_old_ddb;
2746 	req.newfunc = sysctl_new_ddb;
2747 	req.lock = REQ_UNWIRED;
2748 	if (oldlenp) {
2749 		req.oldlen = *oldlenp;
2750 	}
2751 	req.validlen = req.oldlen;
2752 	if (old) {
2753 		req.oldptr = old;
2754 	}
2755 
2756 	/* Setup our globals for sysctl_old_ddb */
2757 	g_ddb_oid = oidp;
2758 	g_ddb_sysctl_flags = flags;
2759 	g_ddb_sysctl_printed = 0;
2760 
2761 	error = sysctl_root(0, name, namelen, &req);
2762 
2763 	/* Reset globals */
2764 	g_ddb_oid = NULL;
2765 	g_ddb_sysctl_flags = 0;
2766 
2767 	if (retval) {
2768 		if (req.oldptr && req.oldidx > req.validlen)
2769 			*retval = req.validlen;
2770 		else
2771 			*retval = req.oldidx;
2772 	}
2773 	return (error);
2774 }
2775 
2776 /*
2777  * Show a sysctl's name
2778  */
2779 static void
db_show_oid_name(int * oid,size_t nlen)2780 db_show_oid_name(int *oid, size_t nlen)
2781 {
2782 	struct sysctl_oid *oidp;
2783 	int qoid[CTL_MAXNAME+2];
2784 	int error;
2785 
2786 	qoid[0] = 0;
2787 	memcpy(qoid + 2, oid, nlen * sizeof(int));
2788 	qoid[1] = 1;
2789 
2790 	error = sysctl_find_oid(qoid, nlen + 2, &oidp, NULL, NULL);
2791 	if (error)
2792 		db_error("sysctl name oid");
2793 
2794 	error = db_sysctl(oidp, qoid, nlen + 2, NULL, NULL, NULL, 0);
2795 	if (error)
2796 		db_error("sysctl name");
2797 }
2798 
2799 /*
2800  * Check to see if an OID is safe to print from ddb.
2801  */
2802 static bool
db_oid_safe(const struct sysctl_oid * oidp)2803 db_oid_safe(const struct sysctl_oid *oidp)
2804 {
2805 	for (unsigned int i = 0; i < nitems(db_safe_handlers); ++i) {
2806 		if (oidp->oid_handler == db_safe_handlers[i])
2807 			return (true);
2808 	}
2809 
2810 	return (false);
2811 }
2812 
2813 /*
2814  * Show a sysctl at a specific OID
2815  * Compare to the input handling in show_var from sbin/sysctl/sysctl.c
2816  */
2817 static int
db_show_oid(struct sysctl_oid * oidp,int * oid,size_t nlen,int flags)2818 db_show_oid(struct sysctl_oid *oidp, int *oid, size_t nlen, int flags)
2819 {
2820 	int error, xflag, oflag, Nflag, nflag;
2821 	size_t len;
2822 
2823 	xflag = flags & DB_SYSCTL_HEX;
2824 	oflag = flags & DB_SYSCTL_OPAQUE;
2825 	nflag = flags & DB_SYSCTL_VALUE_ONLY;
2826 	Nflag = flags & DB_SYSCTL_NAME_ONLY;
2827 
2828 	if ((oidp->oid_kind & CTLTYPE) == CTLTYPE_OPAQUE &&
2829 	    (!xflag && !oflag))
2830 		return (0);
2831 
2832 	if (Nflag) {
2833 		db_show_oid_name(oid, nlen);
2834 		error = 0;
2835 		goto out;
2836 	}
2837 
2838 	if (!nflag) {
2839 		db_show_oid_name(oid, nlen);
2840 		db_printf(": ");
2841 	}
2842 
2843 	if ((flags & DB_SYSCTL_SAFE_ONLY) && !db_oid_safe(oidp)) {
2844 		db_printf("Skipping, unsafe to print while recursing.");
2845 		error = 0;
2846 		goto out;
2847 	}
2848 
2849 	/* Try once, and ask about the size */
2850 	len = 0;
2851 	error = db_sysctl(oidp, oid, nlen,
2852 	    NULL, NULL, &len, flags);
2853 	if (error)
2854 		goto out;
2855 
2856 	if (!g_ddb_sysctl_printed)
2857 		/* Lie about the size */
2858 		error = db_sysctl(oidp, oid, nlen,
2859 		    (void *) 1, &len, NULL, flags);
2860 
2861 out:
2862 	db_printf("\n");
2863 	return (error);
2864 }
2865 
2866 /*
2867  * Show all sysctls under a specific OID
2868  * Compare to sysctl_all from sbin/sysctl/sysctl.c
2869  */
2870 static int
db_show_sysctl_all(int * oid,size_t len,int flags)2871 db_show_sysctl_all(int *oid, size_t len, int flags)
2872 {
2873 	struct sysctl_oid *oidp;
2874 	int name1[CTL_MAXNAME + 2], name2[CTL_MAXNAME + 2];
2875 	size_t l1, l2;
2876 
2877 	name1[0] = CTL_SYSCTL;
2878 	name1[1] = CTL_SYSCTL_NEXT;
2879 	l1 = 2;
2880 	if (len) {
2881 		memcpy(name1 + 2, oid, len * sizeof(int));
2882 		l1 += len;
2883 	} else {
2884 		name1[2] = CTL_KERN;
2885 		l1++;
2886 	}
2887 	for (;;) {
2888 		int i, error;
2889 
2890 		l2 = sizeof(name2);
2891 		error = kernel_sysctl(kdb_thread, name1, l1,
2892 		    name2, &l2, NULL, 0, &l2, 0);
2893 		if (error != 0) {
2894 			if (error == ENOENT)
2895 				return (0);
2896 			else
2897 				db_error("sysctl(next)");
2898 		}
2899 
2900 		l2 /= sizeof(int);
2901 
2902 		if (l2 < (unsigned int)len)
2903 			return (0);
2904 
2905 		for (i = 0; i < len; i++)
2906 			if (name2[i] != oid[i])
2907 				return (0);
2908 
2909 		/* Find the OID in question */
2910 		error = sysctl_find_oid(name2, l2, &oidp, NULL, NULL);
2911 		if (error)
2912 			return (error);
2913 
2914 		i = db_show_oid(oidp, name2, l2, flags | DB_SYSCTL_SAFE_ONLY);
2915 
2916 		if (db_pager_quit)
2917 			return (0);
2918 
2919 		memcpy(name1+2, name2, l2 * sizeof(int));
2920 		l1 = 2 + l2;
2921 	}
2922 }
2923 
2924 /*
2925  * Show a sysctl by its user facing string
2926  */
2927 static int
db_sysctlbyname(const char * name,int flags)2928 db_sysctlbyname(const char *name, int flags)
2929 {
2930 	struct sysctl_oid *oidp;
2931 	int oid[CTL_MAXNAME];
2932 	int error, nlen;
2933 
2934 	error = name2oid(name, oid, &nlen, &oidp);
2935 	if (error) {
2936 		return (error);
2937 	}
2938 
2939 	if ((oidp->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
2940 		db_show_sysctl_all(oid, nlen, flags);
2941 	} else {
2942 		error = db_show_oid(oidp, oid, nlen, flags);
2943 	}
2944 
2945 	return (error);
2946 }
2947 
2948 static void
db_sysctl_cmd_usage(void)2949 db_sysctl_cmd_usage(void)
2950 {
2951 	db_printf(
2952 	    " sysctl [/Nnox] <sysctl>					    \n"
2953 	    "								    \n"
2954 	    " <sysctl> The name of the sysctl to show.			    \n"
2955 	    "								    \n"
2956 	    " Show a sysctl by hooking into SYSCTL_IN and SYSCTL_OUT.	    \n"
2957 	    " This will work for most sysctls, but should not be used	    \n"
2958 	    " with sysctls that are known to malloc.			    \n"
2959 	    "								    \n"
2960 	    " While recursing any \"unsafe\" sysctls will be skipped.	    \n"
2961 	    " Call sysctl directly on the sysctl to try printing the	    \n"
2962 	    " skipped sysctl. This is unsafe and may make the ddb	    \n"
2963 	    " session unusable.						    \n"
2964 	    "								    \n"
2965 	    " Arguments:						    \n"
2966 	    "	/N	Display only the name of the sysctl.		    \n"
2967 	    "	/n	Display only the value of the sysctl.		    \n"
2968 	    "	/o	Display opaque values.				    \n"
2969 	    "	/x	Display the sysctl in hex.			    \n"
2970 	    "								    \n"
2971 	    "For example:						    \n"
2972 	    "sysctl vm.v_free_min					    \n"
2973 	    "vn.v_free_min: 12669					    \n"
2974 	    );
2975 }
2976 
2977 /*
2978  * Show a specific sysctl similar to sysctl (8).
2979  */
DB_COMMAND_FLAGS(sysctl,db_sysctl_cmd,CS_OWN)2980 DB_COMMAND_FLAGS(sysctl, db_sysctl_cmd, CS_OWN)
2981 {
2982 	char name[TOK_STRING_SIZE];
2983 	int error, i, t, flags;
2984 
2985 	/* Parse the modifiers */
2986 	t = db_read_token();
2987 	if (t == tSLASH || t == tMINUS) {
2988 		t = db_read_token();
2989 		if (t != tIDENT) {
2990 			db_printf("Bad modifier\n");
2991 			error = EINVAL;
2992 			goto out;
2993 		}
2994 		db_strcpy(modif, db_tok_string);
2995 	}
2996 	else {
2997 		db_unread_token(t);
2998 		modif[0] = '\0';
2999 	}
3000 
3001 	flags = 0;
3002 	for (i = 0; i < nitems(db_sysctl_modifs); i++) {
3003 		if (strchr(modif, db_sysctl_modifs[i])) {
3004 			flags |= db_sysctl_modif_values[i];
3005 		}
3006 	}
3007 
3008 	/* Parse the sysctl names */
3009 	t = db_read_token();
3010 	if (t != tIDENT) {
3011 		db_printf("Need sysctl name\n");
3012 		error = EINVAL;
3013 		goto out;
3014 	}
3015 
3016 	/* Copy the name into a temporary buffer */
3017 	db_strcpy(name, db_tok_string);
3018 
3019 	/* Ensure there is no trailing cruft */
3020 	t = db_read_token();
3021 	if (t != tEOL) {
3022 		db_printf("Unexpected sysctl argument\n");
3023 		error = EINVAL;
3024 		goto out;
3025 	}
3026 
3027 	error = db_sysctlbyname(name, flags);
3028 	if (error == ENOENT) {
3029 		db_printf("unknown oid: '%s'\n", db_tok_string);
3030 		goto out;
3031 	} else if (error) {
3032 		db_printf("%s: error: %d\n", db_tok_string, error);
3033 		goto out;
3034 	}
3035 
3036 out:
3037 	/* Ensure we eat all of our text */
3038 	db_flush_lex();
3039 
3040 	if (error == EINVAL) {
3041 		db_sysctl_cmd_usage();
3042 	}
3043 }
3044 
3045 #endif /* DDB */
3046