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