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>
49 #include <sys/kernel.h>
50 #include <sys/systm.h>
51 #include <sys/sysent.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 MALLOC_DEFINE(M_KENV, "kenv", "kernel environment");
64 #define KENV_SIZE 512 /* Maximum number of environment strings */
66 static uma_zone_t kenv_zone;
67 static int kenv_mvallen = KENV_MVALLEN;
69 /* pointer to the config-generated static environment */
72 /* pointer to the md-static environment */
74 static int md_env_len;
75 static int md_env_pos;
77 static char *kernenv_next(char *);
79 /* dynamic environment variables */
84 * No need to protect this with a mutex since SYSINITS are single threaded.
88 #define KENV_CHECK if (!dynamic_kenv) \
89 panic("%s: called before SI_SUB_KMEM", __func__)
91 static char *getenv_string_buffer(const char *);
103 char *name, *value, *buffer = NULL;
104 size_t len, done, needed, buflen;
107 KASSERT(dynamic_kenv, ("kenv: dynamic_kenv = false"));
110 if (uap->what == KENV_DUMP) {
112 error = mac_kenv_check_dump(td->td_ucred);
118 if (buflen > KENV_SIZE * (KENV_MNAMELEN + kenv_mvallen + 2))
119 buflen = KENV_SIZE * (KENV_MNAMELEN +
121 if (uap->len > 0 && uap->value != NULL)
122 buffer = malloc(buflen, M_TEMP, M_WAITOK|M_ZERO);
123 mtx_lock(&kenv_lock);
124 for (i = 0; kenvp[i] != NULL; i++) {
125 len = strlen(kenvp[i]) + 1;
127 len = min(len, buflen - done);
129 * If called with a NULL or insufficiently large
130 * buffer, just keep computing the required size.
132 if (uap->value != NULL && buffer != NULL && len > 0) {
133 bcopy(kenvp[i], buffer + done, len);
137 mtx_unlock(&kenv_lock);
138 if (buffer != NULL) {
139 error = copyout(buffer, uap->value, done);
140 free(buffer, M_TEMP);
142 td->td_retval[0] = ((done == needed) ? 0 : needed);
148 error = priv_check(td, PRIV_KENV_SET);
154 error = priv_check(td, PRIV_KENV_UNSET);
160 name = malloc(KENV_MNAMELEN + 1, M_TEMP, M_WAITOK);
162 error = copyinstr(uap->name, name, KENV_MNAMELEN + 1, NULL);
169 error = mac_kenv_check_get(td->td_ucred, name);
173 value = kern_getenv(name);
178 len = strlen(value) + 1;
181 error = copyout(value, uap->value, len);
185 td->td_retval[0] = len;
193 if (len > kenv_mvallen + 1)
194 len = kenv_mvallen + 1;
195 value = malloc(len, M_TEMP, M_WAITOK);
196 error = copyinstr(uap->value, value, len, NULL);
202 error = mac_kenv_check_set(td->td_ucred, name, value);
205 kern_setenv(name, value);
210 error = mac_kenv_check_unset(td->td_ucred, name);
214 error = kern_unsetenv(name);
228 * Populate the initial kernel environment.
230 * This is called very early in MD startup, either to provide a copy of the
231 * environment obtained from a boot loader, or to provide an empty buffer into
232 * which MD code can store an initial environment using kern_setenv() calls.
234 * kern_envp is set to the static_env generated by config(8). This implements
235 * the env keyword described in config(5).
237 * If len is non-zero, the caller is providing an empty buffer. The caller will
238 * subsequently use kern_setenv() to add up to len bytes of initial environment
239 * before the dynamic environment is available.
241 * If len is zero, the caller is providing a pre-loaded buffer containing
242 * environment strings. Additional strings cannot be added until the dynamic
243 * environment is available. The memory pointed to must remain stable at least
244 * until sysinit runs init_dynamic_kenv() and preferably until after SI_SUB_KMEM
245 * is finished so that subr_hints routines may continue to use it until the
246 * environments have been fully merged at the end of the pass. If no initial
247 * environment is available from the boot loader, passing a NULL pointer allows
248 * the static_env to be installed if it is configured. In this case, any call
249 * to kern_setenv() prior to the setup of the dynamic environment will result in
253 init_static_kenv(char *buf, size_t len)
257 KASSERT(!dynamic_kenv, ("kenv: dynamic_kenv already initialized"));
259 * Suitably sized means it must be able to hold at least one empty
260 * variable, otherwise things go belly up if a kern_getenv call is
261 * made without a prior call to kern_setenv as we have a malformed
264 KASSERT(len == 0 || len >= 2,
265 ("kenv: static env must be initialized or suitably sized"));
266 KASSERT(len == 0 || (*buf == '\0' && *(buf + 1) == '\0'),
267 ("kenv: sized buffer must be initially empty"));
270 * We may be called twice, with the second call needed to relocate
271 * md_envp after enabling paging. md_envp is then garbage if it is
272 * not null and the relocation will move it. Discard it so as to
273 * not crash using its old value in our first call to kern_getenv().
275 * The second call gives the same environment as the first except
276 * in silly configurations where the static env disables itself.
278 * Other env calls don't handle possibly-garbage pointers, so must
279 * not be made between enabling paging and calling here.
286 * Give the static environment a chance to disable the loader(8)
287 * environment first. This is done with loader_env.disabled=1.
289 * static_env and static_hints may both be disabled, but in slightly
290 * different ways. For static_env, we just don't setup kern_envp and
291 * it's as if a static env wasn't even provided. For static_hints,
292 * we effectively zero out the buffer to stop the rest of the kernel
293 * from being able to use it.
295 * We're intentionally setting this up so that static_hints.disabled may
296 * be specified in either the MD env or the static env. This keeps us
297 * consistent in our new world view.
299 * As a warning, the static environment may not be disabled in any way
300 * if the static environment has disabled the loader environment.
302 kern_envp = static_env;
303 eval = kern_getenv("loader_env.disabled");
304 if (eval == NULL || strcmp(eval, "1") != 0) {
309 eval = kern_getenv("static_env.disabled");
310 if (eval != NULL && strcmp(eval, "1") == 0) {
315 eval = kern_getenv("static_hints.disabled");
316 if (eval != NULL && strcmp(eval, "1") == 0) {
317 static_hints[0] = '\0';
318 static_hints[1] = '\0';
323 init_dynamic_kenv_from(char *init_env, int *curpos)
325 char *cp, *cpnext, *eqpos, *found;
329 if (init_env && *init_env != '\0') {
332 for (cp = init_env; cp != NULL; cp = cpnext) {
333 cpnext = kernenv_next(cp);
334 len = strlen(cp) + 1;
335 if (len > KENV_MNAMELEN + 1 + kenv_mvallen + 1) {
337 "WARNING: too long kenv string, ignoring %s\n",
341 eqpos = strchr(cp, '=');
344 "WARNING: malformed static env value, ignoring %s\n",
350 * De-dupe the environment as we go. We don't add the
351 * duplicated assignments because config(8) will flip
352 * the order of the static environment around to make
353 * kernel processing match the order of specification
354 * in the kernel config.
356 found = _getenv_dynamic_locked(cp, NULL);
362 "WARNING: too many kenv strings, ignoring %s\n",
367 kenvp[i] = malloc(len, M_KENV, M_WAITOK);
368 strcpy(kenvp[i++], cp);
370 explicit_bzero(cp, len - 1);
377 * Setup the dynamic kernel environment.
380 init_dynamic_kenv(void *data __unused)
385 TUNABLE_INT_FETCH("kenv_mvallen", &kenv_mvallen);
386 size = KENV_MNAMELEN + 1 + kenv_mvallen + 1;
388 kenv_zone = uma_zcreate("kenv", size, NULL, NULL, NULL, NULL,
391 kenvp = malloc((KENV_SIZE + 1) * sizeof(char *), M_KENV,
395 init_dynamic_kenv_from(md_envp, &dynamic_envpos);
396 init_dynamic_kenv_from(kern_envp, &dynamic_envpos);
397 kenvp[dynamic_envpos] = NULL;
399 mtx_init(&kenv_lock, "kernel environment", NULL, MTX_DEF);
402 SYSINIT(kenv, SI_SUB_KMEM + 1, SI_ORDER_FIRST, init_dynamic_kenv, NULL);
408 if (dynamic_kenv && env != NULL) {
409 explicit_bzero(env, strlen(env));
410 uma_zfree(kenv_zone, env);
415 * Internal functions for string lookup.
418 _getenv_dynamic_locked(const char *name, int *idx)
424 for (cp = kenvp[0], i = 0; cp != NULL; cp = kenvp[++i]) {
425 if ((strncmp(cp, name, len) == 0) &&
429 return (cp + len + 1);
436 _getenv_dynamic(const char *name, int *idx)
439 mtx_assert(&kenv_lock, MA_OWNED);
440 return (_getenv_dynamic_locked(name, idx));
444 _getenv_static_from(char *chkenv, const char *name)
449 for (cp = chkenv; cp != NULL; cp = kernenv_next(cp)) {
450 for (ep = cp; (*ep != '=') && (*ep != 0); ep++)
456 if (!strncmp(name, cp, len) && name[len] == 0)
463 _getenv_static(const char *name)
467 val = _getenv_static_from(md_envp, name);
470 val = _getenv_static_from(kern_envp, name);
477 * Look up an environment variable by name.
478 * Return a pointer to the string if found.
479 * The pointer has to be freed with freeenv()
483 kern_getenv(const char *name)
488 ret = getenv_string_buffer(name);
490 WITNESS_WARN(WARN_GIANTOK | WARN_SLEEPOK, NULL,
494 ret = _getenv_static(name);
499 * Test if an environment variable is defined.
502 testenv(const char *name)
507 mtx_lock(&kenv_lock);
508 cp = _getenv_dynamic(name, NULL);
509 mtx_unlock(&kenv_lock);
511 cp = _getenv_static(name);
518 * Set an environment variable in the MD-static environment. This cannot
519 * feasibly be done on config(8)-generated static environments as they don't
520 * generally include space for extra variables.
523 setenv_static(const char *name, const char *value)
527 if (md_env_pos >= md_env_len)
530 /* Check space for x=y and two nuls */
531 len = strlen(name) + strlen(value);
532 if (len + 3 < md_env_len - md_env_pos) {
533 len = sprintf(&md_envp[md_env_pos], "%s=%s", name, value);
535 md_envp[md_env_pos] = '\0';
543 * Set an environment variable by name.
546 kern_setenv(const char *name, const char *value)
548 char *buf, *cp, *oldenv;
549 int namelen, vallen, i;
551 if (!dynamic_kenv && md_env_len > 0)
552 return (setenv_static(name, value));
556 namelen = strlen(name) + 1;
557 if (namelen > KENV_MNAMELEN + 1)
559 vallen = strlen(value) + 1;
560 if (vallen > kenv_mvallen + 1)
562 buf = malloc(namelen + vallen, M_KENV, M_WAITOK);
563 sprintf(buf, "%s=%s", name, value);
565 mtx_lock(&kenv_lock);
566 cp = _getenv_dynamic(name, &i);
570 mtx_unlock(&kenv_lock);
571 free(oldenv, M_KENV);
573 /* We add the option if it wasn't found */
574 for (i = 0; (cp = kenvp[i]) != NULL; i++)
577 /* Bounds checking */
578 if (i < 0 || i >= KENV_SIZE) {
580 mtx_unlock(&kenv_lock);
586 mtx_unlock(&kenv_lock);
592 * Unset an environment variable string.
595 kern_unsetenv(const char *name)
602 mtx_lock(&kenv_lock);
603 cp = _getenv_dynamic(name, &i);
606 for (j = i + 1; kenvp[j] != NULL; j++)
607 kenvp[i++] = kenvp[j];
609 mtx_unlock(&kenv_lock);
610 explicit_bzero(oldenv, strlen(oldenv));
611 free(oldenv, M_KENV);
614 mtx_unlock(&kenv_lock);
619 * Return a buffer containing the string value from an environment variable
622 getenv_string_buffer(const char *name)
628 len = KENV_MNAMELEN + 1 + kenv_mvallen + 1;
629 ret = uma_zalloc(kenv_zone, M_WAITOK | M_ZERO);
630 mtx_lock(&kenv_lock);
631 cp = _getenv_dynamic(name, NULL);
633 strlcpy(ret, cp, len);
634 mtx_unlock(&kenv_lock);
636 uma_zfree(kenv_zone, ret);
640 ret = _getenv_static(name);
646 * Return a string value from an environment variable.
649 getenv_string(const char *name, char *data, int size)
654 mtx_lock(&kenv_lock);
655 cp = _getenv_dynamic(name, NULL);
657 strlcpy(data, cp, size);
658 mtx_unlock(&kenv_lock);
660 cp = _getenv_static(name);
662 strlcpy(data, cp, size);
668 * Return an array of integers at the given type size and signedness.
671 getenv_array(const char *name, void *pdata, int size, int *psize,
672 int type_size, bool allow_signed)
683 if ((buf = getenv_string_buffer(name)) == NULL)
686 rc = 0; /* assume failure */
687 /* get maximum number of elements */
692 for (ptr = buf; *ptr != 0; ) {
694 value = strtoq(ptr, &end, 0);
696 /* check if signed numbers are allowed */
697 if (value < 0 && !allow_signed)
700 /* check for invalid value */
704 /* check for valid suffix */
733 /* garbage after numeric value */
737 /* skip till next value, if any */
738 while (*end == '\t' || *end == ',' || *end == ' ')
749 if ((value >> shift) != old)
752 /* check for buffer overflow */
756 /* store value according to type size */
760 if (value < SCHAR_MIN || value > SCHAR_MAX)
763 if (value < 0 || value > UCHAR_MAX)
766 ((uint8_t *)pdata)[n] = (uint8_t)value;
770 if (value < SHRT_MIN || value > SHRT_MAX)
773 if (value < 0 || value > USHRT_MAX)
776 ((uint16_t *)pdata)[n] = (uint16_t)value;
780 if (value < INT_MIN || value > INT_MAX)
783 if (value > UINT_MAX)
786 ((uint32_t *)pdata)[n] = (uint32_t)value;
789 ((uint64_t *)pdata)[n] = (uint64_t)value;
796 *psize = n * type_size;
799 rc = 1; /* success */
802 uma_zfree(kenv_zone, buf);
807 * Return an integer value from an environment variable.
810 getenv_int(const char *name, int *data)
815 rval = getenv_quad(name, &tmp);
822 * Return an unsigned integer value from an environment variable.
825 getenv_uint(const char *name, unsigned int *data)
830 rval = getenv_quad(name, &tmp);
832 *data = (unsigned int) tmp;
837 * Return an int64_t value from an environment variable.
840 getenv_int64(const char *name, int64_t *data)
845 rval = getenv_quad(name, &tmp);
847 *data = (int64_t) tmp;
852 * Return an uint64_t value from an environment variable.
855 getenv_uint64(const char *name, uint64_t *data)
860 rval = getenv_quad(name, &tmp);
862 *data = (uint64_t) tmp;
867 * Return a long value from an environment variable.
870 getenv_long(const char *name, long *data)
875 rval = getenv_quad(name, &tmp);
882 * Return an unsigned long value from an environment variable.
885 getenv_ulong(const char *name, unsigned long *data)
890 rval = getenv_quad(name, &tmp);
892 *data = (unsigned long) tmp;
897 * Return a quad_t value from an environment variable.
900 getenv_quad(const char *name, quad_t *data)
905 value = getenv_string_buffer(name);
908 iv = strtoq(value, &vtp, 0);
909 if (vtp == value || (vtp[0] != '\0' && vtp[1] != '\0')) {
937 * Find the next entry after the one which (cp) falls within, return a
938 * pointer to its start or NULL if there are no more.
941 kernenv_next(char *cp)
955 tunable_int_init(void *data)
957 struct tunable_int *d = (struct tunable_int *)data;
959 TUNABLE_INT_FETCH(d->path, d->var);
963 tunable_long_init(void *data)
965 struct tunable_long *d = (struct tunable_long *)data;
967 TUNABLE_LONG_FETCH(d->path, d->var);
971 tunable_ulong_init(void *data)
973 struct tunable_ulong *d = (struct tunable_ulong *)data;
975 TUNABLE_ULONG_FETCH(d->path, d->var);
979 tunable_int64_init(void *data)
981 struct tunable_int64 *d = (struct tunable_int64 *)data;
983 TUNABLE_INT64_FETCH(d->path, d->var);
987 tunable_uint64_init(void *data)
989 struct tunable_uint64 *d = (struct tunable_uint64 *)data;
991 TUNABLE_UINT64_FETCH(d->path, d->var);
995 tunable_quad_init(void *data)
997 struct tunable_quad *d = (struct tunable_quad *)data;
999 TUNABLE_QUAD_FETCH(d->path, d->var);
1003 tunable_str_init(void *data)
1005 struct tunable_str *d = (struct tunable_str *)data;
1007 TUNABLE_STR_FETCH(d->path, d->var, d->size);