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