]> CyberLeo.Net >> Repos - FreeBSD/stable/10.git/blob - sys/kern/kern_sysctl.c
MFC r315960: dtrace sched:::preempt should fire only when there is preemption
[FreeBSD/stable/10.git] / sys / kern / kern_sysctl.c
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * This code is derived from software contributed to Berkeley by
6  * Mike Karels at Berkeley Software Design, Inc.
7  *
8  * Quite extensively rewritten by Poul-Henning Kamp of the FreeBSD
9  * project, to make these variables more userfriendly.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 4. Neither the name of the University nor the names of its contributors
20  *    may be used to endorse or promote products derived from this software
21  *    without specific prior written permission.
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
24  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
25  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
26  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
27  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
28  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
29  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
30  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
31  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
32  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33  * SUCH DAMAGE.
34  *
35  *      @(#)kern_sysctl.c       8.4 (Berkeley) 4/14/94
36  */
37
38 #include <sys/cdefs.h>
39 __FBSDID("$FreeBSD$");
40
41 #include "opt_capsicum.h"
42 #include "opt_compat.h"
43 #include "opt_ktrace.h"
44
45 #include <sys/param.h>
46 #include <sys/fail.h>
47 #include <sys/systm.h>
48 #include <sys/capsicum.h>
49 #include <sys/kernel.h>
50 #include <sys/sysctl.h>
51 #include <sys/malloc.h>
52 #include <sys/priv.h>
53 #include <sys/proc.h>
54 #include <sys/jail.h>
55 #include <sys/lock.h>
56 #include <sys/mutex.h>
57 #include <sys/sbuf.h>
58 #include <sys/sx.h>
59 #include <sys/sysproto.h>
60 #include <sys/uio.h>
61 #ifdef KTRACE
62 #include <sys/ktrace.h>
63 #endif
64
65 #include <net/vnet.h>
66
67 #include <security/mac/mac_framework.h>
68
69 #include <vm/vm.h>
70 #include <vm/vm_extern.h>
71
72 static MALLOC_DEFINE(M_SYSCTL, "sysctl", "sysctl internal magic");
73 static MALLOC_DEFINE(M_SYSCTLOID, "sysctloid", "sysctl dynamic oids");
74 static MALLOC_DEFINE(M_SYSCTLTMP, "sysctltmp", "sysctl temp output buffer");
75
76 /*
77  * The sysctllock protects the MIB tree.  It also protects sysctl
78  * contexts used with dynamic sysctls.  The sysctl_register_oid() and
79  * sysctl_unregister_oid() routines require the sysctllock to already
80  * be held, so the sysctl_lock() and sysctl_unlock() routines are
81  * provided for the few places in the kernel which need to use that
82  * API rather than using the dynamic API.  Use of the dynamic API is
83  * strongly encouraged for most code.
84  *
85  * The sysctlmemlock is used to limit the amount of user memory wired for
86  * sysctl requests.  This is implemented by serializing any userland
87  * sysctl requests larger than a single page via an exclusive lock.
88  */
89 static struct sx sysctllock;
90 static struct sx sysctlmemlock;
91
92 #define SYSCTL_XLOCK()          sx_xlock(&sysctllock)
93 #define SYSCTL_XUNLOCK()        sx_xunlock(&sysctllock)
94 #define SYSCTL_ASSERT_XLOCKED() sx_assert(&sysctllock, SA_XLOCKED)
95 #define SYSCTL_INIT()           sx_init(&sysctllock, "sysctl lock")
96 #define SYSCTL_SLEEP(ch, wmesg, timo)                                   \
97                                 sx_sleep(ch, &sysctllock, 0, wmesg, timo)
98
99 static int sysctl_root(SYSCTL_HANDLER_ARGS);
100
101 struct sysctl_oid_list sysctl__children; /* root list */
102
103 static int      sysctl_remove_oid_locked(struct sysctl_oid *oidp, int del,
104                     int recurse);
105
106 static struct sysctl_oid *
107 sysctl_find_oidname(const char *name, struct sysctl_oid_list *list)
108 {
109         struct sysctl_oid *oidp;
110
111         SYSCTL_ASSERT_XLOCKED();
112         SLIST_FOREACH(oidp, list, oid_link) {
113                 if (strcmp(oidp->oid_name, name) == 0) {
114                         return (oidp);
115                 }
116         }
117         return (NULL);
118 }
119
120 /*
121  * Initialization of the MIB tree.
122  *
123  * Order by number in each list.
124  */
125 void
126 sysctl_lock(void)
127 {
128
129         SYSCTL_XLOCK();
130 }
131
132 void
133 sysctl_unlock(void)
134 {
135
136         SYSCTL_XUNLOCK();
137 }
138
139 void
140 sysctl_register_oid(struct sysctl_oid *oidp)
141 {
142         struct sysctl_oid_list *parent = oidp->oid_parent;
143         struct sysctl_oid *p;
144         struct sysctl_oid *q;
145         int oid_number;
146         int timeout = 2;
147
148         /*
149          * First check if another oid with the same name already
150          * exists in the parent's list.
151          */
152         SYSCTL_ASSERT_XLOCKED();
153         p = sysctl_find_oidname(oidp->oid_name, parent);
154         if (p != NULL) {
155                 if ((p->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
156                         p->oid_refcnt++;
157                         return;
158                 } else {
159                         printf("can't re-use a leaf (%s)!\n", p->oid_name);
160                         return;
161                 }
162         }
163         /* get current OID number */
164         oid_number = oidp->oid_number;
165
166 #if (OID_AUTO >= 0)
167 #error "OID_AUTO is expected to be a negative value"
168 #endif  
169         /*
170          * Any negative OID number qualifies as OID_AUTO. Valid OID
171          * numbers should always be positive.
172          *
173          * NOTE: DO NOT change the starting value here, change it in
174          * <sys/sysctl.h>, and make sure it is at least 256 to
175          * accommodate e.g. net.inet.raw as a static sysctl node.
176          */
177         if (oid_number < 0) {
178                 static int newoid;
179
180                 /*
181                  * By decrementing the next OID number we spend less
182                  * time inserting the OIDs into a sorted list.
183                  */
184                 if (--newoid < CTL_AUTO_START)
185                         newoid = 0x7fffffff;
186
187                 oid_number = newoid;
188         }
189
190         /*
191          * Insert the OID into the parent's list sorted by OID number.
192          */
193 retry:
194         q = NULL;
195         SLIST_FOREACH(p, parent, oid_link) {
196                 /* check if the current OID number is in use */
197                 if (oid_number == p->oid_number) {
198                         /* get the next valid OID number */
199                         if (oid_number < CTL_AUTO_START ||
200                             oid_number == 0x7fffffff) {
201                                 /* wraparound - restart */
202                                 oid_number = CTL_AUTO_START;
203                                 /* don't loop forever */
204                                 if (!timeout--)
205                                         panic("sysctl: Out of OID numbers\n");
206                                 goto retry;
207                         } else {
208                                 oid_number++;
209                         }
210                 } else if (oid_number < p->oid_number)
211                         break;
212                 q = p;
213         }
214         /* check for non-auto OID number collision */
215         if (oidp->oid_number >= 0 && oidp->oid_number < CTL_AUTO_START &&
216             oid_number >= CTL_AUTO_START) {
217                 printf("sysctl: OID number(%d) is already in use for '%s'\n",
218                     oidp->oid_number, oidp->oid_name);
219         }
220         /* update the OID number, if any */
221         oidp->oid_number = oid_number;
222         if (q != NULL)
223                 SLIST_INSERT_AFTER(q, oidp, oid_link);
224         else
225                 SLIST_INSERT_HEAD(parent, oidp, oid_link);
226 }
227
228 void
229 sysctl_unregister_oid(struct sysctl_oid *oidp)
230 {
231         struct sysctl_oid *p;
232         int error;
233
234         SYSCTL_ASSERT_XLOCKED();
235         error = ENOENT;
236         if (oidp->oid_number == OID_AUTO) {
237                 error = EINVAL;
238         } else {
239                 SLIST_FOREACH(p, oidp->oid_parent, oid_link) {
240                         if (p == oidp) {
241                                 SLIST_REMOVE(oidp->oid_parent, oidp,
242                                     sysctl_oid, oid_link);
243                                 error = 0;
244                                 break;
245                         }
246                 }
247         }
248
249         /* 
250          * This can happen when a module fails to register and is
251          * being unloaded afterwards.  It should not be a panic()
252          * for normal use.
253          */
254         if (error)
255                 printf("%s: failed to unregister sysctl\n", __func__);
256 }
257
258 /* Initialize a new context to keep track of dynamically added sysctls. */
259 int
260 sysctl_ctx_init(struct sysctl_ctx_list *c)
261 {
262
263         if (c == NULL) {
264                 return (EINVAL);
265         }
266
267         /*
268          * No locking here, the caller is responsible for not adding
269          * new nodes to a context until after this function has
270          * returned.
271          */
272         TAILQ_INIT(c);
273         return (0);
274 }
275
276 /* Free the context, and destroy all dynamic oids registered in this context */
277 int
278 sysctl_ctx_free(struct sysctl_ctx_list *clist)
279 {
280         struct sysctl_ctx_entry *e, *e1;
281         int error;
282
283         error = 0;
284         /*
285          * First perform a "dry run" to check if it's ok to remove oids.
286          * XXX FIXME
287          * XXX This algorithm is a hack. But I don't know any
288          * XXX better solution for now...
289          */
290         SYSCTL_XLOCK();
291         TAILQ_FOREACH(e, clist, link) {
292                 error = sysctl_remove_oid_locked(e->entry, 0, 0);
293                 if (error)
294                         break;
295         }
296         /*
297          * Restore deregistered entries, either from the end,
298          * or from the place where error occurred.
299          * e contains the entry that was not unregistered
300          */
301         if (error)
302                 e1 = TAILQ_PREV(e, sysctl_ctx_list, link);
303         else
304                 e1 = TAILQ_LAST(clist, sysctl_ctx_list);
305         while (e1 != NULL) {
306                 sysctl_register_oid(e1->entry);
307                 e1 = TAILQ_PREV(e1, sysctl_ctx_list, link);
308         }
309         if (error) {
310                 SYSCTL_XUNLOCK();
311                 return(EBUSY);
312         }
313         /* Now really delete the entries */
314         e = TAILQ_FIRST(clist);
315         while (e != NULL) {
316                 e1 = TAILQ_NEXT(e, link);
317                 error = sysctl_remove_oid_locked(e->entry, 1, 0);
318                 if (error)
319                         panic("sysctl_remove_oid: corrupt tree, entry: %s",
320                             e->entry->oid_name);
321                 free(e, M_SYSCTLOID);
322                 e = e1;
323         }
324         SYSCTL_XUNLOCK();
325         return (error);
326 }
327
328 /* Add an entry to the context */
329 struct sysctl_ctx_entry *
330 sysctl_ctx_entry_add(struct sysctl_ctx_list *clist, struct sysctl_oid *oidp)
331 {
332         struct sysctl_ctx_entry *e;
333
334         SYSCTL_ASSERT_XLOCKED();
335         if (clist == NULL || oidp == NULL)
336                 return(NULL);
337         e = malloc(sizeof(struct sysctl_ctx_entry), M_SYSCTLOID, M_WAITOK);
338         e->entry = oidp;
339         TAILQ_INSERT_HEAD(clist, e, link);
340         return (e);
341 }
342
343 /* Find an entry in the context */
344 struct sysctl_ctx_entry *
345 sysctl_ctx_entry_find(struct sysctl_ctx_list *clist, struct sysctl_oid *oidp)
346 {
347         struct sysctl_ctx_entry *e;
348
349         SYSCTL_ASSERT_XLOCKED();
350         if (clist == NULL || oidp == NULL)
351                 return(NULL);
352         TAILQ_FOREACH(e, clist, link) {
353                 if(e->entry == oidp)
354                         return(e);
355         }
356         return (e);
357 }
358
359 /*
360  * Delete an entry from the context.
361  * NOTE: this function doesn't free oidp! You have to remove it
362  * with sysctl_remove_oid().
363  */
364 int
365 sysctl_ctx_entry_del(struct sysctl_ctx_list *clist, struct sysctl_oid *oidp)
366 {
367         struct sysctl_ctx_entry *e;
368
369         if (clist == NULL || oidp == NULL)
370                 return (EINVAL);
371         SYSCTL_XLOCK();
372         e = sysctl_ctx_entry_find(clist, oidp);
373         if (e != NULL) {
374                 TAILQ_REMOVE(clist, e, link);
375                 SYSCTL_XUNLOCK();
376                 free(e, M_SYSCTLOID);
377                 return (0);
378         } else {
379                 SYSCTL_XUNLOCK();
380                 return (ENOENT);
381         }
382 }
383
384 /*
385  * Remove dynamically created sysctl trees.
386  * oidp - top of the tree to be removed
387  * del - if 0 - just deregister, otherwise free up entries as well
388  * recurse - if != 0 traverse the subtree to be deleted
389  */
390 int
391 sysctl_remove_oid(struct sysctl_oid *oidp, int del, int recurse)
392 {
393         int error;
394
395         SYSCTL_XLOCK();
396         error = sysctl_remove_oid_locked(oidp, del, recurse);
397         SYSCTL_XUNLOCK();
398         return (error);
399 }
400
401 int
402 sysctl_remove_name(struct sysctl_oid *parent, const char *name,
403     int del, int recurse)
404 {
405         struct sysctl_oid *p, *tmp;
406         int error;
407
408         error = ENOENT;
409         SYSCTL_XLOCK();
410         SLIST_FOREACH_SAFE(p, SYSCTL_CHILDREN(parent), oid_link, tmp) {
411                 if (strcmp(p->oid_name, name) == 0) {
412                         error = sysctl_remove_oid_locked(p, del, recurse);
413                         break;
414                 }
415         }
416         SYSCTL_XUNLOCK();
417
418         return (error);
419 }
420
421
422 static int
423 sysctl_remove_oid_locked(struct sysctl_oid *oidp, int del, int recurse)
424 {
425         struct sysctl_oid *p, *tmp;
426         int error;
427
428         SYSCTL_ASSERT_XLOCKED();
429         if (oidp == NULL)
430                 return(EINVAL);
431         if ((oidp->oid_kind & CTLFLAG_DYN) == 0) {
432                 printf("Warning: can't remove non-dynamic nodes (%s)!\n",
433                     oidp->oid_name);
434                 return (EINVAL);
435         }
436         /*
437          * WARNING: normal method to do this should be through
438          * sysctl_ctx_free(). Use recursing as the last resort
439          * method to purge your sysctl tree of leftovers...
440          * However, if some other code still references these nodes,
441          * it will panic.
442          */
443         if ((oidp->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
444                 if (oidp->oid_refcnt == 1) {
445                         SLIST_FOREACH_SAFE(p,
446                             SYSCTL_CHILDREN(oidp), oid_link, tmp) {
447                                 if (!recurse) {
448                                         printf("Warning: failed attempt to "
449                                             "remove oid %s with child %s\n",
450                                             oidp->oid_name, p->oid_name);
451                                         return (ENOTEMPTY);
452                                 }
453                                 error = sysctl_remove_oid_locked(p, del,
454                                     recurse);
455                                 if (error)
456                                         return (error);
457                         }
458                         if (del)
459                                 free(SYSCTL_CHILDREN(oidp), M_SYSCTLOID);
460                 }
461         }
462         if (oidp->oid_refcnt > 1 ) {
463                 oidp->oid_refcnt--;
464         } else {
465                 if (oidp->oid_refcnt == 0) {
466                         printf("Warning: bad oid_refcnt=%u (%s)!\n",
467                                 oidp->oid_refcnt, oidp->oid_name);
468                         return (EINVAL);
469                 }
470                 sysctl_unregister_oid(oidp);
471                 if (del) {
472                         /*
473                          * Wait for all threads running the handler to drain.
474                          * This preserves the previous behavior when the
475                          * sysctl lock was held across a handler invocation,
476                          * and is necessary for module unload correctness.
477                          */
478                         while (oidp->oid_running > 0) {
479                                 oidp->oid_kind |= CTLFLAG_DYING;
480                                 SYSCTL_SLEEP(&oidp->oid_running, "oidrm", 0);
481                         }
482                         if (oidp->oid_descr)
483                                 free(__DECONST(char *, oidp->oid_descr),
484                                     M_SYSCTLOID);
485                         free(__DECONST(char *, oidp->oid_name), M_SYSCTLOID);
486                         free(oidp, M_SYSCTLOID);
487                 }
488         }
489         return (0);
490 }
491 /*
492  * Create new sysctls at run time.
493  * clist may point to a valid context initialized with sysctl_ctx_init().
494  */
495 struct sysctl_oid *
496 sysctl_add_oid(struct sysctl_ctx_list *clist, struct sysctl_oid_list *parent,
497         int number, const char *name, int kind, void *arg1, intptr_t arg2,
498         int (*handler)(SYSCTL_HANDLER_ARGS), const char *fmt, const char *descr)
499 {
500         struct sysctl_oid *oidp;
501
502         /* You have to hook up somewhere.. */
503         if (parent == NULL)
504                 return(NULL);
505         /* Check if the node already exists, otherwise create it */
506         SYSCTL_XLOCK();
507         oidp = sysctl_find_oidname(name, parent);
508         if (oidp != NULL) {
509                 if ((oidp->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
510                         oidp->oid_refcnt++;
511                         /* Update the context */
512                         if (clist != NULL)
513                                 sysctl_ctx_entry_add(clist, oidp);
514                         SYSCTL_XUNLOCK();
515                         return (oidp);
516                 } else {
517                         SYSCTL_XUNLOCK();
518                         printf("can't re-use a leaf (%s)!\n", name);
519                         return (NULL);
520                 }
521         }
522         oidp = malloc(sizeof(struct sysctl_oid), M_SYSCTLOID, M_WAITOK|M_ZERO);
523         oidp->oid_parent = parent;
524         SLIST_NEXT(oidp, oid_link) = NULL;
525         oidp->oid_number = number;
526         oidp->oid_refcnt = 1;
527         oidp->oid_name = strdup(name, M_SYSCTLOID);
528         oidp->oid_handler = handler;
529         oidp->oid_kind = CTLFLAG_DYN | kind;
530         if ((kind & CTLTYPE) == CTLTYPE_NODE) {
531                 /* Allocate space for children */
532                 SYSCTL_CHILDREN_SET(oidp, malloc(sizeof(struct sysctl_oid_list),
533                     M_SYSCTLOID, M_WAITOK));
534                 SLIST_INIT(SYSCTL_CHILDREN(oidp));
535                 oidp->oid_arg2 = arg2;
536         } else {
537                 oidp->oid_arg1 = arg1;
538                 oidp->oid_arg2 = arg2;
539         }
540         oidp->oid_fmt = fmt;
541         if (descr)
542                 oidp->oid_descr = strdup(descr, M_SYSCTLOID);
543         /* Update the context, if used */
544         if (clist != NULL)
545                 sysctl_ctx_entry_add(clist, oidp);
546         /* Register this oid */
547         sysctl_register_oid(oidp);
548         SYSCTL_XUNLOCK();
549         return (oidp);
550 }
551
552 /*
553  * Rename an existing oid.
554  */
555 void
556 sysctl_rename_oid(struct sysctl_oid *oidp, const char *name)
557 {
558         char *newname;
559         char *oldname;
560
561         newname = strdup(name, M_SYSCTLOID);
562         SYSCTL_XLOCK();
563         oldname = __DECONST(char *, oidp->oid_name);
564         oidp->oid_name = newname;
565         SYSCTL_XUNLOCK();
566         free(oldname, M_SYSCTLOID);
567 }
568
569 /*
570  * Reparent an existing oid.
571  */
572 int
573 sysctl_move_oid(struct sysctl_oid *oid, struct sysctl_oid_list *parent)
574 {
575         struct sysctl_oid *oidp;
576
577         SYSCTL_XLOCK();
578         if (oid->oid_parent == parent) {
579                 SYSCTL_XUNLOCK();
580                 return (0);
581         }
582         oidp = sysctl_find_oidname(oid->oid_name, parent);
583         if (oidp != NULL) {
584                 SYSCTL_XUNLOCK();
585                 return (EEXIST);
586         }
587         sysctl_unregister_oid(oid);
588         oid->oid_parent = parent;
589         oid->oid_number = OID_AUTO;
590         sysctl_register_oid(oid);
591         SYSCTL_XUNLOCK();
592         return (0);
593 }
594
595 /*
596  * Register the kernel's oids on startup.
597  */
598 SET_DECLARE(sysctl_set, struct sysctl_oid);
599
600 static void
601 sysctl_register_all(void *arg)
602 {
603         struct sysctl_oid **oidp;
604
605         sx_init(&sysctlmemlock, "sysctl mem");
606         SYSCTL_INIT();
607         SYSCTL_XLOCK();
608         SET_FOREACH(oidp, sysctl_set)
609                 sysctl_register_oid(*oidp);
610         SYSCTL_XUNLOCK();
611 }
612 SYSINIT(sysctl, SI_SUB_KMEM, SI_ORDER_ANY, sysctl_register_all, 0);
613
614 /*
615  * "Staff-functions"
616  *
617  * These functions implement a presently undocumented interface 
618  * used by the sysctl program to walk the tree, and get the type
619  * so it can print the value.
620  * This interface is under work and consideration, and should probably
621  * be killed with a big axe by the first person who can find the time.
622  * (be aware though, that the proper interface isn't as obvious as it
623  * may seem, there are various conflicting requirements.
624  *
625  * {0,0}        printf the entire MIB-tree.
626  * {0,1,...}    return the name of the "..." OID.
627  * {0,2,...}    return the next OID.
628  * {0,3}        return the OID of the name in "new"
629  * {0,4,...}    return the kind & format info for the "..." OID.
630  * {0,5,...}    return the description the "..." OID.
631  */
632
633 #ifdef SYSCTL_DEBUG
634 static void
635 sysctl_sysctl_debug_dump_node(struct sysctl_oid_list *l, int i)
636 {
637         int k;
638         struct sysctl_oid *oidp;
639
640         SYSCTL_ASSERT_XLOCKED();
641         SLIST_FOREACH(oidp, l, oid_link) {
642
643                 for (k=0; k<i; k++)
644                         printf(" ");
645
646                 printf("%d %s ", oidp->oid_number, oidp->oid_name);
647
648                 printf("%c%c",
649                         oidp->oid_kind & CTLFLAG_RD ? 'R':' ',
650                         oidp->oid_kind & CTLFLAG_WR ? 'W':' ');
651
652                 if (oidp->oid_handler)
653                         printf(" *Handler");
654
655                 switch (oidp->oid_kind & CTLTYPE) {
656                         case CTLTYPE_NODE:
657                                 printf(" Node\n");
658                                 if (!oidp->oid_handler) {
659                                         sysctl_sysctl_debug_dump_node(
660                                                 oidp->oid_arg1, i+2);
661                                 }
662                                 break;
663                         case CTLTYPE_INT:    printf(" Int\n"); break;
664                         case CTLTYPE_UINT:   printf(" u_int\n"); break;
665                         case CTLTYPE_LONG:   printf(" Long\n"); break;
666                         case CTLTYPE_ULONG:  printf(" u_long\n"); break;
667                         case CTLTYPE_STRING: printf(" String\n"); break;
668                         case CTLTYPE_U64:    printf(" uint64_t\n"); break;
669                         case CTLTYPE_S64:    printf(" int64_t\n"); break;
670                         case CTLTYPE_OPAQUE: printf(" Opaque/struct\n"); break;
671                         default:             printf("\n");
672                 }
673
674         }
675 }
676
677 static int
678 sysctl_sysctl_debug(SYSCTL_HANDLER_ARGS)
679 {
680         int error;
681
682         error = priv_check(req->td, PRIV_SYSCTL_DEBUG);
683         if (error)
684                 return (error);
685         SYSCTL_XLOCK();
686         sysctl_sysctl_debug_dump_node(&sysctl__children, 0);
687         SYSCTL_XUNLOCK();
688         return (ENOENT);
689 }
690
691 SYSCTL_PROC(_sysctl, 0, debug, CTLTYPE_STRING|CTLFLAG_RD,
692         0, 0, sysctl_sysctl_debug, "-", "");
693 #endif
694
695 static int
696 sysctl_sysctl_name(SYSCTL_HANDLER_ARGS)
697 {
698         int *name = (int *) arg1;
699         u_int namelen = arg2;
700         int error = 0;
701         struct sysctl_oid *oid;
702         struct sysctl_oid_list *lsp = &sysctl__children, *lsp2;
703         char buf[10];
704
705         SYSCTL_XLOCK();
706         while (namelen) {
707                 if (!lsp) {
708                         snprintf(buf,sizeof(buf),"%d",*name);
709                         if (req->oldidx)
710                                 error = SYSCTL_OUT(req, ".", 1);
711                         if (!error)
712                                 error = SYSCTL_OUT(req, buf, strlen(buf));
713                         if (error)
714                                 goto out;
715                         namelen--;
716                         name++;
717                         continue;
718                 }
719                 lsp2 = 0;
720                 SLIST_FOREACH(oid, lsp, oid_link) {
721                         if (oid->oid_number != *name)
722                                 continue;
723
724                         if (req->oldidx)
725                                 error = SYSCTL_OUT(req, ".", 1);
726                         if (!error)
727                                 error = SYSCTL_OUT(req, oid->oid_name,
728                                         strlen(oid->oid_name));
729                         if (error)
730                                 goto out;
731
732                         namelen--;
733                         name++;
734
735                         if ((oid->oid_kind & CTLTYPE) != CTLTYPE_NODE) 
736                                 break;
737
738                         if (oid->oid_handler)
739                                 break;
740
741                         lsp2 = SYSCTL_CHILDREN(oid);
742                         break;
743                 }
744                 lsp = lsp2;
745         }
746         error = SYSCTL_OUT(req, "", 1);
747  out:
748         SYSCTL_XUNLOCK();
749         return (error);
750 }
751
752 /*
753  * XXXRW/JA: Shouldn't return name data for nodes that we don't permit in
754  * capability mode.
755  */
756 static SYSCTL_NODE(_sysctl, 1, name, CTLFLAG_RD | CTLFLAG_CAPRD,
757     sysctl_sysctl_name, "");
758
759 static int
760 sysctl_sysctl_next_ls(struct sysctl_oid_list *lsp, int *name, u_int namelen, 
761         int *next, int *len, int level, struct sysctl_oid **oidpp)
762 {
763         struct sysctl_oid *oidp;
764
765         SYSCTL_ASSERT_XLOCKED();
766         *len = level;
767         SLIST_FOREACH(oidp, lsp, oid_link) {
768                 *next = oidp->oid_number;
769                 *oidpp = oidp;
770
771                 if (oidp->oid_kind & CTLFLAG_SKIP)
772                         continue;
773
774                 if (!namelen) {
775                         if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE) 
776                                 return (0);
777                         if (oidp->oid_handler) 
778                                 /* We really should call the handler here...*/
779                                 return (0);
780                         lsp = SYSCTL_CHILDREN(oidp);
781                         if (!sysctl_sysctl_next_ls(lsp, 0, 0, next+1, 
782                                 len, level+1, oidpp))
783                                 return (0);
784                         goto emptynode;
785                 }
786
787                 if (oidp->oid_number < *name)
788                         continue;
789
790                 if (oidp->oid_number > *name) {
791                         if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
792                                 return (0);
793                         if (oidp->oid_handler)
794                                 return (0);
795                         lsp = SYSCTL_CHILDREN(oidp);
796                         if (!sysctl_sysctl_next_ls(lsp, name+1, namelen-1, 
797                                 next+1, len, level+1, oidpp))
798                                 return (0);
799                         goto next;
800                 }
801                 if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
802                         continue;
803
804                 if (oidp->oid_handler)
805                         continue;
806
807                 lsp = SYSCTL_CHILDREN(oidp);
808                 if (!sysctl_sysctl_next_ls(lsp, name+1, namelen-1, next+1, 
809                         len, level+1, oidpp))
810                         return (0);
811         next:
812                 namelen = 1;
813         emptynode:
814                 *len = level;
815         }
816         return (1);
817 }
818
819 static int
820 sysctl_sysctl_next(SYSCTL_HANDLER_ARGS)
821 {
822         int *name = (int *) arg1;
823         u_int namelen = arg2;
824         int i, j, error;
825         struct sysctl_oid *oid;
826         struct sysctl_oid_list *lsp = &sysctl__children;
827         int newoid[CTL_MAXNAME];
828
829         SYSCTL_XLOCK();
830         i = sysctl_sysctl_next_ls(lsp, name, namelen, newoid, &j, 1, &oid);
831         SYSCTL_XUNLOCK();
832         if (i)
833                 return (ENOENT);
834         error = SYSCTL_OUT(req, newoid, j * sizeof (int));
835         return (error);
836 }
837
838 /*
839  * XXXRW/JA: Shouldn't return next data for nodes that we don't permit in
840  * capability mode.
841  */
842 static SYSCTL_NODE(_sysctl, 2, next, CTLFLAG_RD | CTLFLAG_CAPRD,
843     sysctl_sysctl_next, "");
844
845 static int
846 name2oid(char *name, int *oid, int *len, struct sysctl_oid **oidpp)
847 {
848         struct sysctl_oid *oidp;
849         struct sysctl_oid_list *lsp = &sysctl__children;
850         char *p;
851
852         SYSCTL_ASSERT_XLOCKED();
853
854         for (*len = 0; *len < CTL_MAXNAME;) {
855                 p = strsep(&name, ".");
856
857                 oidp = SLIST_FIRST(lsp);
858                 for (;; oidp = SLIST_NEXT(oidp, oid_link)) {
859                         if (oidp == NULL)
860                                 return (ENOENT);
861                         if (strcmp(p, oidp->oid_name) == 0)
862                                 break;
863                 }
864                 *oid++ = oidp->oid_number;
865                 (*len)++;
866
867                 if (name == NULL || *name == '\0') {
868                         if (oidpp)
869                                 *oidpp = oidp;
870                         return (0);
871                 }
872
873                 if ((oidp->oid_kind & CTLTYPE) != CTLTYPE_NODE)
874                         break;
875
876                 if (oidp->oid_handler)
877                         break;
878
879                 lsp = SYSCTL_CHILDREN(oidp);
880         }
881         return (ENOENT);
882 }
883
884 static int
885 sysctl_sysctl_name2oid(SYSCTL_HANDLER_ARGS)
886 {
887         char *p;
888         int error, oid[CTL_MAXNAME], len = 0;
889         struct sysctl_oid *op = 0;
890
891         if (!req->newlen) 
892                 return (ENOENT);
893         if (req->newlen >= MAXPATHLEN)  /* XXX arbitrary, undocumented */
894                 return (ENAMETOOLONG);
895
896         p = malloc(req->newlen+1, M_SYSCTL, M_WAITOK);
897
898         error = SYSCTL_IN(req, p, req->newlen);
899         if (error) {
900                 free(p, M_SYSCTL);
901                 return (error);
902         }
903
904         p [req->newlen] = '\0';
905
906         SYSCTL_XLOCK();
907         error = name2oid(p, oid, &len, &op);
908         SYSCTL_XUNLOCK();
909
910         free(p, M_SYSCTL);
911
912         if (error)
913                 return (error);
914
915         error = SYSCTL_OUT(req, oid, len * sizeof *oid);
916         return (error);
917 }
918
919 /*
920  * XXXRW/JA: Shouldn't return name2oid data for nodes that we don't permit in
921  * capability mode.
922  */
923 SYSCTL_PROC(_sysctl, 3, name2oid,
924     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_ANYBODY | CTLFLAG_MPSAFE
925     | CTLFLAG_CAPRW, 0, 0, sysctl_sysctl_name2oid, "I", "");
926
927 static int
928 sysctl_sysctl_oidfmt(SYSCTL_HANDLER_ARGS)
929 {
930         struct sysctl_oid *oid;
931         int error;
932
933         SYSCTL_XLOCK();
934         error = sysctl_find_oid(arg1, arg2, &oid, NULL, req);
935         if (error)
936                 goto out;
937
938         if (oid->oid_fmt == NULL) {
939                 error = ENOENT;
940                 goto out;
941         }
942         error = SYSCTL_OUT(req, &oid->oid_kind, sizeof(oid->oid_kind));
943         if (error)
944                 goto out;
945         error = SYSCTL_OUT(req, oid->oid_fmt, strlen(oid->oid_fmt) + 1);
946  out:
947         SYSCTL_XUNLOCK();
948         return (error);
949 }
950
951
952 static SYSCTL_NODE(_sysctl, 4, oidfmt, CTLFLAG_RD|CTLFLAG_MPSAFE|CTLFLAG_CAPRD,
953     sysctl_sysctl_oidfmt, "");
954
955 static int
956 sysctl_sysctl_oiddescr(SYSCTL_HANDLER_ARGS)
957 {
958         struct sysctl_oid *oid;
959         int error;
960
961         SYSCTL_XLOCK();
962         error = sysctl_find_oid(arg1, arg2, &oid, NULL, req);
963         if (error)
964                 goto out;
965
966         if (oid->oid_descr == NULL) {
967                 error = ENOENT;
968                 goto out;
969         }
970         error = SYSCTL_OUT(req, oid->oid_descr, strlen(oid->oid_descr) + 1);
971  out:
972         SYSCTL_XUNLOCK();
973         return (error);
974 }
975
976 static SYSCTL_NODE(_sysctl, 5, oiddescr, CTLFLAG_RD|CTLFLAG_CAPRD,
977     sysctl_sysctl_oiddescr, "");
978
979 /*
980  * Default "handler" functions.
981  */
982
983 /*
984  * Handle an int, signed or unsigned.
985  * Two cases:
986  *     a variable:  point arg1 at it.
987  *     a constant:  pass it in arg2.
988  */
989
990 int
991 sysctl_handle_int(SYSCTL_HANDLER_ARGS)
992 {
993         int tmpout, error = 0;
994
995         /*
996          * Attempt to get a coherent snapshot by making a copy of the data.
997          */
998         if (arg1)
999                 tmpout = *(int *)arg1;
1000         else
1001                 tmpout = arg2;
1002         error = SYSCTL_OUT(req, &tmpout, sizeof(int));
1003
1004         if (error || !req->newptr)
1005                 return (error);
1006
1007         if (!arg1)
1008                 error = EPERM;
1009         else
1010                 error = SYSCTL_IN(req, arg1, sizeof(int));
1011         return (error);
1012 }
1013
1014 /*
1015  * Based on on sysctl_handle_int() convert milliseconds into ticks.
1016  * Note: this is used by TCP.
1017  */
1018
1019 int
1020 sysctl_msec_to_ticks(SYSCTL_HANDLER_ARGS)
1021 {
1022         int error, s, tt;
1023
1024         tt = *(int *)arg1;
1025         s = (int)((int64_t)tt * 1000 / hz);
1026
1027         error = sysctl_handle_int(oidp, &s, 0, req);
1028         if (error || !req->newptr)
1029                 return (error);
1030
1031         tt = (int)((int64_t)s * hz / 1000);
1032         if (tt < 1)
1033                 return (EINVAL);
1034
1035         *(int *)arg1 = tt;
1036         return (0);
1037 }
1038
1039
1040 /*
1041  * Handle a long, signed or unsigned.
1042  * Two cases:
1043  *     a variable:  point arg1 at it.
1044  *     a constant:  pass it in arg2.
1045  */
1046
1047 int
1048 sysctl_handle_long(SYSCTL_HANDLER_ARGS)
1049 {
1050         int error = 0;
1051         long tmplong;
1052 #ifdef SCTL_MASK32
1053         int tmpint;
1054 #endif
1055
1056         /*
1057          * Attempt to get a coherent snapshot by making a copy of the data.
1058          */
1059         if (arg1)
1060                 tmplong = *(long *)arg1;
1061         else
1062                 tmplong = arg2;
1063 #ifdef SCTL_MASK32
1064         if (req->flags & SCTL_MASK32) {
1065                 tmpint = tmplong;
1066                 error = SYSCTL_OUT(req, &tmpint, sizeof(int));
1067         } else
1068 #endif
1069                 error = SYSCTL_OUT(req, &tmplong, sizeof(long));
1070
1071         if (error || !req->newptr)
1072                 return (error);
1073
1074         if (!arg1)
1075                 error = EPERM;
1076 #ifdef SCTL_MASK32
1077         else if (req->flags & SCTL_MASK32) {
1078                 error = SYSCTL_IN(req, &tmpint, sizeof(int));
1079                 *(long *)arg1 = (long)tmpint;
1080         }
1081 #endif
1082         else
1083                 error = SYSCTL_IN(req, arg1, sizeof(long));
1084         return (error);
1085 }
1086
1087 /*
1088  * Handle a 64 bit int, signed or unsigned.
1089  * Two cases:
1090  *     a variable:  point arg1 at it.
1091  *     a constant:  pass it in arg2.
1092  */
1093 int
1094 sysctl_handle_64(SYSCTL_HANDLER_ARGS)
1095 {
1096         int error = 0;
1097         uint64_t tmpout;
1098
1099         /*
1100          * Attempt to get a coherent snapshot by making a copy of the data.
1101          */
1102         if (arg1)
1103                 tmpout = *(uint64_t *)arg1;
1104         else
1105                 tmpout = arg2;
1106         error = SYSCTL_OUT(req, &tmpout, sizeof(uint64_t));
1107
1108         if (error || !req->newptr)
1109                 return (error);
1110
1111         if (!arg1)
1112                 error = EPERM;
1113         else
1114                 error = SYSCTL_IN(req, arg1, sizeof(uint64_t));
1115         return (error);
1116 }
1117
1118 /*
1119  * Handle our generic '\0' terminated 'C' string.
1120  * Two cases:
1121  *      a variable string:  point arg1 at it, arg2 is max length.
1122  *      a constant string:  point arg1 at it, arg2 is zero.
1123  */
1124
1125 int
1126 sysctl_handle_string(SYSCTL_HANDLER_ARGS)
1127 {
1128         int error=0;
1129         char *tmparg;
1130         size_t outlen;
1131
1132         /*
1133          * Attempt to get a coherent snapshot by copying to a
1134          * temporary kernel buffer.
1135          */
1136 retry:
1137         outlen = strlen((char *)arg1)+1;
1138         tmparg = malloc(outlen, M_SYSCTLTMP, M_WAITOK);
1139
1140         if (strlcpy(tmparg, (char *)arg1, outlen) >= outlen) {
1141                 free(tmparg, M_SYSCTLTMP);
1142                 goto retry;
1143         }
1144
1145         error = SYSCTL_OUT(req, tmparg, outlen);
1146         free(tmparg, M_SYSCTLTMP);
1147
1148         if (error || !req->newptr)
1149                 return (error);
1150
1151         if ((req->newlen - req->newidx) >= arg2) {
1152                 error = EINVAL;
1153         } else {
1154                 arg2 = (req->newlen - req->newidx);
1155                 error = SYSCTL_IN(req, arg1, arg2);
1156                 ((char *)arg1)[arg2] = '\0';
1157         }
1158
1159         return (error);
1160 }
1161
1162 /*
1163  * Handle any kind of opaque data.
1164  * arg1 points to it, arg2 is the size.
1165  */
1166
1167 int
1168 sysctl_handle_opaque(SYSCTL_HANDLER_ARGS)
1169 {
1170         int error, tries;
1171         u_int generation;
1172         struct sysctl_req req2;
1173
1174         /*
1175          * Attempt to get a coherent snapshot, by using the thread
1176          * pre-emption counter updated from within mi_switch() to
1177          * determine if we were pre-empted during a bcopy() or
1178          * copyout(). Make 3 attempts at doing this before giving up.
1179          * If we encounter an error, stop immediately.
1180          */
1181         tries = 0;
1182         req2 = *req;
1183 retry:
1184         generation = curthread->td_generation;
1185         error = SYSCTL_OUT(req, arg1, arg2);
1186         if (error)
1187                 return (error);
1188         tries++;
1189         if (generation != curthread->td_generation && tries < 3) {
1190                 *req = req2;
1191                 goto retry;
1192         }
1193
1194         error = SYSCTL_IN(req, arg1, arg2);
1195
1196         return (error);
1197 }
1198
1199 /*
1200  * Transfer functions to/from kernel space.
1201  * XXX: rather untested at this point
1202  */
1203 static int
1204 sysctl_old_kernel(struct sysctl_req *req, const void *p, size_t l)
1205 {
1206         size_t i = 0;
1207
1208         if (req->oldptr) {
1209                 i = l;
1210                 if (req->oldlen <= req->oldidx)
1211                         i = 0;
1212                 else
1213                         if (i > req->oldlen - req->oldidx)
1214                                 i = req->oldlen - req->oldidx;
1215                 if (i > 0)
1216                         bcopy(p, (char *)req->oldptr + req->oldidx, i);
1217         }
1218         req->oldidx += l;
1219         if (req->oldptr && i != l)
1220                 return (ENOMEM);
1221         return (0);
1222 }
1223
1224 static int
1225 sysctl_new_kernel(struct sysctl_req *req, void *p, size_t l)
1226 {
1227         if (!req->newptr)
1228                 return (0);
1229         if (req->newlen - req->newidx < l)
1230                 return (EINVAL);
1231         bcopy((char *)req->newptr + req->newidx, p, l);
1232         req->newidx += l;
1233         return (0);
1234 }
1235
1236 int
1237 kernel_sysctl(struct thread *td, int *name, u_int namelen, void *old,
1238     size_t *oldlenp, void *new, size_t newlen, size_t *retval, int flags)
1239 {
1240         int error = 0;
1241         struct sysctl_req req;
1242
1243         bzero(&req, sizeof req);
1244
1245         req.td = td;
1246         req.flags = flags;
1247
1248         if (oldlenp) {
1249                 req.oldlen = *oldlenp;
1250         }
1251         req.validlen = req.oldlen;
1252
1253         if (old) {
1254                 req.oldptr= old;
1255         }
1256
1257         if (new != NULL) {
1258                 req.newlen = newlen;
1259                 req.newptr = new;
1260         }
1261
1262         req.oldfunc = sysctl_old_kernel;
1263         req.newfunc = sysctl_new_kernel;
1264         req.lock = REQ_UNWIRED;
1265
1266         SYSCTL_XLOCK();
1267         error = sysctl_root(0, name, namelen, &req);
1268         SYSCTL_XUNLOCK();
1269
1270         if (req.lock == REQ_WIRED && req.validlen > 0)
1271                 vsunlock(req.oldptr, req.validlen);
1272
1273         if (error && error != ENOMEM)
1274                 return (error);
1275
1276         if (retval) {
1277                 if (req.oldptr && req.oldidx > req.validlen)
1278                         *retval = req.validlen;
1279                 else
1280                         *retval = req.oldidx;
1281         }
1282         return (error);
1283 }
1284
1285 int
1286 kernel_sysctlbyname(struct thread *td, char *name, void *old, size_t *oldlenp,
1287     void *new, size_t newlen, size_t *retval, int flags)
1288 {
1289         int oid[CTL_MAXNAME];
1290         size_t oidlen, plen;
1291         int error;
1292
1293         oid[0] = 0;             /* sysctl internal magic */
1294         oid[1] = 3;             /* name2oid */
1295         oidlen = sizeof(oid);
1296
1297         error = kernel_sysctl(td, oid, 2, oid, &oidlen,
1298             (void *)name, strlen(name), &plen, flags);
1299         if (error)
1300                 return (error);
1301
1302         error = kernel_sysctl(td, oid, plen / sizeof(int), old, oldlenp,
1303             new, newlen, retval, flags);
1304         return (error);
1305 }
1306
1307 /*
1308  * Transfer function to/from user space.
1309  */
1310 static int
1311 sysctl_old_user(struct sysctl_req *req, const void *p, size_t l)
1312 {
1313         size_t i, len, origidx;
1314         int error;
1315
1316         origidx = req->oldidx;
1317         req->oldidx += l;
1318         if (req->oldptr == NULL)
1319                 return (0);
1320         /*
1321          * If we have not wired the user supplied buffer and we are currently
1322          * holding locks, drop a witness warning, as it's possible that
1323          * write operations to the user page can sleep.
1324          */
1325         if (req->lock != REQ_WIRED)
1326                 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1327                     "sysctl_old_user()");
1328         i = l;
1329         len = req->validlen;
1330         if (len <= origidx)
1331                 i = 0;
1332         else {
1333                 if (i > len - origidx)
1334                         i = len - origidx;
1335                 if (req->lock == REQ_WIRED) {
1336                         error = copyout_nofault(p, (char *)req->oldptr +
1337                             origidx, i);
1338                 } else
1339                         error = copyout(p, (char *)req->oldptr + origidx, i);
1340                 if (error != 0)
1341                         return (error);
1342         }
1343         if (i < l)
1344                 return (ENOMEM);
1345         return (0);
1346 }
1347
1348 static int
1349 sysctl_new_user(struct sysctl_req *req, void *p, size_t l)
1350 {
1351         int error;
1352
1353         if (!req->newptr)
1354                 return (0);
1355         if (req->newlen - req->newidx < l)
1356                 return (EINVAL);
1357         WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
1358             "sysctl_new_user()");
1359         error = copyin((char *)req->newptr + req->newidx, p, l);
1360         req->newidx += l;
1361         return (error);
1362 }
1363
1364 /*
1365  * Wire the user space destination buffer.  If set to a value greater than
1366  * zero, the len parameter limits the maximum amount of wired memory.
1367  */
1368 int
1369 sysctl_wire_old_buffer(struct sysctl_req *req, size_t len)
1370 {
1371         int ret;
1372         size_t wiredlen;
1373
1374         wiredlen = (len > 0 && len < req->oldlen) ? len : req->oldlen;
1375         ret = 0;
1376         if (req->lock != REQ_WIRED && req->oldptr &&
1377             req->oldfunc == sysctl_old_user) {
1378                 if (wiredlen != 0) {
1379                         ret = vslock(req->oldptr, wiredlen);
1380                         if (ret != 0) {
1381                                 if (ret != ENOMEM)
1382                                         return (ret);
1383                                 wiredlen = 0;
1384                         }
1385                 }
1386                 req->lock = REQ_WIRED;
1387                 req->validlen = wiredlen;
1388         }
1389         return (0);
1390 }
1391
1392 int
1393 sysctl_find_oid(int *name, u_int namelen, struct sysctl_oid **noid,
1394     int *nindx, struct sysctl_req *req)
1395 {
1396         struct sysctl_oid_list *lsp;
1397         struct sysctl_oid *oid;
1398         int indx;
1399
1400         SYSCTL_ASSERT_XLOCKED();
1401         lsp = &sysctl__children;
1402         indx = 0;
1403         while (indx < CTL_MAXNAME) {
1404                 SLIST_FOREACH(oid, lsp, oid_link) {
1405                         if (oid->oid_number == name[indx])
1406                                 break;
1407                 }
1408                 if (oid == NULL)
1409                         return (ENOENT);
1410
1411                 indx++;
1412                 if ((oid->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
1413                         if (oid->oid_handler != NULL || indx == namelen) {
1414                                 *noid = oid;
1415                                 if (nindx != NULL)
1416                                         *nindx = indx;
1417                                 KASSERT((oid->oid_kind & CTLFLAG_DYING) == 0,
1418                                     ("%s found DYING node %p", __func__, oid));
1419                                 return (0);
1420                         }
1421                         lsp = SYSCTL_CHILDREN(oid);
1422                 } else if (indx == namelen) {
1423                         *noid = oid;
1424                         if (nindx != NULL)
1425                                 *nindx = indx;
1426                         KASSERT((oid->oid_kind & CTLFLAG_DYING) == 0,
1427                             ("%s found DYING node %p", __func__, oid));
1428                         return (0);
1429                 } else {
1430                         return (ENOTDIR);
1431                 }
1432         }
1433         return (ENOENT);
1434 }
1435
1436 /*
1437  * Traverse our tree, and find the right node, execute whatever it points
1438  * to, and return the resulting error code.
1439  */
1440
1441 static int
1442 sysctl_root(SYSCTL_HANDLER_ARGS)
1443 {
1444         struct sysctl_oid *oid;
1445         int error, indx, lvl;
1446
1447         SYSCTL_ASSERT_XLOCKED();
1448
1449         error = sysctl_find_oid(arg1, arg2, &oid, &indx, req);
1450         if (error)
1451                 return (error);
1452
1453         if ((oid->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
1454                 /*
1455                  * You can't call a sysctl when it's a node, but has
1456                  * no handler.  Inform the user that it's a node.
1457                  * The indx may or may not be the same as namelen.
1458                  */
1459                 if (oid->oid_handler == NULL)
1460                         return (EISDIR);
1461         }
1462
1463         /* Is this sysctl writable? */
1464         if (req->newptr && !(oid->oid_kind & CTLFLAG_WR))
1465                 return (EPERM);
1466
1467         KASSERT(req->td != NULL, ("sysctl_root(): req->td == NULL"));
1468
1469 #ifdef CAPABILITY_MODE
1470         /*
1471          * If the process is in capability mode, then don't permit reading or
1472          * writing unless specifically granted for the node.
1473          */
1474         if (IN_CAPABILITY_MODE(req->td)) {
1475                 if (req->oldptr && !(oid->oid_kind & CTLFLAG_CAPRD))
1476                         return (EPERM);
1477                 if (req->newptr && !(oid->oid_kind & CTLFLAG_CAPWR))
1478                         return (EPERM);
1479         }
1480 #endif
1481
1482         /* Is this sysctl sensitive to securelevels? */
1483         if (req->newptr && (oid->oid_kind & CTLFLAG_SECURE)) {
1484                 lvl = (oid->oid_kind & CTLMASK_SECURE) >> CTLSHIFT_SECURE;
1485                 error = securelevel_gt(req->td->td_ucred, lvl);
1486                 if (error)
1487                         return (error);
1488         }
1489
1490         /* Is this sysctl writable by only privileged users? */
1491         if (req->newptr && !(oid->oid_kind & CTLFLAG_ANYBODY)) {
1492                 int priv;
1493
1494                 if (oid->oid_kind & CTLFLAG_PRISON)
1495                         priv = PRIV_SYSCTL_WRITEJAIL;
1496 #ifdef VIMAGE
1497                 else if ((oid->oid_kind & CTLFLAG_VNET) &&
1498                      prison_owns_vnet(req->td->td_ucred))
1499                         priv = PRIV_SYSCTL_WRITEJAIL;
1500 #endif
1501                 else
1502                         priv = PRIV_SYSCTL_WRITE;
1503                 error = priv_check(req->td, priv);
1504                 if (error)
1505                         return (error);
1506         }
1507
1508         if (!oid->oid_handler)
1509                 return (EINVAL);
1510
1511         if ((oid->oid_kind & CTLTYPE) == CTLTYPE_NODE) {
1512                 arg1 = (int *)arg1 + indx;
1513                 arg2 -= indx;
1514         } else {
1515                 arg1 = oid->oid_arg1;
1516                 arg2 = oid->oid_arg2;
1517         }
1518 #ifdef MAC
1519         error = mac_system_check_sysctl(req->td->td_ucred, oid, arg1, arg2,
1520             req);
1521         if (error != 0)
1522                 return (error);
1523 #endif
1524         oid->oid_running++;
1525         SYSCTL_XUNLOCK();
1526 #ifdef VIMAGE
1527         if ((oid->oid_kind & CTLFLAG_VNET) && arg1 != NULL)
1528                 arg1 = (void *)(curvnet->vnet_data_base + (uintptr_t)arg1);
1529 #endif
1530         if (!(oid->oid_kind & CTLFLAG_MPSAFE))
1531                 mtx_lock(&Giant);
1532         error = oid->oid_handler(oid, arg1, arg2, req);
1533         if (!(oid->oid_kind & CTLFLAG_MPSAFE))
1534                 mtx_unlock(&Giant);
1535
1536         KFAIL_POINT_ERROR(_debug_fail_point, sysctl_running, error);
1537
1538         SYSCTL_XLOCK();
1539         oid->oid_running--;
1540         if (oid->oid_running == 0 && (oid->oid_kind & CTLFLAG_DYING) != 0)
1541                 wakeup(&oid->oid_running);
1542         return (error);
1543 }
1544
1545 #ifndef _SYS_SYSPROTO_H_
1546 struct sysctl_args {
1547         int     *name;
1548         u_int   namelen;
1549         void    *old;
1550         size_t  *oldlenp;
1551         void    *new;
1552         size_t  newlen;
1553 };
1554 #endif
1555 int
1556 sys___sysctl(struct thread *td, struct sysctl_args *uap)
1557 {
1558         int error, i, name[CTL_MAXNAME];
1559         size_t j;
1560
1561         if (uap->namelen > CTL_MAXNAME || uap->namelen < 2)
1562                 return (EINVAL);
1563
1564         error = copyin(uap->name, &name, uap->namelen * sizeof(int));
1565         if (error)
1566                 return (error);
1567
1568         error = userland_sysctl(td, name, uap->namelen,
1569                 uap->old, uap->oldlenp, 0,
1570                 uap->new, uap->newlen, &j, 0);
1571         if (error && error != ENOMEM)
1572                 return (error);
1573         if (uap->oldlenp) {
1574                 i = copyout(&j, uap->oldlenp, sizeof(j));
1575                 if (i)
1576                         return (i);
1577         }
1578         return (error);
1579 }
1580
1581 /*
1582  * This is used from various compatibility syscalls too.  That's why name
1583  * must be in kernel space.
1584  */
1585 int
1586 userland_sysctl(struct thread *td, int *name, u_int namelen, void *old,
1587     size_t *oldlenp, int inkernel, void *new, size_t newlen, size_t *retval,
1588     int flags)
1589 {
1590         int error = 0, memlocked;
1591         struct sysctl_req req;
1592
1593         bzero(&req, sizeof req);
1594
1595         req.td = td;
1596         req.flags = flags;
1597
1598         if (oldlenp) {
1599                 if (inkernel) {
1600                         req.oldlen = *oldlenp;
1601                 } else {
1602                         error = copyin(oldlenp, &req.oldlen, sizeof(*oldlenp));
1603                         if (error)
1604                                 return (error);
1605                 }
1606         }
1607         req.validlen = req.oldlen;
1608
1609         if (old) {
1610                 if (!useracc(old, req.oldlen, VM_PROT_WRITE))
1611                         return (EFAULT);
1612                 req.oldptr= old;
1613         }
1614
1615         if (new != NULL) {
1616                 if (!useracc(new, newlen, VM_PROT_READ))
1617                         return (EFAULT);
1618                 req.newlen = newlen;
1619                 req.newptr = new;
1620         }
1621
1622         req.oldfunc = sysctl_old_user;
1623         req.newfunc = sysctl_new_user;
1624         req.lock = REQ_UNWIRED;
1625
1626 #ifdef KTRACE
1627         if (KTRPOINT(curthread, KTR_SYSCTL))
1628                 ktrsysctl(name, namelen);
1629 #endif
1630
1631         if (req.oldlen > PAGE_SIZE) {
1632                 memlocked = 1;
1633                 sx_xlock(&sysctlmemlock);
1634         } else
1635                 memlocked = 0;
1636         CURVNET_SET(TD_TO_VNET(td));
1637
1638         for (;;) {
1639                 req.oldidx = 0;
1640                 req.newidx = 0;
1641                 SYSCTL_XLOCK();
1642                 error = sysctl_root(0, name, namelen, &req);
1643                 SYSCTL_XUNLOCK();
1644                 if (error != EAGAIN)
1645                         break;
1646                 kern_yield(PRI_USER);
1647         }
1648
1649         CURVNET_RESTORE();
1650
1651         if (req.lock == REQ_WIRED && req.validlen > 0)
1652                 vsunlock(req.oldptr, req.validlen);
1653         if (memlocked)
1654                 sx_xunlock(&sysctlmemlock);
1655
1656         if (error && error != ENOMEM)
1657                 return (error);
1658
1659         if (retval) {
1660                 if (req.oldptr && req.oldidx > req.validlen)
1661                         *retval = req.validlen;
1662                 else
1663                         *retval = req.oldidx;
1664         }
1665         return (error);
1666 }
1667
1668 /*
1669  * Drain into a sysctl struct.  The user buffer should be wired if a page
1670  * fault would cause issue.
1671  */
1672 static int
1673 sbuf_sysctl_drain(void *arg, const char *data, int len)
1674 {
1675         struct sysctl_req *req = arg;
1676         int error;
1677
1678         error = SYSCTL_OUT(req, data, len);
1679         KASSERT(error >= 0, ("Got unexpected negative value %d", error));
1680         return (error == 0 ? len : -error);
1681 }
1682
1683 struct sbuf *
1684 sbuf_new_for_sysctl(struct sbuf *s, char *buf, int length,
1685     struct sysctl_req *req)
1686 {
1687
1688         s = sbuf_new(s, buf, length, SBUF_FIXEDLEN);
1689         sbuf_set_drain(s, sbuf_sysctl_drain, req);
1690         return (s);
1691 }