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__)
96 kenv_dump(struct thread *td, char **envp, int what, char *value, int len)
99 size_t done, needed, buflen;
106 MPASS(what == KENV_DUMP || what == KENV_DUMP_LOADER ||
107 what == KENV_DUMP_STATIC);
110 * For non-dynamic kernel environment, we pass in either md_envp or
111 * kern_envp and we must traverse with kernenv_next(). This shuffling
112 * of pointers simplifies the below loop by only differing in how envp
115 if (what != KENV_DUMP) {
121 if (buflen > KENV_SIZE * (KENV_MNAMELEN + kenv_mvallen + 2))
122 buflen = KENV_SIZE * (KENV_MNAMELEN +
124 if (len > 0 && value != NULL)
125 buffer = malloc(buflen, M_TEMP, M_WAITOK|M_ZERO);
127 /* Only take the lock for the dynamic kenv. */
128 if (what == KENV_DUMP)
129 mtx_lock(&kenv_lock);
130 while (*envp != NULL) {
131 len = strlen(*envp) + 1;
133 len = min(len, buflen - done);
135 * If called with a NULL or insufficiently large
136 * buffer, just keep computing the required size.
138 if (value != NULL && buffer != NULL && len > 0) {
139 bcopy(*envp, buffer + done, len);
143 /* Advance the pointer depending on the kenv format. */
144 if (what == KENV_DUMP)
147 senv = kernenv_next(senv);
149 if (what == KENV_DUMP)
150 mtx_unlock(&kenv_lock);
151 if (buffer != NULL) {
152 error = copyout(buffer, value, done);
153 free(buffer, M_TEMP);
155 td->td_retval[0] = ((done == needed) ? 0 : needed);
160 sys_kenv(struct thread *td, struct kenv_args *uap)
166 KASSERT(dynamic_kenv, ("kenv: dynamic_kenv = false"));
173 error = mac_kenv_check_dump(td->td_ucred);
177 return (kenv_dump(td, kenvp, uap->what, uap->value, uap->len));
178 case KENV_DUMP_LOADER:
179 case KENV_DUMP_STATIC:
181 error = mac_kenv_check_dump(td->td_ucred);
185 #ifdef PRESERVE_EARLY_KENV
186 return (kenv_dump(td,
187 uap->what == KENV_DUMP_LOADER ? (char **)md_envp :
188 (char **)kern_envp, uap->what, uap->value, uap->len));
193 error = priv_check(td, PRIV_KENV_SET);
199 error = priv_check(td, PRIV_KENV_UNSET);
205 name = malloc(KENV_MNAMELEN + 1, M_TEMP, M_WAITOK);
207 error = copyinstr(uap->name, name, KENV_MNAMELEN + 1, NULL);
214 error = mac_kenv_check_get(td->td_ucred, name);
218 value = kern_getenv(name);
223 len = strlen(value) + 1;
226 error = copyout(value, uap->value, len);
230 td->td_retval[0] = len;
238 if (len > kenv_mvallen + 1)
239 len = kenv_mvallen + 1;
240 value = malloc(len, M_TEMP, M_WAITOK);
241 error = copyinstr(uap->value, value, len, NULL);
247 error = mac_kenv_check_set(td->td_ucred, name, value);
250 kern_setenv(name, value);
255 error = mac_kenv_check_unset(td->td_ucred, name);
259 error = kern_unsetenv(name);
273 * Populate the initial kernel environment.
275 * This is called very early in MD startup, either to provide a copy of the
276 * environment obtained from a boot loader, or to provide an empty buffer into
277 * which MD code can store an initial environment using kern_setenv() calls.
279 * kern_envp is set to the static_env generated by config(8). This implements
280 * the env keyword described in config(5).
282 * If len is non-zero, the caller is providing an empty buffer. The caller will
283 * subsequently use kern_setenv() to add up to len bytes of initial environment
284 * before the dynamic environment is available.
286 * If len is zero, the caller is providing a pre-loaded buffer containing
287 * environment strings. Additional strings cannot be added until the dynamic
288 * environment is available. The memory pointed to must remain stable at least
289 * until sysinit runs init_dynamic_kenv() and preferably until after SI_SUB_KMEM
290 * is finished so that subr_hints routines may continue to use it until the
291 * environments have been fully merged at the end of the pass. If no initial
292 * environment is available from the boot loader, passing a NULL pointer allows
293 * the static_env to be installed if it is configured. In this case, any call
294 * to kern_setenv() prior to the setup of the dynamic environment will result in
298 init_static_kenv(char *buf, size_t len)
301 KASSERT(!dynamic_kenv, ("kenv: dynamic_kenv already initialized"));
303 * Suitably sized means it must be able to hold at least one empty
304 * variable, otherwise things go belly up if a kern_getenv call is
305 * made without a prior call to kern_setenv as we have a malformed
308 KASSERT(len == 0 || len >= 2,
309 ("kenv: static env must be initialized or suitably sized"));
310 KASSERT(len == 0 || (*buf == '\0' && *(buf + 1) == '\0'),
311 ("kenv: sized buffer must be initially empty"));
314 * We may be called twice, with the second call needed to relocate
315 * md_envp after enabling paging. md_envp is then garbage if it is
316 * not null and the relocation will move it. Discard it so as to
317 * not crash using its old value in our first call to kern_getenv().
319 * The second call gives the same environment as the first except
320 * in silly configurations where the static env disables itself.
322 * Other env calls don't handle possibly-garbage pointers, so must
323 * not be made between enabling paging and calling here.
330 * Give the static environment a chance to disable the loader(8)
331 * environment first. This is done with loader_env.disabled=1.
333 * static_env and static_hints may both be disabled, but in slightly
334 * different ways. For static_env, we just don't setup kern_envp and
335 * it's as if a static env wasn't even provided. For static_hints,
336 * we effectively zero out the buffer to stop the rest of the kernel
337 * from being able to use it.
339 * We're intentionally setting this up so that static_hints.disabled may
340 * be specified in either the MD env or the static env. This keeps us
341 * consistent in our new world view.
343 * As a warning, the static environment may not be disabled in any way
344 * if the static environment has disabled the loader environment.
346 kern_envp = static_env;
347 if (!getenv_is_true("loader_env.disabled")) {
352 if (getenv_is_true("static_env.disabled")) {
357 if (getenv_is_true("static_hints.disabled")) {
358 static_hints[0] = '\0';
359 static_hints[1] = '\0';
364 init_dynamic_kenv_from(char *init_env, int *curpos)
366 char *cp, *cpnext, *eqpos, *found;
370 if (init_env && *init_env != '\0') {
373 for (cp = init_env; cp != NULL; cp = cpnext) {
374 cpnext = kernenv_next(cp);
375 len = strlen(cp) + 1;
376 if (len > KENV_MNAMELEN + 1 + kenv_mvallen + 1) {
378 "WARNING: too long kenv string, ignoring %s\n",
382 eqpos = strchr(cp, '=');
385 "WARNING: malformed static env value, ignoring %s\n",
391 * De-dupe the environment as we go. We don't add the
392 * duplicated assignments because config(8) will flip
393 * the order of the static environment around to make
394 * kernel processing match the order of specification
395 * in the kernel config.
397 found = _getenv_dynamic_locked(cp, NULL);
403 "WARNING: too many kenv strings, ignoring %s\n",
408 kenvp[i] = malloc(len, M_KENV, M_WAITOK);
409 strcpy(kenvp[i++], cp);
411 #ifdef PRESERVE_EARLY_KENV
414 explicit_bzero(cp, len - 1);
422 * Setup the dynamic kernel environment.
425 init_dynamic_kenv(void *data __unused)
430 TUNABLE_INT_FETCH("kenv_mvallen", &kenv_mvallen);
431 size = KENV_MNAMELEN + 1 + kenv_mvallen + 1;
433 kenv_zone = uma_zcreate("kenv", size, NULL, NULL, NULL, NULL,
436 kenvp = malloc((KENV_SIZE + 1) * sizeof(char *), M_KENV,
440 init_dynamic_kenv_from(md_envp, &dynamic_envpos);
441 init_dynamic_kenv_from(kern_envp, &dynamic_envpos);
442 kenvp[dynamic_envpos] = NULL;
444 mtx_init(&kenv_lock, "kernel environment", NULL, MTX_DEF);
447 SYSINIT(kenv, SI_SUB_KMEM + 1, SI_ORDER_FIRST, init_dynamic_kenv, NULL);
453 if (dynamic_kenv && env != NULL) {
454 explicit_bzero(env, strlen(env));
455 uma_zfree(kenv_zone, env);
460 * Internal functions for string lookup.
463 _getenv_dynamic_locked(const char *name, int *idx)
469 for (cp = kenvp[0], i = 0; cp != NULL; cp = kenvp[++i]) {
470 if ((strncmp(cp, name, len) == 0) &&
474 return (cp + len + 1);
481 _getenv_dynamic(const char *name, int *idx)
484 mtx_assert(&kenv_lock, MA_OWNED);
485 return (_getenv_dynamic_locked(name, idx));
489 _getenv_static_from(char *chkenv, const char *name)
494 for (cp = chkenv; cp != NULL; cp = kernenv_next(cp)) {
495 for (ep = cp; (*ep != '=') && (*ep != 0); ep++)
501 if (!strncmp(name, cp, len) && name[len] == 0)
508 _getenv_static(const char *name)
512 val = _getenv_static_from(md_envp, name);
515 val = _getenv_static_from(kern_envp, name);
522 * Look up an environment variable by name.
523 * Return a pointer to the string if found.
524 * The pointer has to be freed with freeenv()
528 kern_getenv(const char *name)
534 len = KENV_MNAMELEN + 1 + kenv_mvallen + 1;
535 ret = uma_zalloc(kenv_zone, M_WAITOK | M_ZERO);
536 mtx_lock(&kenv_lock);
537 cp = _getenv_dynamic(name, NULL);
539 strlcpy(ret, cp, len);
540 mtx_unlock(&kenv_lock);
542 uma_zfree(kenv_zone, ret);
546 ret = _getenv_static(name);
552 * Test if an environment variable is defined.
555 testenv(const char *name)
559 cp = kenv_acquire(name);
568 * Set an environment variable in the MD-static environment. This cannot
569 * feasibly be done on config(8)-generated static environments as they don't
570 * generally include space for extra variables.
573 setenv_static(const char *name, const char *value)
577 if (md_env_pos >= md_env_len)
580 /* Check space for x=y and two nuls */
581 len = strlen(name) + strlen(value);
582 if (len + 3 < md_env_len - md_env_pos) {
583 len = sprintf(&md_envp[md_env_pos], "%s=%s", name, value);
585 md_envp[md_env_pos] = '\0';
593 * Set an environment variable by name.
596 kern_setenv(const char *name, const char *value)
598 char *buf, *cp, *oldenv;
599 int namelen, vallen, i;
601 if (!dynamic_kenv && md_env_len > 0)
602 return (setenv_static(name, value));
606 namelen = strlen(name) + 1;
607 if (namelen > KENV_MNAMELEN + 1)
609 vallen = strlen(value) + 1;
610 if (vallen > kenv_mvallen + 1)
612 buf = malloc(namelen + vallen, M_KENV, M_WAITOK);
613 sprintf(buf, "%s=%s", name, value);
615 mtx_lock(&kenv_lock);
616 cp = _getenv_dynamic(name, &i);
620 mtx_unlock(&kenv_lock);
621 free(oldenv, M_KENV);
623 /* We add the option if it wasn't found */
624 for (i = 0; (cp = kenvp[i]) != NULL; i++)
627 /* Bounds checking */
628 if (i < 0 || i >= KENV_SIZE) {
630 mtx_unlock(&kenv_lock);
636 mtx_unlock(&kenv_lock);
642 * Unset an environment variable string.
645 kern_unsetenv(const char *name)
652 mtx_lock(&kenv_lock);
653 cp = _getenv_dynamic(name, &i);
656 for (j = i + 1; kenvp[j] != NULL; j++)
657 kenvp[i++] = kenvp[j];
659 mtx_unlock(&kenv_lock);
660 zfree(oldenv, M_KENV);
663 mtx_unlock(&kenv_lock);
668 * Return the internal kenv buffer for the variable name, if it exists.
669 * If the dynamic kenv is initialized and the name is present, return
670 * with kenv_lock held.
673 kenv_acquire(const char *name)
678 mtx_lock(&kenv_lock);
679 value = _getenv_dynamic(name, NULL);
681 mtx_unlock(&kenv_lock);
684 return (_getenv_static(name));
688 * Undo a previous kenv_acquire() operation
691 kenv_release(const char *buf)
693 if ((buf != NULL) && dynamic_kenv)
694 mtx_unlock(&kenv_lock);
698 * Return a string value from an environment variable.
701 getenv_string(const char *name, char *data, int size)
705 cp = kenv_acquire(name);
708 strlcpy(data, cp, size);
716 * Return an array of integers at the given type size and signedness.
719 getenv_array(const char *name, void *pdata, int size, int *psize,
720 int type_size, bool allow_signed)
731 rc = 0; /* assume failure */
733 buf = kenv_acquire(name);
737 /* get maximum number of elements */
742 for (ptr = buf; *ptr != 0; ) {
743 value = strtoq(ptr, &end, 0);
745 /* check if signed numbers are allowed */
746 if (value < 0 && !allow_signed)
749 /* check for invalid value */
753 /* check for valid suffix */
782 /* garbage after numeric value */
786 /* skip till next value, if any */
787 while (*end == '\t' || *end == ',' || *end == ' ')
798 if ((value >> shift) != old)
801 /* check for buffer overflow */
805 /* store value according to type size */
809 if (value < SCHAR_MIN || value > SCHAR_MAX)
812 if (value < 0 || value > UCHAR_MAX)
815 ((uint8_t *)pdata)[n] = (uint8_t)value;
819 if (value < SHRT_MIN || value > SHRT_MAX)
822 if (value < 0 || value > USHRT_MAX)
825 ((uint16_t *)pdata)[n] = (uint16_t)value;
829 if (value < INT_MIN || value > INT_MAX)
832 if (value > UINT_MAX)
835 ((uint32_t *)pdata)[n] = (uint32_t)value;
838 ((uint64_t *)pdata)[n] = (uint64_t)value;
845 *psize = n * type_size;
848 rc = 1; /* success */
855 * Return an integer value from an environment variable.
858 getenv_int(const char *name, int *data)
863 rval = getenv_quad(name, &tmp);
870 * Return an unsigned integer value from an environment variable.
873 getenv_uint(const char *name, unsigned int *data)
878 rval = getenv_quad(name, &tmp);
880 *data = (unsigned int) tmp;
885 * Return an int64_t value from an environment variable.
888 getenv_int64(const char *name, int64_t *data)
893 rval = getenv_quad(name, &tmp);
895 *data = (int64_t) tmp;
900 * Return an uint64_t value from an environment variable.
903 getenv_uint64(const char *name, uint64_t *data)
908 rval = getenv_quad(name, &tmp);
910 *data = (uint64_t) tmp;
915 * Return a long value from an environment variable.
918 getenv_long(const char *name, long *data)
923 rval = getenv_quad(name, &tmp);
930 * Return an unsigned long value from an environment variable.
933 getenv_ulong(const char *name, unsigned long *data)
938 rval = getenv_quad(name, &tmp);
940 *data = (unsigned long) tmp;
945 * Return a quad_t value from an environment variable.
948 getenv_quad(const char *name, quad_t *data)
954 value = kenv_acquire(name);
958 iv = strtoq(value, &vtp, 0);
959 if (vtp == value || (vtp[0] != '\0' && vtp[1] != '\0')) {
989 * Return a boolean value from an environment variable. This can be in
990 * numerical or string form, i.e. "1" or "true".
993 getenv_bool(const char *name, bool *data)
1001 val = kern_getenv(name);
1005 if ((strcmp(val, "1") == 0) || (strcasecmp(val, "true") == 0)) {
1008 } else if ((strcmp(val, "0") == 0) || (strcasecmp(val, "false") == 0)) {
1012 /* Spit out a warning for malformed boolean variables. */
1013 printf("Environment variable %s has non-boolean value \"%s\"\n",
1022 * Wrapper around getenv_bool to easily check for true.
1025 getenv_is_true(const char *name)
1029 if (getenv_bool(name, &val) != 0)
1035 * Wrapper around getenv_bool to easily check for false.
1038 getenv_is_false(const char *name)
1042 if (getenv_bool(name, &val) != 0)
1048 * Find the next entry after the one which (cp) falls within, return a
1049 * pointer to its start or NULL if there are no more.
1052 kernenv_next(char *cp)
1066 tunable_int_init(void *data)
1068 struct tunable_int *d = (struct tunable_int *)data;
1070 TUNABLE_INT_FETCH(d->path, d->var);
1074 tunable_long_init(void *data)
1076 struct tunable_long *d = (struct tunable_long *)data;
1078 TUNABLE_LONG_FETCH(d->path, d->var);
1082 tunable_ulong_init(void *data)
1084 struct tunable_ulong *d = (struct tunable_ulong *)data;
1086 TUNABLE_ULONG_FETCH(d->path, d->var);
1090 tunable_int64_init(void *data)
1092 struct tunable_int64 *d = (struct tunable_int64 *)data;
1094 TUNABLE_INT64_FETCH(d->path, d->var);
1098 tunable_uint64_init(void *data)
1100 struct tunable_uint64 *d = (struct tunable_uint64 *)data;
1102 TUNABLE_UINT64_FETCH(d->path, d->var);
1106 tunable_quad_init(void *data)
1108 struct tunable_quad *d = (struct tunable_quad *)data;
1110 TUNABLE_QUAD_FETCH(d->path, d->var);
1114 tunable_bool_init(void *data)
1116 struct tunable_bool *d = (struct tunable_bool *)data;
1118 TUNABLE_BOOL_FETCH(d->path, d->var);
1122 tunable_str_init(void *data)
1124 struct tunable_str *d = (struct tunable_str *)data;
1126 TUNABLE_STR_FETCH(d->path, d->var, d->size);