xref: /openbmc/linux/lib/bootconfig.c (revision 081c65360bd817672d0753fdf68ab34802d7a81d)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Extra Boot Config
4  * Masami Hiramatsu <mhiramat@kernel.org>
5  */
6 
7 #define pr_fmt(fmt)    "bootconfig: " fmt
8 
9 #include <linux/bug.h>
10 #include <linux/ctype.h>
11 #include <linux/errno.h>
12 #include <linux/kernel.h>
13 #include <linux/printk.h>
14 #include <linux/bootconfig.h>
15 #include <linux/string.h>
16 
17 /*
18  * Extra Boot Config (XBC) is given as tree-structured ascii text of
19  * key-value pairs on memory.
20  * xbc_parse() parses the text to build a simple tree. Each tree node is
21  * simply a key word or a value. A key node may have a next key node or/and
22  * a child node (both key and value). A value node may have a next value
23  * node (for array).
24  */
25 
26 static struct xbc_node xbc_nodes[XBC_NODE_MAX] __initdata;
27 static int xbc_node_num __initdata;
28 static char *xbc_data __initdata;
29 static size_t xbc_data_size __initdata;
30 static struct xbc_node *last_parent __initdata;
31 
32 static int __init xbc_parse_error(const char *msg, const char *p)
33 {
34 	int pos = p - xbc_data;
35 
36 	pr_err("Parse error at pos %d: %s\n", pos, msg);
37 	return -EINVAL;
38 }
39 
40 /**
41  * xbc_root_node() - Get the root node of extended boot config
42  *
43  * Return the address of root node of extended boot config. If the
44  * extended boot config is not initiized, return NULL.
45  */
46 struct xbc_node * __init xbc_root_node(void)
47 {
48 	if (unlikely(!xbc_data))
49 		return NULL;
50 
51 	return xbc_nodes;
52 }
53 
54 /**
55  * xbc_node_index() - Get the index of XBC node
56  * @node: A target node of getting index.
57  *
58  * Return the index number of @node in XBC node list.
59  */
60 int __init xbc_node_index(struct xbc_node *node)
61 {
62 	return node - &xbc_nodes[0];
63 }
64 
65 /**
66  * xbc_node_get_parent() - Get the parent XBC node
67  * @node: An XBC node.
68  *
69  * Return the parent node of @node. If the node is top node of the tree,
70  * return NULL.
71  */
72 struct xbc_node * __init xbc_node_get_parent(struct xbc_node *node)
73 {
74 	return node->parent == XBC_NODE_MAX ? NULL : &xbc_nodes[node->parent];
75 }
76 
77 /**
78  * xbc_node_get_child() - Get the child XBC node
79  * @node: An XBC node.
80  *
81  * Return the first child node of @node. If the node has no child, return
82  * NULL.
83  */
84 struct xbc_node * __init xbc_node_get_child(struct xbc_node *node)
85 {
86 	return node->child ? &xbc_nodes[node->child] : NULL;
87 }
88 
89 /**
90  * xbc_node_get_next() - Get the next sibling XBC node
91  * @node: An XBC node.
92  *
93  * Return the NEXT sibling node of @node. If the node has no next sibling,
94  * return NULL. Note that even if this returns NULL, it doesn't mean @node
95  * has no siblings. (You also has to check whether the parent's child node
96  * is @node or not.)
97  */
98 struct xbc_node * __init xbc_node_get_next(struct xbc_node *node)
99 {
100 	return node->next ? &xbc_nodes[node->next] : NULL;
101 }
102 
103 /**
104  * xbc_node_get_data() - Get the data of XBC node
105  * @node: An XBC node.
106  *
107  * Return the data (which is always a null terminated string) of @node.
108  * If the node has invalid data, warn and return NULL.
109  */
110 const char * __init xbc_node_get_data(struct xbc_node *node)
111 {
112 	int offset = node->data & ~XBC_VALUE;
113 
114 	if (WARN_ON(offset >= xbc_data_size))
115 		return NULL;
116 
117 	return xbc_data + offset;
118 }
119 
120 static bool __init
121 xbc_node_match_prefix(struct xbc_node *node, const char **prefix)
122 {
123 	const char *p = xbc_node_get_data(node);
124 	int len = strlen(p);
125 
126 	if (strncmp(*prefix, p, len))
127 		return false;
128 
129 	p = *prefix + len;
130 	if (*p == '.')
131 		p++;
132 	else if (*p != '\0')
133 		return false;
134 	*prefix = p;
135 
136 	return true;
137 }
138 
139 /**
140  * xbc_node_find_child() - Find a child node which matches given key
141  * @parent: An XBC node.
142  * @key: A key string.
143  *
144  * Search a node under @parent which matches @key. The @key can contain
145  * several words jointed with '.'. If @parent is NULL, this searches the
146  * node from whole tree. Return NULL if no node is matched.
147  */
148 struct xbc_node * __init
149 xbc_node_find_child(struct xbc_node *parent, const char *key)
150 {
151 	struct xbc_node *node;
152 
153 	if (parent)
154 		node = xbc_node_get_child(parent);
155 	else
156 		node = xbc_root_node();
157 
158 	while (node && xbc_node_is_key(node)) {
159 		if (!xbc_node_match_prefix(node, &key))
160 			node = xbc_node_get_next(node);
161 		else if (*key != '\0')
162 			node = xbc_node_get_child(node);
163 		else
164 			break;
165 	}
166 
167 	return node;
168 }
169 
170 /**
171  * xbc_node_find_value() - Find a value node which matches given key
172  * @parent: An XBC node.
173  * @key: A key string.
174  * @vnode: A container pointer of found XBC node.
175  *
176  * Search a value node under @parent whose (parent) key node matches @key,
177  * store it in *@vnode, and returns the value string.
178  * The @key can contain several words jointed with '.'. If @parent is NULL,
179  * this searches the node from whole tree. Return the value string if a
180  * matched key found, return NULL if no node is matched.
181  * Note that this returns 0-length string and stores NULL in *@vnode if the
182  * key has no value. And also it will return the value of the first entry if
183  * the value is an array.
184  */
185 const char * __init
186 xbc_node_find_value(struct xbc_node *parent, const char *key,
187 		    struct xbc_node **vnode)
188 {
189 	struct xbc_node *node = xbc_node_find_child(parent, key);
190 
191 	if (!node || !xbc_node_is_key(node))
192 		return NULL;
193 
194 	node = xbc_node_get_child(node);
195 	if (node && !xbc_node_is_value(node))
196 		return NULL;
197 
198 	if (vnode)
199 		*vnode = node;
200 
201 	return node ? xbc_node_get_data(node) : "";
202 }
203 
204 /**
205  * xbc_node_compose_key_after() - Compose partial key string of the XBC node
206  * @root: Root XBC node
207  * @node: Target XBC node.
208  * @buf: A buffer to store the key.
209  * @size: The size of the @buf.
210  *
211  * Compose the partial key of the @node into @buf, which is starting right
212  * after @root (@root is not included.) If @root is NULL, this returns full
213  * key words of @node.
214  * Returns the total length of the key stored in @buf. Returns -EINVAL
215  * if @node is NULL or @root is not the ancestor of @node or @root is @node,
216  * or returns -ERANGE if the key depth is deeper than max depth.
217  * This is expected to be used with xbc_find_node() to list up all (child)
218  * keys under given key.
219  */
220 int __init xbc_node_compose_key_after(struct xbc_node *root,
221 				      struct xbc_node *node,
222 				      char *buf, size_t size)
223 {
224 	u16 keys[XBC_DEPTH_MAX];
225 	int depth = 0, ret = 0, total = 0;
226 
227 	if (!node || node == root)
228 		return -EINVAL;
229 
230 	if (xbc_node_is_value(node))
231 		node = xbc_node_get_parent(node);
232 
233 	while (node && node != root) {
234 		keys[depth++] = xbc_node_index(node);
235 		if (depth == XBC_DEPTH_MAX)
236 			return -ERANGE;
237 		node = xbc_node_get_parent(node);
238 	}
239 	if (!node && root)
240 		return -EINVAL;
241 
242 	while (--depth >= 0) {
243 		node = xbc_nodes + keys[depth];
244 		ret = snprintf(buf, size, "%s%s", xbc_node_get_data(node),
245 			       depth ? "." : "");
246 		if (ret < 0)
247 			return ret;
248 		if (ret > size) {
249 			size = 0;
250 		} else {
251 			size -= ret;
252 			buf += ret;
253 		}
254 		total += ret;
255 	}
256 
257 	return total;
258 }
259 
260 /**
261  * xbc_node_find_next_leaf() - Find the next leaf node under given node
262  * @root: An XBC root node
263  * @node: An XBC node which starts from.
264  *
265  * Search the next leaf node (which means the terminal key node) of @node
266  * under @root node (including @root node itself).
267  * Return the next node or NULL if next leaf node is not found.
268  */
269 struct xbc_node * __init xbc_node_find_next_leaf(struct xbc_node *root,
270 						 struct xbc_node *node)
271 {
272 	if (unlikely(!xbc_data))
273 		return NULL;
274 
275 	if (!node) {	/* First try */
276 		node = root;
277 		if (!node)
278 			node = xbc_nodes;
279 	} else {
280 		if (node == root)	/* @root was a leaf, no child node. */
281 			return NULL;
282 
283 		while (!node->next) {
284 			node = xbc_node_get_parent(node);
285 			if (node == root)
286 				return NULL;
287 			/* User passed a node which is not uder parent */
288 			if (WARN_ON(!node))
289 				return NULL;
290 		}
291 		node = xbc_node_get_next(node);
292 	}
293 
294 	while (node && !xbc_node_is_leaf(node))
295 		node = xbc_node_get_child(node);
296 
297 	return node;
298 }
299 
300 /**
301  * xbc_node_find_next_key_value() - Find the next key-value pair nodes
302  * @root: An XBC root node
303  * @leaf: A container pointer of XBC node which starts from.
304  *
305  * Search the next leaf node (which means the terminal key node) of *@leaf
306  * under @root node. Returns the value and update *@leaf if next leaf node
307  * is found, or NULL if no next leaf node is found.
308  * Note that this returns 0-length string if the key has no value, or
309  * the value of the first entry if the value is an array.
310  */
311 const char * __init xbc_node_find_next_key_value(struct xbc_node *root,
312 						 struct xbc_node **leaf)
313 {
314 	/* tip must be passed */
315 	if (WARN_ON(!leaf))
316 		return NULL;
317 
318 	*leaf = xbc_node_find_next_leaf(root, *leaf);
319 	if (!*leaf)
320 		return NULL;
321 	if ((*leaf)->child)
322 		return xbc_node_get_data(xbc_node_get_child(*leaf));
323 	else
324 		return "";	/* No value key */
325 }
326 
327 /* XBC parse and tree build */
328 
329 static struct xbc_node * __init xbc_add_node(char *data, u32 flag)
330 {
331 	struct xbc_node *node;
332 	unsigned long offset;
333 
334 	if (xbc_node_num == XBC_NODE_MAX)
335 		return NULL;
336 
337 	node = &xbc_nodes[xbc_node_num++];
338 	offset = data - xbc_data;
339 	node->data = (u16)offset;
340 	if (WARN_ON(offset >= XBC_DATA_MAX))
341 		return NULL;
342 	node->data |= flag;
343 	node->child = 0;
344 	node->next = 0;
345 
346 	return node;
347 }
348 
349 static inline __init struct xbc_node *xbc_last_sibling(struct xbc_node *node)
350 {
351 	while (node->next)
352 		node = xbc_node_get_next(node);
353 
354 	return node;
355 }
356 
357 static struct xbc_node * __init xbc_add_sibling(char *data, u32 flag)
358 {
359 	struct xbc_node *sib, *node = xbc_add_node(data, flag);
360 
361 	if (node) {
362 		if (!last_parent) {
363 			node->parent = XBC_NODE_MAX;
364 			sib = xbc_last_sibling(xbc_nodes);
365 			sib->next = xbc_node_index(node);
366 		} else {
367 			node->parent = xbc_node_index(last_parent);
368 			if (!last_parent->child) {
369 				last_parent->child = xbc_node_index(node);
370 			} else {
371 				sib = xbc_node_get_child(last_parent);
372 				sib = xbc_last_sibling(sib);
373 				sib->next = xbc_node_index(node);
374 			}
375 		}
376 	}
377 
378 	return node;
379 }
380 
381 static inline __init struct xbc_node *xbc_add_child(char *data, u32 flag)
382 {
383 	struct xbc_node *node = xbc_add_sibling(data, flag);
384 
385 	if (node)
386 		last_parent = node;
387 
388 	return node;
389 }
390 
391 static inline __init bool xbc_valid_keyword(char *key)
392 {
393 	if (key[0] == '\0')
394 		return false;
395 
396 	while (isalnum(*key) || *key == '-' || *key == '_')
397 		key++;
398 
399 	return *key == '\0';
400 }
401 
402 static char *skip_comment(char *p)
403 {
404 	char *ret;
405 
406 	ret = strchr(p, '\n');
407 	if (!ret)
408 		ret = p + strlen(p);
409 	else
410 		ret++;
411 
412 	return ret;
413 }
414 
415 static char *skip_spaces_until_newline(char *p)
416 {
417 	while (isspace(*p) && *p != '\n')
418 		p++;
419 	return p;
420 }
421 
422 static int __init __xbc_open_brace(void)
423 {
424 	/* Mark the last key as open brace */
425 	last_parent->next = XBC_NODE_MAX;
426 
427 	return 0;
428 }
429 
430 static int __init __xbc_close_brace(char *p)
431 {
432 	struct xbc_node *node;
433 
434 	if (!last_parent || last_parent->next != XBC_NODE_MAX)
435 		return xbc_parse_error("Unexpected closing brace", p);
436 
437 	node = last_parent;
438 	node->next = 0;
439 	do {
440 		node = xbc_node_get_parent(node);
441 	} while (node && node->next != XBC_NODE_MAX);
442 	last_parent = node;
443 
444 	return 0;
445 }
446 
447 /*
448  * Return delimiter or error, no node added. As same as lib/cmdline.c,
449  * you can use " around spaces, but can't escape " for value.
450  */
451 static int __init __xbc_parse_value(char **__v, char **__n)
452 {
453 	char *p, *v = *__v;
454 	int c, quotes = 0;
455 
456 	v = skip_spaces(v);
457 	while (*v == '#') {
458 		v = skip_comment(v);
459 		v = skip_spaces(v);
460 	}
461 	if (*v == '"' || *v == '\'') {
462 		quotes = *v;
463 		v++;
464 	}
465 	p = v - 1;
466 	while ((c = *++p)) {
467 		if (!isprint(c) && !isspace(c))
468 			return xbc_parse_error("Non printable value", p);
469 		if (quotes) {
470 			if (c != quotes)
471 				continue;
472 			quotes = 0;
473 			*p++ = '\0';
474 			p = skip_spaces_until_newline(p);
475 			c = *p;
476 			if (c && !strchr(",;\n#}", c))
477 				return xbc_parse_error("No value delimiter", p);
478 			if (*p)
479 				p++;
480 			break;
481 		}
482 		if (strchr(",;\n#}", c)) {
483 			v = strim(v);
484 			*p++ = '\0';
485 			break;
486 		}
487 	}
488 	if (quotes)
489 		return xbc_parse_error("No closing quotes", p);
490 	if (c == '#') {
491 		p = skip_comment(p);
492 		c = '\n';	/* A comment must be treated as a newline */
493 	}
494 	*__n = p;
495 	*__v = v;
496 
497 	return c;
498 }
499 
500 static int __init xbc_parse_array(char **__v)
501 {
502 	struct xbc_node *node;
503 	char *next;
504 	int c = 0;
505 
506 	do {
507 		c = __xbc_parse_value(__v, &next);
508 		if (c < 0)
509 			return c;
510 
511 		node = xbc_add_sibling(*__v, XBC_VALUE);
512 		if (!node)
513 			return -ENOMEM;
514 		*__v = next;
515 	} while (c == ',');
516 	node->next = 0;
517 
518 	return c;
519 }
520 
521 static inline __init
522 struct xbc_node *find_match_node(struct xbc_node *node, char *k)
523 {
524 	while (node) {
525 		if (!strcmp(xbc_node_get_data(node), k))
526 			break;
527 		node = xbc_node_get_next(node);
528 	}
529 	return node;
530 }
531 
532 static int __init __xbc_add_key(char *k)
533 {
534 	struct xbc_node *node;
535 
536 	if (!xbc_valid_keyword(k))
537 		return xbc_parse_error("Invalid keyword", k);
538 
539 	if (unlikely(xbc_node_num == 0))
540 		goto add_node;
541 
542 	if (!last_parent)	/* the first level */
543 		node = find_match_node(xbc_nodes, k);
544 	else
545 		node = find_match_node(xbc_node_get_child(last_parent), k);
546 
547 	if (node)
548 		last_parent = node;
549 	else {
550 add_node:
551 		node = xbc_add_child(k, XBC_KEY);
552 		if (!node)
553 			return -ENOMEM;
554 	}
555 	return 0;
556 }
557 
558 static int __init __xbc_parse_keys(char *k)
559 {
560 	char *p;
561 	int ret;
562 
563 	k = strim(k);
564 	while ((p = strchr(k, '.'))) {
565 		*p++ = '\0';
566 		ret = __xbc_add_key(k);
567 		if (ret)
568 			return ret;
569 		k = p;
570 	}
571 
572 	return __xbc_add_key(k);
573 }
574 
575 static int __init xbc_parse_kv(char **k, char *v)
576 {
577 	struct xbc_node *prev_parent = last_parent;
578 	struct xbc_node *node;
579 	char *next;
580 	int c, ret;
581 
582 	ret = __xbc_parse_keys(*k);
583 	if (ret)
584 		return ret;
585 
586 	c = __xbc_parse_value(&v, &next);
587 	if (c < 0)
588 		return c;
589 
590 	node = xbc_add_sibling(v, XBC_VALUE);
591 	if (!node)
592 		return -ENOMEM;
593 
594 	if (c == ',') {	/* Array */
595 		c = xbc_parse_array(&next);
596 		if (c < 0)
597 			return c;
598 	}
599 
600 	last_parent = prev_parent;
601 
602 	if (c == '}') {
603 		ret = __xbc_close_brace(next - 1);
604 		if (ret < 0)
605 			return ret;
606 	}
607 
608 	*k = next;
609 
610 	return 0;
611 }
612 
613 static int __init xbc_parse_key(char **k, char *n)
614 {
615 	struct xbc_node *prev_parent = last_parent;
616 	int ret;
617 
618 	*k = strim(*k);
619 	if (**k != '\0') {
620 		ret = __xbc_parse_keys(*k);
621 		if (ret)
622 			return ret;
623 		last_parent = prev_parent;
624 	}
625 	*k = n;
626 
627 	return 0;
628 }
629 
630 static int __init xbc_open_brace(char **k, char *n)
631 {
632 	int ret;
633 
634 	ret = __xbc_parse_keys(*k);
635 	if (ret)
636 		return ret;
637 	*k = n;
638 
639 	return __xbc_open_brace();
640 }
641 
642 static int __init xbc_close_brace(char **k, char *n)
643 {
644 	int ret;
645 
646 	ret = xbc_parse_key(k, n);
647 	if (ret)
648 		return ret;
649 	/* k is updated in xbc_parse_key() */
650 
651 	return __xbc_close_brace(n - 1);
652 }
653 
654 static int __init xbc_verify_tree(void)
655 {
656 	int i, depth, len, wlen;
657 	struct xbc_node *n, *m;
658 
659 	/* Empty tree */
660 	if (xbc_node_num == 0)
661 		return -ENOENT;
662 
663 	for (i = 0; i < xbc_node_num; i++) {
664 		if (xbc_nodes[i].next > xbc_node_num) {
665 			return xbc_parse_error("No closing brace",
666 				xbc_node_get_data(xbc_nodes + i));
667 		}
668 	}
669 
670 	/* Key tree limitation check */
671 	n = &xbc_nodes[0];
672 	depth = 1;
673 	len = 0;
674 
675 	while (n) {
676 		wlen = strlen(xbc_node_get_data(n)) + 1;
677 		len += wlen;
678 		if (len > XBC_KEYLEN_MAX)
679 			return xbc_parse_error("Too long key length",
680 				xbc_node_get_data(n));
681 
682 		m = xbc_node_get_child(n);
683 		if (m && xbc_node_is_key(m)) {
684 			n = m;
685 			depth++;
686 			if (depth > XBC_DEPTH_MAX)
687 				return xbc_parse_error("Too many key words",
688 						xbc_node_get_data(n));
689 			continue;
690 		}
691 		len -= wlen;
692 		m = xbc_node_get_next(n);
693 		while (!m) {
694 			n = xbc_node_get_parent(n);
695 			if (!n)
696 				break;
697 			len -= strlen(xbc_node_get_data(n)) + 1;
698 			depth--;
699 			m = xbc_node_get_next(n);
700 		}
701 		n = m;
702 	}
703 
704 	return 0;
705 }
706 
707 /**
708  * xbc_destroy_all() - Clean up all parsed bootconfig
709  *
710  * This clears all data structures of parsed bootconfig on memory.
711  * If you need to reuse xbc_init() with new boot config, you can
712  * use this.
713  */
714 void __init xbc_destroy_all(void)
715 {
716 	xbc_data = NULL;
717 	xbc_data_size = 0;
718 	xbc_node_num = 0;
719 	memset(xbc_nodes, 0, sizeof(xbc_nodes));
720 }
721 
722 /**
723  * xbc_init() - Parse given XBC file and build XBC internal tree
724  * @buf: boot config text
725  *
726  * This parses the boot config text in @buf. @buf must be a
727  * null terminated string and smaller than XBC_DATA_MAX.
728  * Return 0 if succeeded, or -errno if there is any error.
729  */
730 int __init xbc_init(char *buf)
731 {
732 	char *p, *q;
733 	int ret, c;
734 
735 	if (xbc_data)
736 		return -EBUSY;
737 
738 	ret = strlen(buf);
739 	if (ret > XBC_DATA_MAX - 1 || ret == 0)
740 		return -ERANGE;
741 
742 	xbc_data = buf;
743 	xbc_data_size = ret + 1;
744 	last_parent = NULL;
745 
746 	p = buf;
747 	do {
748 		q = strpbrk(p, "{}=;\n#");
749 		if (!q) {
750 			p = skip_spaces(p);
751 			if (*p != '\0')
752 				ret = xbc_parse_error("No delimiter", p);
753 			break;
754 		}
755 
756 		c = *q;
757 		*q++ = '\0';
758 		switch (c) {
759 		case '=':
760 			ret = xbc_parse_kv(&p, q);
761 			break;
762 		case '{':
763 			ret = xbc_open_brace(&p, q);
764 			break;
765 		case '#':
766 			q = skip_comment(q);
767 			/* fall through */
768 		case ';':
769 		case '\n':
770 			ret = xbc_parse_key(&p, q);
771 			break;
772 		case '}':
773 			ret = xbc_close_brace(&p, q);
774 			break;
775 		}
776 	} while (!ret);
777 
778 	if (!ret)
779 		ret = xbc_verify_tree();
780 
781 	if (ret < 0)
782 		xbc_destroy_all();
783 
784 	return ret;
785 }
786 
787 /**
788  * xbc_debug_dump() - Dump current XBC node list
789  *
790  * Dump the current XBC node list on printk buffer for debug.
791  */
792 void __init xbc_debug_dump(void)
793 {
794 	int i;
795 
796 	for (i = 0; i < xbc_node_num; i++) {
797 		pr_debug("[%d] %s (%s) .next=%d, .child=%d .parent=%d\n", i,
798 			xbc_node_get_data(xbc_nodes + i),
799 			xbc_node_is_value(xbc_nodes + i) ? "value" : "key",
800 			xbc_nodes[i].next, xbc_nodes[i].child,
801 			xbc_nodes[i].parent);
802 	}
803 }
804