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/sysproto.h>
53 #include <sys/libkern.h>
55 #include <sys/limits.h>
57 #include <security/mac/mac_framework.h>
59 static char *_getenv_dynamic_locked(const char *name, int *idx);
60 static char *_getenv_dynamic(const char *name, int *idx);
62 static char *kenv_acquire(const char *name);
63 static void kenv_release(const char *buf);
65 static MALLOC_DEFINE(M_KENV, "kenv", "kernel environment");
67 #define KENV_SIZE 512 /* Maximum number of environment strings */
69 static uma_zone_t kenv_zone;
70 static int kenv_mvallen = KENV_MVALLEN;
72 /* pointer to the config-generated static environment */
75 /* pointer to the md-static environment */
77 static int md_env_len;
78 static int md_env_pos;
80 static char *kernenv_next(char *);
82 /* dynamic environment variables */
87 * No need to protect this with a mutex since SYSINITS are single threaded.
91 #define KENV_CHECK if (!dynamic_kenv) \
92 panic("%s: called before SI_SUB_KMEM", __func__)
95 kenv_dump(struct thread *td, char **envp, int what, char *value, int len)
98 size_t done, needed, buflen;
105 MPASS(what == KENV_DUMP || what == KENV_DUMP_LOADER ||
106 what == KENV_DUMP_STATIC);
109 * For non-dynamic kernel environment, we pass in either md_envp or
110 * kern_envp and we must traverse with kernenv_next(). This shuffling
111 * of pointers simplifies the below loop by only differing in how envp
114 if (what != KENV_DUMP) {
120 if (buflen > KENV_SIZE * (KENV_MNAMELEN + kenv_mvallen + 2))
121 buflen = KENV_SIZE * (KENV_MNAMELEN +
123 if (len > 0 && value != NULL)
124 buffer = malloc(buflen, M_TEMP, M_WAITOK|M_ZERO);
126 /* Only take the lock for the dynamic kenv. */
127 if (what == KENV_DUMP)
128 mtx_lock(&kenv_lock);
129 while (*envp != NULL) {
130 len = strlen(*envp) + 1;
132 len = min(len, buflen - done);
134 * If called with a NULL or insufficiently large
135 * buffer, just keep computing the required size.
137 if (value != NULL && buffer != NULL && len > 0) {
138 bcopy(*envp, buffer + done, len);
142 /* Advance the pointer depending on the kenv format. */
143 if (what == KENV_DUMP)
146 senv = kernenv_next(senv);
148 if (what == KENV_DUMP)
149 mtx_unlock(&kenv_lock);
150 if (buffer != NULL) {
151 error = copyout(buffer, value, done);
152 free(buffer, M_TEMP);
154 td->td_retval[0] = ((done == needed) ? 0 : needed);
159 sys_kenv(struct thread *td, struct kenv_args *uap)
165 KASSERT(dynamic_kenv, ("kenv: dynamic_kenv = false"));
172 error = mac_kenv_check_dump(td->td_ucred);
176 return (kenv_dump(td, kenvp, uap->what, uap->value, uap->len));
177 case KENV_DUMP_LOADER:
178 case KENV_DUMP_STATIC:
180 error = mac_kenv_check_dump(td->td_ucred);
184 #ifdef PRESERVE_EARLY_KENV
185 return (kenv_dump(td,
186 uap->what == KENV_DUMP_LOADER ? (char **)md_envp :
187 (char **)kern_envp, uap->what, uap->value, uap->len));
192 error = priv_check(td, PRIV_KENV_SET);
198 error = priv_check(td, PRIV_KENV_UNSET);
204 name = malloc(KENV_MNAMELEN + 1, M_TEMP, M_WAITOK);
206 error = copyinstr(uap->name, name, KENV_MNAMELEN + 1, NULL);
213 error = mac_kenv_check_get(td->td_ucred, name);
217 value = kern_getenv(name);
222 len = strlen(value) + 1;
225 error = copyout(value, uap->value, len);
229 td->td_retval[0] = len;
237 if (len > kenv_mvallen + 1)
238 len = kenv_mvallen + 1;
239 value = malloc(len, M_TEMP, M_WAITOK);
240 error = copyinstr(uap->value, value, len, NULL);
246 error = mac_kenv_check_set(td->td_ucred, name, value);
249 kern_setenv(name, value);
254 error = mac_kenv_check_unset(td->td_ucred, name);
258 error = kern_unsetenv(name);
272 * Populate the initial kernel environment.
274 * This is called very early in MD startup, either to provide a copy of the
275 * environment obtained from a boot loader, or to provide an empty buffer into
276 * which MD code can store an initial environment using kern_setenv() calls.
278 * kern_envp is set to the static_env generated by config(8). This implements
279 * the env keyword described in config(5).
281 * If len is non-zero, the caller is providing an empty buffer. The caller will
282 * subsequently use kern_setenv() to add up to len bytes of initial environment
283 * before the dynamic environment is available.
285 * If len is zero, the caller is providing a pre-loaded buffer containing
286 * environment strings. Additional strings cannot be added until the dynamic
287 * environment is available. The memory pointed to must remain stable at least
288 * until sysinit runs init_dynamic_kenv() and preferably until after SI_SUB_KMEM
289 * is finished so that subr_hints routines may continue to use it until the
290 * environments have been fully merged at the end of the pass. If no initial
291 * environment is available from the boot loader, passing a NULL pointer allows
292 * the static_env to be installed if it is configured. In this case, any call
293 * to kern_setenv() prior to the setup of the dynamic environment will result in
297 init_static_kenv(char *buf, size_t len)
300 KASSERT(!dynamic_kenv, ("kenv: dynamic_kenv already initialized"));
302 * Suitably sized means it must be able to hold at least one empty
303 * variable, otherwise things go belly up if a kern_getenv call is
304 * made without a prior call to kern_setenv as we have a malformed
307 KASSERT(len == 0 || len >= 2,
308 ("kenv: static env must be initialized or suitably sized"));
309 KASSERT(len == 0 || (*buf == '\0' && *(buf + 1) == '\0'),
310 ("kenv: sized buffer must be initially empty"));
313 * We may be called twice, with the second call needed to relocate
314 * md_envp after enabling paging. md_envp is then garbage if it is
315 * not null and the relocation will move it. Discard it so as to
316 * not crash using its old value in our first call to kern_getenv().
318 * The second call gives the same environment as the first except
319 * in silly configurations where the static env disables itself.
321 * Other env calls don't handle possibly-garbage pointers, so must
322 * not be made between enabling paging and calling here.
329 * Give the static environment a chance to disable the loader(8)
330 * environment first. This is done with loader_env.disabled=1.
332 * static_env and static_hints may both be disabled, but in slightly
333 * different ways. For static_env, we just don't setup kern_envp and
334 * it's as if a static env wasn't even provided. For static_hints,
335 * we effectively zero out the buffer to stop the rest of the kernel
336 * from being able to use it.
338 * We're intentionally setting this up so that static_hints.disabled may
339 * be specified in either the MD env or the static env. This keeps us
340 * consistent in our new world view.
342 * As a warning, the static environment may not be disabled in any way
343 * if the static environment has disabled the loader environment.
345 kern_envp = static_env;
346 if (!getenv_is_true("loader_env.disabled")) {
351 if (getenv_is_true("static_env.disabled")) {
356 if (getenv_is_true("static_hints.disabled")) {
357 static_hints[0] = '\0';
358 static_hints[1] = '\0';
363 init_dynamic_kenv_from(char *init_env, int *curpos)
365 char *cp, *cpnext, *eqpos, *found;
369 if (init_env && *init_env != '\0') {
372 for (cp = init_env; cp != NULL; cp = cpnext) {
373 cpnext = kernenv_next(cp);
374 len = strlen(cp) + 1;
375 if (len > KENV_MNAMELEN + 1 + kenv_mvallen + 1) {
377 "WARNING: too long kenv string, ignoring %s\n",
381 eqpos = strchr(cp, '=');
384 "WARNING: malformed static env value, ignoring %s\n",
390 * De-dupe the environment as we go. We don't add the
391 * duplicated assignments because config(8) will flip
392 * the order of the static environment around to make
393 * kernel processing match the order of specification
394 * in the kernel config.
396 found = _getenv_dynamic_locked(cp, NULL);
402 "WARNING: too many kenv strings, ignoring %s\n",
407 kenvp[i] = malloc(len, M_KENV, M_WAITOK);
408 strcpy(kenvp[i++], cp);
410 #ifdef PRESERVE_EARLY_KENV
413 explicit_bzero(cp, len - 1);
421 * Setup the dynamic kernel environment.
424 init_dynamic_kenv(void *data __unused)
429 TUNABLE_INT_FETCH("kenv_mvallen", &kenv_mvallen);
430 size = KENV_MNAMELEN + 1 + kenv_mvallen + 1;
432 kenv_zone = uma_zcreate("kenv", size, NULL, NULL, NULL, NULL,
435 kenvp = malloc((KENV_SIZE + 1) * sizeof(char *), M_KENV,
439 init_dynamic_kenv_from(md_envp, &dynamic_envpos);
440 init_dynamic_kenv_from(kern_envp, &dynamic_envpos);
441 kenvp[dynamic_envpos] = NULL;
443 mtx_init(&kenv_lock, "kernel environment", NULL, MTX_DEF);
446 SYSINIT(kenv, SI_SUB_KMEM + 1, SI_ORDER_FIRST, init_dynamic_kenv, NULL);
452 if (dynamic_kenv && env != NULL) {
453 explicit_bzero(env, strlen(env));
454 uma_zfree(kenv_zone, env);
459 * Internal functions for string lookup.
462 _getenv_dynamic_locked(const char *name, int *idx)
468 for (cp = kenvp[0], i = 0; cp != NULL; cp = kenvp[++i]) {
469 if ((strncmp(cp, name, len) == 0) &&
473 return (cp + len + 1);
480 _getenv_dynamic(const char *name, int *idx)
483 mtx_assert(&kenv_lock, MA_OWNED);
484 return (_getenv_dynamic_locked(name, idx));
488 _getenv_static_from(char *chkenv, const char *name)
493 for (cp = chkenv; cp != NULL; cp = kernenv_next(cp)) {
494 for (ep = cp; (*ep != '=') && (*ep != 0); ep++)
500 if (!strncmp(name, cp, len) && name[len] == 0)
507 _getenv_static(const char *name)
511 val = _getenv_static_from(md_envp, name);
514 val = _getenv_static_from(kern_envp, name);
521 * Look up an environment variable by name.
522 * Return a pointer to the string if found.
523 * The pointer has to be freed with freeenv()
527 kern_getenv(const char *name)
533 len = KENV_MNAMELEN + 1 + kenv_mvallen + 1;
534 ret = uma_zalloc(kenv_zone, M_WAITOK | M_ZERO);
535 mtx_lock(&kenv_lock);
536 cp = _getenv_dynamic(name, NULL);
538 strlcpy(ret, cp, len);
539 mtx_unlock(&kenv_lock);
541 uma_zfree(kenv_zone, ret);
545 ret = _getenv_static(name);
551 * Test if an environment variable is defined.
554 testenv(const char *name)
558 cp = kenv_acquire(name);
567 * Set an environment variable in the MD-static environment. This cannot
568 * feasibly be done on config(8)-generated static environments as they don't
569 * generally include space for extra variables.
572 setenv_static(const char *name, const char *value)
576 if (md_env_pos >= md_env_len)
579 /* Check space for x=y and two nuls */
580 len = strlen(name) + strlen(value);
581 if (len + 3 < md_env_len - md_env_pos) {
582 len = sprintf(&md_envp[md_env_pos], "%s=%s", name, value);
584 md_envp[md_env_pos] = '\0';
592 * Set an environment variable by name.
595 kern_setenv(const char *name, const char *value)
597 char *buf, *cp, *oldenv;
598 int namelen, vallen, i;
600 if (!dynamic_kenv && md_env_len > 0)
601 return (setenv_static(name, value));
605 namelen = strlen(name) + 1;
606 if (namelen > KENV_MNAMELEN + 1)
608 vallen = strlen(value) + 1;
609 if (vallen > kenv_mvallen + 1)
611 buf = malloc(namelen + vallen, M_KENV, M_WAITOK);
612 sprintf(buf, "%s=%s", name, value);
614 mtx_lock(&kenv_lock);
615 cp = _getenv_dynamic(name, &i);
619 mtx_unlock(&kenv_lock);
620 free(oldenv, M_KENV);
622 /* We add the option if it wasn't found */
623 for (i = 0; (cp = kenvp[i]) != NULL; i++)
626 /* Bounds checking */
627 if (i < 0 || i >= KENV_SIZE) {
629 mtx_unlock(&kenv_lock);
635 mtx_unlock(&kenv_lock);
641 * Unset an environment variable string.
644 kern_unsetenv(const char *name)
651 mtx_lock(&kenv_lock);
652 cp = _getenv_dynamic(name, &i);
655 for (j = i + 1; kenvp[j] != NULL; j++)
656 kenvp[i++] = kenvp[j];
658 mtx_unlock(&kenv_lock);
659 zfree(oldenv, M_KENV);
662 mtx_unlock(&kenv_lock);
667 * Return the internal kenv buffer for the variable name, if it exists.
668 * If the dynamic kenv is initialized and the name is present, return
669 * with kenv_lock held.
672 kenv_acquire(const char *name)
677 mtx_lock(&kenv_lock);
678 value = _getenv_dynamic(name, NULL);
680 mtx_unlock(&kenv_lock);
683 return (_getenv_static(name));
687 * Undo a previous kenv_acquire() operation
690 kenv_release(const char *buf)
692 if ((buf != NULL) && dynamic_kenv)
693 mtx_unlock(&kenv_lock);
697 * Return a string value from an environment variable.
700 getenv_string(const char *name, char *data, int size)
704 cp = kenv_acquire(name);
707 strlcpy(data, cp, size);
715 * Return an array of integers at the given type size and signedness.
718 getenv_array(const char *name, void *pdata, int size, int *psize,
719 int type_size, bool allow_signed)
730 rc = 0; /* assume failure */
732 buf = kenv_acquire(name);
736 /* get maximum number of elements */
741 for (ptr = buf; *ptr != 0; ) {
742 value = strtoq(ptr, &end, 0);
744 /* check if signed numbers are allowed */
745 if (value < 0 && !allow_signed)
748 /* check for invalid value */
752 /* check for valid suffix */
781 /* garbage after numeric value */
785 /* skip till next value, if any */
786 while (*end == '\t' || *end == ',' || *end == ' ')
797 if ((value >> shift) != old)
800 /* check for buffer overflow */
804 /* store value according to type size */
808 if (value < SCHAR_MIN || value > SCHAR_MAX)
811 if (value < 0 || value > UCHAR_MAX)
814 ((uint8_t *)pdata)[n] = (uint8_t)value;
818 if (value < SHRT_MIN || value > SHRT_MAX)
821 if (value < 0 || value > USHRT_MAX)
824 ((uint16_t *)pdata)[n] = (uint16_t)value;
828 if (value < INT_MIN || value > INT_MAX)
831 if (value > UINT_MAX)
834 ((uint32_t *)pdata)[n] = (uint32_t)value;
837 ((uint64_t *)pdata)[n] = (uint64_t)value;
844 *psize = n * type_size;
847 rc = 1; /* success */
854 * Return an integer value from an environment variable.
857 getenv_int(const char *name, int *data)
862 rval = getenv_quad(name, &tmp);
869 * Return an unsigned integer value from an environment variable.
872 getenv_uint(const char *name, unsigned int *data)
877 rval = getenv_quad(name, &tmp);
879 *data = (unsigned int) tmp;
884 * Return an int64_t value from an environment variable.
887 getenv_int64(const char *name, int64_t *data)
892 rval = getenv_quad(name, &tmp);
894 *data = (int64_t) tmp;
899 * Return an uint64_t value from an environment variable.
902 getenv_uint64(const char *name, uint64_t *data)
907 rval = getenv_quad(name, &tmp);
909 *data = (uint64_t) tmp;
914 * Return a long value from an environment variable.
917 getenv_long(const char *name, long *data)
922 rval = getenv_quad(name, &tmp);
929 * Return an unsigned long value from an environment variable.
932 getenv_ulong(const char *name, unsigned long *data)
937 rval = getenv_quad(name, &tmp);
939 *data = (unsigned long) tmp;
944 * Return a quad_t value from an environment variable.
947 getenv_quad(const char *name, quad_t *data)
953 value = kenv_acquire(name);
957 iv = strtoq(value, &vtp, 0);
958 if (vtp == value || (vtp[0] != '\0' && vtp[1] != '\0')) {
988 * Return a boolean value from an environment variable. This can be in
989 * numerical or string form, i.e. "1" or "true".
992 getenv_bool(const char *name, bool *data)
1000 val = kern_getenv(name);
1004 if ((strcmp(val, "1") == 0) || (strcasecmp(val, "true") == 0)) {
1007 } else if ((strcmp(val, "0") == 0) || (strcasecmp(val, "false") == 0)) {
1011 /* Spit out a warning for malformed boolean variables. */
1012 printf("Environment variable %s has non-boolean value \"%s\"\n",
1021 * Wrapper around getenv_bool to easily check for true.
1024 getenv_is_true(const char *name)
1028 if (getenv_bool(name, &val) != 0)
1034 * Wrapper around getenv_bool to easily check for false.
1037 getenv_is_false(const char *name)
1041 if (getenv_bool(name, &val) != 0)
1047 * Find the next entry after the one which (cp) falls within, return a
1048 * pointer to its start or NULL if there are no more.
1051 kernenv_next(char *cp)
1065 tunable_int_init(void *data)
1067 struct tunable_int *d = (struct tunable_int *)data;
1069 TUNABLE_INT_FETCH(d->path, d->var);
1073 tunable_long_init(void *data)
1075 struct tunable_long *d = (struct tunable_long *)data;
1077 TUNABLE_LONG_FETCH(d->path, d->var);
1081 tunable_ulong_init(void *data)
1083 struct tunable_ulong *d = (struct tunable_ulong *)data;
1085 TUNABLE_ULONG_FETCH(d->path, d->var);
1089 tunable_int64_init(void *data)
1091 struct tunable_int64 *d = (struct tunable_int64 *)data;
1093 TUNABLE_INT64_FETCH(d->path, d->var);
1097 tunable_uint64_init(void *data)
1099 struct tunable_uint64 *d = (struct tunable_uint64 *)data;
1101 TUNABLE_UINT64_FETCH(d->path, d->var);
1105 tunable_quad_init(void *data)
1107 struct tunable_quad *d = (struct tunable_quad *)data;
1109 TUNABLE_QUAD_FETCH(d->path, d->var);
1113 tunable_bool_init(void *data)
1115 struct tunable_bool *d = (struct tunable_bool *)data;
1117 TUNABLE_BOOL_FETCH(d->path, d->var);
1121 tunable_str_init(void *data)
1123 struct tunable_str *d = (struct tunable_str *)data;
1125 TUNABLE_STR_FETCH(d->path, d->var, d->size);