xref: /freebsd/sys/kern/subr_hints.c (revision 8ddb146abcdf061be9f2c0db7e391697dafad85c)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2000,2001 Peter Wemm <peter@FreeBSD.org>
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
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.
15  *
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
26  * SUCH DAMAGE.
27  */
28 
29 #include <sys/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/lock.h>
34 #include <sys/kenv.h>
35 #include <sys/kernel.h>
36 #include <sys/malloc.h>
37 #include <sys/mutex.h>
38 #include <sys/sysctl.h>
39 #include <sys/systm.h>
40 #include <sys/bus.h>
41 
42 #define	FBACK_MDENV	0	/* MD env (e.g. loader.conf) */
43 #define	FBACK_STENV	1	/* Static env */
44 #define	FBACK_STATIC	2	/* static_hints */
45 
46 /*
47  * We'll use hintenv_merged to indicate that the dynamic environment has been
48  * properly prepared for hint usage.  This implies that the dynamic environment
49  * has already been setup (dynamic_kenv) and that we have added any supplied
50  * static_hints to the dynamic environment.
51  */
52 static bool	hintenv_merged;
53 /* Static environment and static hints cannot change, so we'll skip known bad */
54 static bool	stenv_skip;
55 static bool	sthints_skip;
56 /*
57  * Access functions for device resources.
58  */
59 
60 static void
61 static_hints_to_env(void *data __unused)
62 {
63 	const char *cp;
64 	char *line, *eq;
65 	int eqidx, i;
66 
67 	cp = static_hints;
68 	while (cp && *cp != '\0') {
69 		eq = strchr(cp, '=');
70 		if (eq == NULL)
71 			/* Bad hint value */
72 			continue;
73 		eqidx = eq - cp;
74 
75 		i = strlen(cp);
76 		line = malloc(i + 1, M_TEMP, M_WAITOK);
77 		strcpy(line, cp);
78 		line[eqidx] = line[i] = '\0';
79 		/*
80 		 * Before adding a hint to the dynamic environment, check if
81 		 * another value for said hint has already been added.  This is
82 		 * needed because static environment overrides static hints and
83 		 * dynamic environment overrides all.
84 		 */
85 		if (testenv(line) == 0)
86 			kern_setenv(line, line + eqidx + 1);
87 		free(line, M_TEMP);
88 		cp += i + 1;
89 	}
90 	hintenv_merged = true;
91 }
92 
93 /* Any time after dynamic env is setup */
94 SYSINIT(hintenv, SI_SUB_KMEM + 1, SI_ORDER_SECOND, static_hints_to_env, NULL);
95 
96 /*
97  * Checks the environment to see if we even have any hints.  If it has no hints,
98  * then res_find can take the hint that there's no point in searching it and
99  * either move on to the next environment or fail early.
100  */
101 static bool
102 _res_checkenv(char *envp)
103 {
104 	char *cp;
105 
106 	cp = envp;
107 	while (cp) {
108 		if (strncmp(cp, "hint.", 5) == 0)
109 			return (true);
110 		while (*cp != '\0')
111 			cp++;
112 		cp++;
113 		if (*cp == '\0')
114 			break;
115 	}
116 	return (false);
117 }
118 
119 /*
120  * Evil wildcarding resource string lookup.
121  * This walks the supplied env string table and returns a match.
122  * The start point can be remembered for incremental searches.
123  */
124 static int
125 res_find(char **hintp_cookie, int *line, int *startln,
126     const char *name, int *unit, const char *resname, const char *value,
127     const char **ret_name, int *ret_namelen, int *ret_unit,
128     const char **ret_resname, int *ret_resnamelen, const char **ret_value)
129 {
130 	int fbacklvl = FBACK_MDENV, i = 0, n = 0, namelen;
131 	char r_name[32];
132 	int r_unit;
133 	char r_resname[32];
134 	char r_value[128];
135 	const char *s, *cp;
136 	char *hintp, *p;
137 	bool dyn_used = false;
138 
139 	/*
140 	 * We are expecting that the caller will pass us a hintp_cookie that
141 	 * they are tracking.  Upon entry, if *hintp_cookie is *not* set, this
142 	 * indicates to us that we should be figuring out based on the current
143 	 * environment where to search.  This keeps us sane throughout the
144 	 * entirety of a single search.
145 	 */
146 	if (*hintp_cookie == NULL) {
147 		hintp = NULL;
148 		if (hintenv_merged) {
149 			/*
150 			 * static_hints, if it was previously used, has
151 			 * already been folded in to the environment
152 			 * by this point.
153 			 */
154 			mtx_lock(&kenv_lock);
155 			cp = kenvp[0];
156 			for (i = 0; cp != NULL; cp = kenvp[++i]) {
157 				if (!strncmp(cp, "hint.", 5)) {
158 					hintp = kenvp[0];
159 					break;
160 				}
161 			}
162 			mtx_unlock(&kenv_lock);
163 			dyn_used = true;
164 		} else {
165 			/*
166 			 * We'll have a chance to keep coming back here until
167 			 * we've actually exhausted all of our possibilities.
168 			 * We might have chosen the MD/Static env because it
169 			 * had some kind of hints, but perhaps it didn't have
170 			 * the hint we are looking for.  We don't provide any
171 			 * fallback when searching the dynamic environment.
172 			 */
173 fallback:
174 			if (dyn_used || fbacklvl >= FBACK_STATIC)
175 				return (ENOENT);
176 
177 			switch (fbacklvl) {
178 			case FBACK_MDENV:
179 				fbacklvl++;
180 				if (_res_checkenv(md_envp)) {
181 					hintp = md_envp;
182 					break;
183 				}
184 
185 				/* FALLTHROUGH */
186 			case FBACK_STENV:
187 				fbacklvl++;
188 				if (!stenv_skip && _res_checkenv(kern_envp)) {
189 					hintp = kern_envp;
190 					break;
191 				} else
192 					stenv_skip = true;
193 
194 				/* FALLTHROUGH */
195 			case FBACK_STATIC:
196 				fbacklvl++;
197 				/* We'll fallback to static_hints if needed/can */
198 				if (!sthints_skip &&
199 				    _res_checkenv(static_hints))
200 					hintp = static_hints;
201 				else
202 					sthints_skip = true;
203 
204 				break;
205 			default:
206 				return (ENOENT);
207 			}
208 		}
209 
210 		if (hintp == NULL)
211 			return (ENOENT);
212 		*hintp_cookie = hintp;
213 	} else {
214 		hintp = *hintp_cookie;
215 		if (hintenv_merged && hintp == kenvp[0])
216 			dyn_used = true;
217 		else
218 			/*
219 			 * If we aren't using the dynamic environment, we need
220 			 * to run through the proper fallback procedure again.
221 			 * This is so that we do continuations right if we're
222 			 * working with *line and *startln.
223 			 */
224 			goto fallback;
225 	}
226 
227 	if (dyn_used) {
228 		mtx_lock(&kenv_lock);
229 		i = 0;
230 	}
231 
232 	if (name)
233 		namelen = strlen(name);
234 	cp = hintp;
235 	while (cp) {
236 		(*line)++;
237 		if (strncmp(cp, "hint.", 5) != 0)
238 			goto nexthint;
239 		if (name && strncmp(cp + 5, name, namelen) != 0)
240 			goto nexthint;
241 		n = sscanf(cp + 5, "%32[^.].%d.%32[^=]=%127s", r_name, &r_unit,
242 		    r_resname, r_value);
243 		if (n != 4) {
244 			printf("CONFIG: invalid hint '%s'\n", cp);
245 			p = strchr(cp, 'h');
246 			*p = 'H';
247 			goto nexthint;
248 		}
249 		if (startln && *startln >= 0 && *line < *startln)
250 			goto nexthint;
251 		if (name && strcmp(name, r_name) != 0)
252 			goto nexthint;
253 		if (unit && *unit != r_unit)
254 			goto nexthint;
255 		if (resname && strcmp(resname, r_resname) != 0)
256 			goto nexthint;
257 		if (value && strcmp(value, r_value) != 0)
258 			goto nexthint;
259 		/* Successfully found a hint matching all criteria */
260 		break;
261 nexthint:
262 		if (dyn_used) {
263 			cp = kenvp[++i];
264 			if (cp == NULL)
265 				break;
266 		} else {
267 			while (*cp != '\0')
268 				cp++;
269 			cp++;
270 			if (*cp == '\0') {
271 				cp = NULL;
272 				break;
273 			}
274 		}
275 	}
276 	if (dyn_used)
277 		mtx_unlock(&kenv_lock);
278 	if (cp == NULL)
279 		goto fallback;
280 
281 	s = cp;
282 	/* This is a bit of a hack, but at least is reentrant */
283 	/* Note that it returns some !unterminated! strings. */
284 	s = strchr(s, '.') + 1;		/* start of device */
285 	if (ret_name)
286 		*ret_name = s;
287 	s = strchr(s, '.') + 1;		/* start of unit */
288 	if (ret_namelen && ret_name)
289 		*ret_namelen = s - *ret_name - 1; /* device length */
290 	if (ret_unit)
291 		*ret_unit = r_unit;
292 	s = strchr(s, '.') + 1;		/* start of resname */
293 	if (ret_resname)
294 		*ret_resname = s;
295 	s = strchr(s, '=') + 1;		/* start of value */
296 	if (ret_resnamelen && ret_resname)
297 		*ret_resnamelen = s - *ret_resname - 1; /* value len */
298 	if (ret_value)
299 		*ret_value = s;
300 	if (startln)			/* line number for anchor */
301 		*startln = *line + 1;
302 	return 0;
303 }
304 
305 /*
306  * Search all the data sources for matches to our query.  We look for
307  * dynamic hints first as overrides for static or fallback hints.
308  */
309 static int
310 resource_find(int *line, int *startln,
311     const char *name, int *unit, const char *resname, const char *value,
312     const char **ret_name, int *ret_namelen, int *ret_unit,
313     const char **ret_resname, int *ret_resnamelen, const char **ret_value)
314 {
315 	int i;
316 	int un;
317 	char *hintp;
318 
319 	*line = 0;
320 	hintp = NULL;
321 
322 	/* Search for exact unit matches first */
323 	i = res_find(&hintp, line, startln, name, unit, resname, value,
324 	    ret_name, ret_namelen, ret_unit, ret_resname, ret_resnamelen,
325 	    ret_value);
326 	if (i == 0)
327 		return 0;
328 	if (unit == NULL)
329 		return ENOENT;
330 	/* If we are still here, search for wildcard matches */
331 	un = -1;
332 	i = res_find(&hintp, line, startln, name, &un, resname, value,
333 	    ret_name, ret_namelen, ret_unit, ret_resname, ret_resnamelen,
334 	    ret_value);
335 	if (i == 0)
336 		return 0;
337 	return ENOENT;
338 }
339 
340 int
341 resource_int_value(const char *name, int unit, const char *resname, int *result)
342 {
343 	int error;
344 	const char *str;
345 	char *op;
346 	unsigned long val;
347 	int line;
348 
349 	line = 0;
350 	error = resource_find(&line, NULL, name, &unit, resname, NULL,
351 	    NULL, NULL, NULL, NULL, NULL, &str);
352 	if (error)
353 		return error;
354 	if (*str == '\0')
355 		return EFTYPE;
356 	val = strtoul(str, &op, 0);
357 	if (*op != '\0')
358 		return EFTYPE;
359 	*result = val;
360 	return 0;
361 }
362 
363 int
364 resource_long_value(const char *name, int unit, const char *resname,
365     long *result)
366 {
367 	int error;
368 	const char *str;
369 	char *op;
370 	unsigned long val;
371 	int line;
372 
373 	line = 0;
374 	error = resource_find(&line, NULL, name, &unit, resname, NULL,
375 	    NULL, NULL, NULL, NULL, NULL, &str);
376 	if (error)
377 		return error;
378 	if (*str == '\0')
379 		return EFTYPE;
380 	val = strtoul(str, &op, 0);
381 	if (*op != '\0')
382 		return EFTYPE;
383 	*result = val;
384 	return 0;
385 }
386 
387 int
388 resource_string_value(const char *name, int unit, const char *resname,
389     const char **result)
390 {
391 	int error;
392 	const char *str;
393 	int line;
394 
395 	line = 0;
396 	error = resource_find(&line, NULL, name, &unit, resname, NULL,
397 	    NULL, NULL, NULL, NULL, NULL, &str);
398 	if (error)
399 		return error;
400 	*result = str;
401 	return 0;
402 }
403 
404 /*
405  * This is a bit nasty, but allows us to not modify the env strings.
406  */
407 static const char *
408 resource_string_copy(const char *s, int len)
409 {
410 	static char stringbuf[256];
411 	static int offset = 0;
412 	const char *ret;
413 
414 	if (len == 0)
415 		len = strlen(s);
416 	if (len > 255)
417 		return NULL;
418 	if ((offset + len + 1) > 255)
419 		offset = 0;
420 	bcopy(s, &stringbuf[offset], len);
421 	stringbuf[offset + len] = '\0';
422 	ret = &stringbuf[offset];
423 	offset += len + 1;
424 	return ret;
425 }
426 
427 /*
428  * err = resource_find_match(&anchor, &name, &unit, resname, value)
429  * Iteratively fetch a list of devices wired "at" something
430  * res and value are restrictions.  eg: "at", "scbus0".
431  * For practical purposes, res = required, value = optional.
432  * *name and *unit are set.
433  * set *anchor to zero before starting.
434  */
435 int
436 resource_find_match(int *anchor, const char **name, int *unit,
437     const char *resname, const char *value)
438 {
439 	const char *found_name;
440 	int found_namelen;
441 	int found_unit;
442 	int ret;
443 	int newln;
444 
445 	newln = *anchor;
446 	ret = resource_find(anchor, &newln, NULL, NULL, resname, value,
447 	    &found_name, &found_namelen, &found_unit, NULL, NULL, NULL);
448 	if (ret == 0) {
449 		*name = resource_string_copy(found_name, found_namelen);
450 		*unit = found_unit;
451 	}
452 	*anchor = newln;
453 	return ret;
454 }
455 
456 /*
457  * err = resource_find_dev(&anchor, name, &unit, res, value);
458  * Iterate through a list of devices, returning their unit numbers.
459  * res and value are optional restrictions.  eg: "at", "scbus0".
460  * *unit is set to the value.
461  * set *anchor to zero before starting.
462  */
463 int
464 resource_find_dev(int *anchor, const char *name, int *unit,
465     const char *resname, const char *value)
466 {
467 	int found_unit;
468 	int newln;
469 	int ret;
470 
471 	newln = *anchor;
472 	ret = resource_find(anchor, &newln, name, NULL, resname, value,
473 	    NULL, NULL, &found_unit, NULL, NULL, NULL);
474 	if (ret == 0) {
475 		*unit = found_unit;
476 	}
477 	*anchor = newln;
478 	return ret;
479 }
480 
481 /*
482  * Check to see if a device is disabled via a disabled hint.
483  */
484 int
485 resource_disabled(const char *name, int unit)
486 {
487 	int error, value;
488 
489 	error = resource_int_value(name, unit, "disabled", &value);
490 	if (error)
491 	       return (0);
492 	return (value);
493 }
494 
495 /*
496  * Clear a value associated with a device by removing it from
497  * the kernel environment.  This only removes a hint for an
498  * exact unit.
499  */
500 int
501 resource_unset_value(const char *name, int unit, const char *resname)
502 {
503 	char varname[128];
504 	const char *retname, *retvalue;
505 	int error, line;
506 	size_t len;
507 
508 	line = 0;
509 	error = resource_find(&line, NULL, name, &unit, resname, NULL,
510 	    &retname, NULL, NULL, NULL, NULL, &retvalue);
511 	if (error)
512 		return (error);
513 
514 	retname -= strlen("hint.");
515 	len = retvalue - retname - 1;
516 	if (len > sizeof(varname) - 1)
517 		return (ENAMETOOLONG);
518 	memcpy(varname, retname, len);
519 	varname[len] = '\0';
520 	return (kern_unsetenv(varname));
521 }
522