2 * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
4 * Copyright (c) 1998 Michael Smith
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * The unified bootloader passes us a pointer to a preserved copy of
31 * bootstrap/kernel environment variables. We convert them to a
32 * dynamic array of strings later when the VM subsystem is up.
34 * We make these available through the kenv(2) syscall for userland
35 * and through kern_getenv()/freeenv() kern_setenv() kern_unsetenv() testenv() for
39 #include <sys/cdefs.h>
40 __FBSDID("$FreeBSD$");
42 #include <sys/param.h>
44 #include <sys/queue.h>
46 #include <sys/malloc.h>
47 #include <sys/mutex.h>
50 #include <sys/kernel.h>
51 #include <sys/systm.h>
52 #include <sys/sysent.h>
53 #include <sys/sysproto.h>
54 #include <sys/libkern.h>
56 #include <sys/limits.h>
58 #include <security/mac/mac_framework.h>
60 static char *_getenv_dynamic_locked(const char *name, int *idx);
61 static char *_getenv_dynamic(const char *name, int *idx);
63 static char *kenv_acquire(const char *name);
64 static void kenv_release(const char *buf);
66 static MALLOC_DEFINE(M_KENV, "kenv", "kernel environment");
68 #define KENV_SIZE 512 /* Maximum number of environment strings */
70 static uma_zone_t kenv_zone;
71 static int kenv_mvallen = KENV_MVALLEN;
73 /* pointer to the config-generated static environment */
76 /* pointer to the md-static environment */
78 static int md_env_len;
79 static int md_env_pos;
81 static char *kernenv_next(char *);
83 /* dynamic environment variables */
88 * No need to protect this with a mutex since SYSINITS are single threaded.
92 #define KENV_CHECK if (!dynamic_kenv) \
93 panic("%s: called before SI_SUB_KMEM", __func__)
105 char *name, *value, *buffer = NULL;
106 size_t len, done, needed, buflen;
109 KASSERT(dynamic_kenv, ("kenv: dynamic_kenv = false"));
112 if (uap->what == KENV_DUMP) {
114 error = mac_kenv_check_dump(td->td_ucred);
120 if (buflen > KENV_SIZE * (KENV_MNAMELEN + kenv_mvallen + 2))
121 buflen = KENV_SIZE * (KENV_MNAMELEN +
123 if (uap->len > 0 && uap->value != NULL)
124 buffer = malloc(buflen, M_TEMP, M_WAITOK|M_ZERO);
125 mtx_lock(&kenv_lock);
126 for (i = 0; kenvp[i] != NULL; i++) {
127 len = strlen(kenvp[i]) + 1;
129 len = min(len, buflen - done);
131 * If called with a NULL or insufficiently large
132 * buffer, just keep computing the required size.
134 if (uap->value != NULL && buffer != NULL && len > 0) {
135 bcopy(kenvp[i], buffer + done, len);
139 mtx_unlock(&kenv_lock);
140 if (buffer != NULL) {
141 error = copyout(buffer, uap->value, done);
142 free(buffer, M_TEMP);
144 td->td_retval[0] = ((done == needed) ? 0 : needed);
150 error = priv_check(td, PRIV_KENV_SET);
156 error = priv_check(td, PRIV_KENV_UNSET);
162 name = malloc(KENV_MNAMELEN + 1, M_TEMP, M_WAITOK);
164 error = copyinstr(uap->name, name, KENV_MNAMELEN + 1, NULL);
171 error = mac_kenv_check_get(td->td_ucred, name);
175 value = kern_getenv(name);
180 len = strlen(value) + 1;
183 error = copyout(value, uap->value, len);
187 td->td_retval[0] = len;
195 if (len > kenv_mvallen + 1)
196 len = kenv_mvallen + 1;
197 value = malloc(len, M_TEMP, M_WAITOK);
198 error = copyinstr(uap->value, value, len, NULL);
204 error = mac_kenv_check_set(td->td_ucred, name, value);
207 kern_setenv(name, value);
212 error = mac_kenv_check_unset(td->td_ucred, name);
216 error = kern_unsetenv(name);
230 * Populate the initial kernel environment.
232 * This is called very early in MD startup, either to provide a copy of the
233 * environment obtained from a boot loader, or to provide an empty buffer into
234 * which MD code can store an initial environment using kern_setenv() calls.
236 * kern_envp is set to the static_env generated by config(8). This implements
237 * the env keyword described in config(5).
239 * If len is non-zero, the caller is providing an empty buffer. The caller will
240 * subsequently use kern_setenv() to add up to len bytes of initial environment
241 * before the dynamic environment is available.
243 * If len is zero, the caller is providing a pre-loaded buffer containing
244 * environment strings. Additional strings cannot be added until the dynamic
245 * environment is available. The memory pointed to must remain stable at least
246 * until sysinit runs init_dynamic_kenv() and preferably until after SI_SUB_KMEM
247 * is finished so that subr_hints routines may continue to use it until the
248 * environments have been fully merged at the end of the pass. If no initial
249 * environment is available from the boot loader, passing a NULL pointer allows
250 * the static_env to be installed if it is configured. In this case, any call
251 * to kern_setenv() prior to the setup of the dynamic environment will result in
255 init_static_kenv(char *buf, size_t len)
258 KASSERT(!dynamic_kenv, ("kenv: dynamic_kenv already initialized"));
260 * Suitably sized means it must be able to hold at least one empty
261 * variable, otherwise things go belly up if a kern_getenv call is
262 * made without a prior call to kern_setenv as we have a malformed
265 KASSERT(len == 0 || len >= 2,
266 ("kenv: static env must be initialized or suitably sized"));
267 KASSERT(len == 0 || (*buf == '\0' && *(buf + 1) == '\0'),
268 ("kenv: sized buffer must be initially empty"));
271 * We may be called twice, with the second call needed to relocate
272 * md_envp after enabling paging. md_envp is then garbage if it is
273 * not null and the relocation will move it. Discard it so as to
274 * not crash using its old value in our first call to kern_getenv().
276 * The second call gives the same environment as the first except
277 * in silly configurations where the static env disables itself.
279 * Other env calls don't handle possibly-garbage pointers, so must
280 * not be made between enabling paging and calling here.
287 * Give the static environment a chance to disable the loader(8)
288 * environment first. This is done with loader_env.disabled=1.
290 * static_env and static_hints may both be disabled, but in slightly
291 * different ways. For static_env, we just don't setup kern_envp and
292 * it's as if a static env wasn't even provided. For static_hints,
293 * we effectively zero out the buffer to stop the rest of the kernel
294 * from being able to use it.
296 * We're intentionally setting this up so that static_hints.disabled may
297 * be specified in either the MD env or the static env. This keeps us
298 * consistent in our new world view.
300 * As a warning, the static environment may not be disabled in any way
301 * if the static environment has disabled the loader environment.
303 kern_envp = static_env;
304 if (!getenv_is_true("loader_env.disabled")) {
309 if (getenv_is_true("static_env.disabled")) {
314 if (getenv_is_true("static_hints.disabled")) {
315 static_hints[0] = '\0';
316 static_hints[1] = '\0';
321 init_dynamic_kenv_from(char *init_env, int *curpos)
323 char *cp, *cpnext, *eqpos, *found;
327 if (init_env && *init_env != '\0') {
330 for (cp = init_env; cp != NULL; cp = cpnext) {
331 cpnext = kernenv_next(cp);
332 len = strlen(cp) + 1;
333 if (len > KENV_MNAMELEN + 1 + kenv_mvallen + 1) {
335 "WARNING: too long kenv string, ignoring %s\n",
339 eqpos = strchr(cp, '=');
342 "WARNING: malformed static env value, ignoring %s\n",
348 * De-dupe the environment as we go. We don't add the
349 * duplicated assignments because config(8) will flip
350 * the order of the static environment around to make
351 * kernel processing match the order of specification
352 * in the kernel config.
354 found = _getenv_dynamic_locked(cp, NULL);
360 "WARNING: too many kenv strings, ignoring %s\n",
365 kenvp[i] = malloc(len, M_KENV, M_WAITOK);
366 strcpy(kenvp[i++], cp);
368 explicit_bzero(cp, len - 1);
375 * Setup the dynamic kernel environment.
378 init_dynamic_kenv(void *data __unused)
383 TUNABLE_INT_FETCH("kenv_mvallen", &kenv_mvallen);
384 size = KENV_MNAMELEN + 1 + kenv_mvallen + 1;
386 kenv_zone = uma_zcreate("kenv", size, NULL, NULL, NULL, NULL,
389 kenvp = malloc((KENV_SIZE + 1) * sizeof(char *), M_KENV,
393 init_dynamic_kenv_from(md_envp, &dynamic_envpos);
394 init_dynamic_kenv_from(kern_envp, &dynamic_envpos);
395 kenvp[dynamic_envpos] = NULL;
397 mtx_init(&kenv_lock, "kernel environment", NULL, MTX_DEF);
400 SYSINIT(kenv, SI_SUB_KMEM + 1, SI_ORDER_FIRST, init_dynamic_kenv, NULL);
406 if (dynamic_kenv && env != NULL) {
407 explicit_bzero(env, strlen(env));
408 uma_zfree(kenv_zone, env);
413 * Internal functions for string lookup.
416 _getenv_dynamic_locked(const char *name, int *idx)
422 for (cp = kenvp[0], i = 0; cp != NULL; cp = kenvp[++i]) {
423 if ((strncmp(cp, name, len) == 0) &&
427 return (cp + len + 1);
434 _getenv_dynamic(const char *name, int *idx)
437 mtx_assert(&kenv_lock, MA_OWNED);
438 return (_getenv_dynamic_locked(name, idx));
442 _getenv_static_from(char *chkenv, const char *name)
447 for (cp = chkenv; cp != NULL; cp = kernenv_next(cp)) {
448 for (ep = cp; (*ep != '=') && (*ep != 0); ep++)
454 if (!strncmp(name, cp, len) && name[len] == 0)
461 _getenv_static(const char *name)
465 val = _getenv_static_from(md_envp, name);
468 val = _getenv_static_from(kern_envp, name);
475 * Look up an environment variable by name.
476 * Return a pointer to the string if found.
477 * The pointer has to be freed with freeenv()
481 kern_getenv(const char *name)
487 len = KENV_MNAMELEN + 1 + kenv_mvallen + 1;
488 ret = uma_zalloc(kenv_zone, M_WAITOK | M_ZERO);
489 mtx_lock(&kenv_lock);
490 cp = _getenv_dynamic(name, NULL);
492 strlcpy(ret, cp, len);
493 mtx_unlock(&kenv_lock);
495 uma_zfree(kenv_zone, ret);
499 ret = _getenv_static(name);
505 * Test if an environment variable is defined.
508 testenv(const char *name)
512 cp = kenv_acquire(name);
521 * Set an environment variable in the MD-static environment. This cannot
522 * feasibly be done on config(8)-generated static environments as they don't
523 * generally include space for extra variables.
526 setenv_static(const char *name, const char *value)
530 if (md_env_pos >= md_env_len)
533 /* Check space for x=y and two nuls */
534 len = strlen(name) + strlen(value);
535 if (len + 3 < md_env_len - md_env_pos) {
536 len = sprintf(&md_envp[md_env_pos], "%s=%s", name, value);
538 md_envp[md_env_pos] = '\0';
546 * Set an environment variable by name.
549 kern_setenv(const char *name, const char *value)
551 char *buf, *cp, *oldenv;
552 int namelen, vallen, i;
554 if (!dynamic_kenv && md_env_len > 0)
555 return (setenv_static(name, value));
559 namelen = strlen(name) + 1;
560 if (namelen > KENV_MNAMELEN + 1)
562 vallen = strlen(value) + 1;
563 if (vallen > kenv_mvallen + 1)
565 buf = malloc(namelen + vallen, M_KENV, M_WAITOK);
566 sprintf(buf, "%s=%s", name, value);
568 mtx_lock(&kenv_lock);
569 cp = _getenv_dynamic(name, &i);
573 mtx_unlock(&kenv_lock);
574 free(oldenv, M_KENV);
576 /* We add the option if it wasn't found */
577 for (i = 0; (cp = kenvp[i]) != NULL; i++)
580 /* Bounds checking */
581 if (i < 0 || i >= KENV_SIZE) {
583 mtx_unlock(&kenv_lock);
589 mtx_unlock(&kenv_lock);
595 * Unset an environment variable string.
598 kern_unsetenv(const char *name)
605 mtx_lock(&kenv_lock);
606 cp = _getenv_dynamic(name, &i);
609 for (j = i + 1; kenvp[j] != NULL; j++)
610 kenvp[i++] = kenvp[j];
612 mtx_unlock(&kenv_lock);
613 zfree(oldenv, M_KENV);
616 mtx_unlock(&kenv_lock);
621 * Return the internal kenv buffer for the variable name, if it exists.
622 * If the dynamic kenv is initialized and the name is present, return
623 * with kenv_lock held.
626 kenv_acquire(const char *name)
631 mtx_lock(&kenv_lock);
632 value = _getenv_dynamic(name, NULL);
634 mtx_unlock(&kenv_lock);
637 return (_getenv_static(name));
641 * Undo a previous kenv_acquire() operation
644 kenv_release(const char *buf)
646 if ((buf != NULL) && dynamic_kenv)
647 mtx_unlock(&kenv_lock);
651 * Return a string value from an environment variable.
654 getenv_string(const char *name, char *data, int size)
658 cp = kenv_acquire(name);
661 strlcpy(data, cp, size);
669 * Return an array of integers at the given type size and signedness.
672 getenv_array(const char *name, void *pdata, int size, int *psize,
673 int type_size, bool allow_signed)
684 rc = 0; /* assume failure */
686 buf = kenv_acquire(name);
690 /* get maximum number of elements */
695 for (ptr = buf; *ptr != 0; ) {
696 value = strtoq(ptr, &end, 0);
698 /* check if signed numbers are allowed */
699 if (value < 0 && !allow_signed)
702 /* check for invalid value */
706 /* check for valid suffix */
735 /* garbage after numeric value */
739 /* skip till next value, if any */
740 while (*end == '\t' || *end == ',' || *end == ' ')
751 if ((value >> shift) != old)
754 /* check for buffer overflow */
758 /* store value according to type size */
762 if (value < SCHAR_MIN || value > SCHAR_MAX)
765 if (value < 0 || value > UCHAR_MAX)
768 ((uint8_t *)pdata)[n] = (uint8_t)value;
772 if (value < SHRT_MIN || value > SHRT_MAX)
775 if (value < 0 || value > USHRT_MAX)
778 ((uint16_t *)pdata)[n] = (uint16_t)value;
782 if (value < INT_MIN || value > INT_MAX)
785 if (value > UINT_MAX)
788 ((uint32_t *)pdata)[n] = (uint32_t)value;
791 ((uint64_t *)pdata)[n] = (uint64_t)value;
798 *psize = n * type_size;
801 rc = 1; /* success */
808 * Return an integer value from an environment variable.
811 getenv_int(const char *name, int *data)
816 rval = getenv_quad(name, &tmp);
823 * Return an unsigned integer value from an environment variable.
826 getenv_uint(const char *name, unsigned int *data)
831 rval = getenv_quad(name, &tmp);
833 *data = (unsigned int) tmp;
838 * Return an int64_t value from an environment variable.
841 getenv_int64(const char *name, int64_t *data)
846 rval = getenv_quad(name, &tmp);
848 *data = (int64_t) tmp;
853 * Return an uint64_t value from an environment variable.
856 getenv_uint64(const char *name, uint64_t *data)
861 rval = getenv_quad(name, &tmp);
863 *data = (uint64_t) tmp;
868 * Return a long value from an environment variable.
871 getenv_long(const char *name, long *data)
876 rval = getenv_quad(name, &tmp);
883 * Return an unsigned long value from an environment variable.
886 getenv_ulong(const char *name, unsigned long *data)
891 rval = getenv_quad(name, &tmp);
893 *data = (unsigned long) tmp;
898 * Return a quad_t value from an environment variable.
901 getenv_quad(const char *name, quad_t *data)
907 value = kenv_acquire(name);
911 iv = strtoq(value, &vtp, 0);
912 if (vtp == value || (vtp[0] != '\0' && vtp[1] != '\0')) {
942 * Return a boolean value from an environment variable. This can be in
943 * numerical or string form, i.e. "1" or "true".
946 getenv_bool(const char *name, bool *data)
954 val = kern_getenv(name);
958 if ((strcmp(val, "1") == 0) || (strcasecmp(val, "true") == 0)) {
961 } else if ((strcmp(val, "0") == 0) || (strcasecmp(val, "false") == 0)) {
965 /* Spit out a warning for malformed boolean variables. */
966 printf("Environment variable %s has non-boolean value \"%s\"\n",
975 * Wrapper around getenv_bool to easily check for true.
978 getenv_is_true(const char *name)
982 if (getenv_bool(name, &val) != 0)
988 * Wrapper around getenv_bool to easily check for false.
991 getenv_is_false(const char *name)
995 if (getenv_bool(name, &val) != 0)
1001 * Find the next entry after the one which (cp) falls within, return a
1002 * pointer to its start or NULL if there are no more.
1005 kernenv_next(char *cp)
1019 tunable_int_init(void *data)
1021 struct tunable_int *d = (struct tunable_int *)data;
1023 TUNABLE_INT_FETCH(d->path, d->var);
1027 tunable_long_init(void *data)
1029 struct tunable_long *d = (struct tunable_long *)data;
1031 TUNABLE_LONG_FETCH(d->path, d->var);
1035 tunable_ulong_init(void *data)
1037 struct tunable_ulong *d = (struct tunable_ulong *)data;
1039 TUNABLE_ULONG_FETCH(d->path, d->var);
1043 tunable_int64_init(void *data)
1045 struct tunable_int64 *d = (struct tunable_int64 *)data;
1047 TUNABLE_INT64_FETCH(d->path, d->var);
1051 tunable_uint64_init(void *data)
1053 struct tunable_uint64 *d = (struct tunable_uint64 *)data;
1055 TUNABLE_UINT64_FETCH(d->path, d->var);
1059 tunable_quad_init(void *data)
1061 struct tunable_quad *d = (struct tunable_quad *)data;
1063 TUNABLE_QUAD_FETCH(d->path, d->var);
1067 tunable_bool_init(void *data)
1069 struct tunable_bool *d = (struct tunable_bool *)data;
1071 TUNABLE_BOOL_FETCH(d->path, d->var);
1075 tunable_str_init(void *data)
1077 struct tunable_str *d = (struct tunable_str *)data;
1079 TUNABLE_STR_FETCH(d->path, d->var, d->size);