xref: /openbmc/linux/lib/bootconfig.c (revision dc6a81c3)
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 	} else
377 		xbc_parse_error("Too many nodes", data);
378 
379 	return node;
380 }
381 
382 static inline __init struct xbc_node *xbc_add_child(char *data, u32 flag)
383 {
384 	struct xbc_node *node = xbc_add_sibling(data, flag);
385 
386 	if (node)
387 		last_parent = node;
388 
389 	return node;
390 }
391 
392 static inline __init bool xbc_valid_keyword(char *key)
393 {
394 	if (key[0] == '\0')
395 		return false;
396 
397 	while (isalnum(*key) || *key == '-' || *key == '_')
398 		key++;
399 
400 	return *key == '\0';
401 }
402 
403 static char *skip_comment(char *p)
404 {
405 	char *ret;
406 
407 	ret = strchr(p, '\n');
408 	if (!ret)
409 		ret = p + strlen(p);
410 	else
411 		ret++;
412 
413 	return ret;
414 }
415 
416 static char *skip_spaces_until_newline(char *p)
417 {
418 	while (isspace(*p) && *p != '\n')
419 		p++;
420 	return p;
421 }
422 
423 static int __init __xbc_open_brace(void)
424 {
425 	/* Mark the last key as open brace */
426 	last_parent->next = XBC_NODE_MAX;
427 
428 	return 0;
429 }
430 
431 static int __init __xbc_close_brace(char *p)
432 {
433 	struct xbc_node *node;
434 
435 	if (!last_parent || last_parent->next != XBC_NODE_MAX)
436 		return xbc_parse_error("Unexpected closing brace", p);
437 
438 	node = last_parent;
439 	node->next = 0;
440 	do {
441 		node = xbc_node_get_parent(node);
442 	} while (node && node->next != XBC_NODE_MAX);
443 	last_parent = node;
444 
445 	return 0;
446 }
447 
448 /*
449  * Return delimiter or error, no node added. As same as lib/cmdline.c,
450  * you can use " around spaces, but can't escape " for value.
451  */
452 static int __init __xbc_parse_value(char **__v, char **__n)
453 {
454 	char *p, *v = *__v;
455 	int c, quotes = 0;
456 
457 	v = skip_spaces(v);
458 	while (*v == '#') {
459 		v = skip_comment(v);
460 		v = skip_spaces(v);
461 	}
462 	if (*v == '"' || *v == '\'') {
463 		quotes = *v;
464 		v++;
465 	}
466 	p = v - 1;
467 	while ((c = *++p)) {
468 		if (!isprint(c) && !isspace(c))
469 			return xbc_parse_error("Non printable value", p);
470 		if (quotes) {
471 			if (c != quotes)
472 				continue;
473 			quotes = 0;
474 			*p++ = '\0';
475 			p = skip_spaces_until_newline(p);
476 			c = *p;
477 			if (c && !strchr(",;\n#}", c))
478 				return xbc_parse_error("No value delimiter", p);
479 			if (*p)
480 				p++;
481 			break;
482 		}
483 		if (strchr(",;\n#}", c)) {
484 			v = strim(v);
485 			*p++ = '\0';
486 			break;
487 		}
488 	}
489 	if (quotes)
490 		return xbc_parse_error("No closing quotes", p);
491 	if (c == '#') {
492 		p = skip_comment(p);
493 		c = '\n';	/* A comment must be treated as a newline */
494 	}
495 	*__n = p;
496 	*__v = v;
497 
498 	return c;
499 }
500 
501 static int __init xbc_parse_array(char **__v)
502 {
503 	struct xbc_node *node;
504 	char *next;
505 	int c = 0;
506 
507 	do {
508 		c = __xbc_parse_value(__v, &next);
509 		if (c < 0)
510 			return c;
511 
512 		node = xbc_add_sibling(*__v, XBC_VALUE);
513 		if (!node)
514 			return -ENOMEM;
515 		*__v = next;
516 	} while (c == ',');
517 	node->next = 0;
518 
519 	return c;
520 }
521 
522 static inline __init
523 struct xbc_node *find_match_node(struct xbc_node *node, char *k)
524 {
525 	while (node) {
526 		if (!strcmp(xbc_node_get_data(node), k))
527 			break;
528 		node = xbc_node_get_next(node);
529 	}
530 	return node;
531 }
532 
533 static int __init __xbc_add_key(char *k)
534 {
535 	struct xbc_node *node;
536 
537 	if (!xbc_valid_keyword(k))
538 		return xbc_parse_error("Invalid keyword", k);
539 
540 	if (unlikely(xbc_node_num == 0))
541 		goto add_node;
542 
543 	if (!last_parent)	/* the first level */
544 		node = find_match_node(xbc_nodes, k);
545 	else
546 		node = find_match_node(xbc_node_get_child(last_parent), k);
547 
548 	if (node)
549 		last_parent = node;
550 	else {
551 add_node:
552 		node = xbc_add_child(k, XBC_KEY);
553 		if (!node)
554 			return -ENOMEM;
555 	}
556 	return 0;
557 }
558 
559 static int __init __xbc_parse_keys(char *k)
560 {
561 	char *p;
562 	int ret;
563 
564 	k = strim(k);
565 	while ((p = strchr(k, '.'))) {
566 		*p++ = '\0';
567 		ret = __xbc_add_key(k);
568 		if (ret)
569 			return ret;
570 		k = p;
571 	}
572 
573 	return __xbc_add_key(k);
574 }
575 
576 static int __init xbc_parse_kv(char **k, char *v)
577 {
578 	struct xbc_node *prev_parent = last_parent;
579 	struct xbc_node *node;
580 	char *next;
581 	int c, ret;
582 
583 	ret = __xbc_parse_keys(*k);
584 	if (ret)
585 		return ret;
586 
587 	c = __xbc_parse_value(&v, &next);
588 	if (c < 0)
589 		return c;
590 
591 	node = xbc_add_sibling(v, XBC_VALUE);
592 	if (!node)
593 		return -ENOMEM;
594 
595 	if (c == ',') {	/* Array */
596 		c = xbc_parse_array(&next);
597 		if (c < 0)
598 			return c;
599 	}
600 
601 	last_parent = prev_parent;
602 
603 	if (c == '}') {
604 		ret = __xbc_close_brace(next - 1);
605 		if (ret < 0)
606 			return ret;
607 	}
608 
609 	*k = next;
610 
611 	return 0;
612 }
613 
614 static int __init xbc_parse_key(char **k, char *n)
615 {
616 	struct xbc_node *prev_parent = last_parent;
617 	int ret;
618 
619 	*k = strim(*k);
620 	if (**k != '\0') {
621 		ret = __xbc_parse_keys(*k);
622 		if (ret)
623 			return ret;
624 		last_parent = prev_parent;
625 	}
626 	*k = n;
627 
628 	return 0;
629 }
630 
631 static int __init xbc_open_brace(char **k, char *n)
632 {
633 	int ret;
634 
635 	ret = __xbc_parse_keys(*k);
636 	if (ret)
637 		return ret;
638 	*k = n;
639 
640 	return __xbc_open_brace();
641 }
642 
643 static int __init xbc_close_brace(char **k, char *n)
644 {
645 	int ret;
646 
647 	ret = xbc_parse_key(k, n);
648 	if (ret)
649 		return ret;
650 	/* k is updated in xbc_parse_key() */
651 
652 	return __xbc_close_brace(n - 1);
653 }
654 
655 static int __init xbc_verify_tree(void)
656 {
657 	int i, depth, len, wlen;
658 	struct xbc_node *n, *m;
659 
660 	/* Empty tree */
661 	if (xbc_node_num == 0) {
662 		xbc_parse_error("Empty config", xbc_data);
663 		return -ENOENT;
664 	}
665 
666 	for (i = 0; i < xbc_node_num; i++) {
667 		if (xbc_nodes[i].next > xbc_node_num) {
668 			return xbc_parse_error("No closing brace",
669 				xbc_node_get_data(xbc_nodes + i));
670 		}
671 	}
672 
673 	/* Key tree limitation check */
674 	n = &xbc_nodes[0];
675 	depth = 1;
676 	len = 0;
677 
678 	while (n) {
679 		wlen = strlen(xbc_node_get_data(n)) + 1;
680 		len += wlen;
681 		if (len > XBC_KEYLEN_MAX)
682 			return xbc_parse_error("Too long key length",
683 				xbc_node_get_data(n));
684 
685 		m = xbc_node_get_child(n);
686 		if (m && xbc_node_is_key(m)) {
687 			n = m;
688 			depth++;
689 			if (depth > XBC_DEPTH_MAX)
690 				return xbc_parse_error("Too many key words",
691 						xbc_node_get_data(n));
692 			continue;
693 		}
694 		len -= wlen;
695 		m = xbc_node_get_next(n);
696 		while (!m) {
697 			n = xbc_node_get_parent(n);
698 			if (!n)
699 				break;
700 			len -= strlen(xbc_node_get_data(n)) + 1;
701 			depth--;
702 			m = xbc_node_get_next(n);
703 		}
704 		n = m;
705 	}
706 
707 	return 0;
708 }
709 
710 /**
711  * xbc_destroy_all() - Clean up all parsed bootconfig
712  *
713  * This clears all data structures of parsed bootconfig on memory.
714  * If you need to reuse xbc_init() with new boot config, you can
715  * use this.
716  */
717 void __init xbc_destroy_all(void)
718 {
719 	xbc_data = NULL;
720 	xbc_data_size = 0;
721 	xbc_node_num = 0;
722 	memset(xbc_nodes, 0, sizeof(xbc_nodes));
723 }
724 
725 /**
726  * xbc_init() - Parse given XBC file and build XBC internal tree
727  * @buf: boot config text
728  *
729  * This parses the boot config text in @buf. @buf must be a
730  * null terminated string and smaller than XBC_DATA_MAX.
731  * Return the number of stored nodes (>0) if succeeded, or -errno
732  * if there is any error.
733  */
734 int __init xbc_init(char *buf)
735 {
736 	char *p, *q;
737 	int ret, c;
738 
739 	if (xbc_data) {
740 		pr_err("Error: bootconfig is already initialized.\n");
741 		return -EBUSY;
742 	}
743 
744 	ret = strlen(buf);
745 	if (ret > XBC_DATA_MAX - 1 || ret == 0) {
746 		pr_err("Error: Config data is %s.\n",
747 			ret ? "too big" : "empty");
748 		return -ERANGE;
749 	}
750 
751 	xbc_data = buf;
752 	xbc_data_size = ret + 1;
753 	last_parent = NULL;
754 
755 	p = buf;
756 	do {
757 		q = strpbrk(p, "{}=;\n#");
758 		if (!q) {
759 			p = skip_spaces(p);
760 			if (*p != '\0')
761 				ret = xbc_parse_error("No delimiter", p);
762 			break;
763 		}
764 
765 		c = *q;
766 		*q++ = '\0';
767 		switch (c) {
768 		case '=':
769 			ret = xbc_parse_kv(&p, q);
770 			break;
771 		case '{':
772 			ret = xbc_open_brace(&p, q);
773 			break;
774 		case '#':
775 			q = skip_comment(q);
776 			/* fall through */
777 		case ';':
778 		case '\n':
779 			ret = xbc_parse_key(&p, q);
780 			break;
781 		case '}':
782 			ret = xbc_close_brace(&p, q);
783 			break;
784 		}
785 	} while (!ret);
786 
787 	if (!ret)
788 		ret = xbc_verify_tree();
789 
790 	if (ret < 0)
791 		xbc_destroy_all();
792 	else
793 		ret = xbc_node_num;
794 
795 	return ret;
796 }
797 
798 /**
799  * xbc_debug_dump() - Dump current XBC node list
800  *
801  * Dump the current XBC node list on printk buffer for debug.
802  */
803 void __init xbc_debug_dump(void)
804 {
805 	int i;
806 
807 	for (i = 0; i < xbc_node_num; i++) {
808 		pr_debug("[%d] %s (%s) .next=%d, .child=%d .parent=%d\n", i,
809 			xbc_node_get_data(xbc_nodes + i),
810 			xbc_node_is_value(xbc_nodes + i) ? "value" : "key",
811 			xbc_nodes[i].next, xbc_nodes[i].child,
812 			xbc_nodes[i].parent);
813 	}
814 }
815