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