xref: /linux/lib/bootconfig.c (revision 9055c64567e9fc2a58d9382205bf3082f7bea141)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Extra Boot Config
4  * Masami Hiramatsu <mhiramat@kernel.org>
5  */
6 
7 /*
8  * NOTE: This is only for tools/bootconfig, because tools/bootconfig will
9  * run the parser sanity test.
10  * This does NOT mean lib/bootconfig.c is available in the user space.
11  * However, if you change this file, please make sure the tools/bootconfig
12  * has no issue on building and running.
13  */
14 #include <linux/bootconfig.h>
15 
16 #ifdef __KERNEL__
17 #include <linux/bug.h>
18 #include <linux/ctype.h>
19 #include <linux/errno.h>
20 #include <linux/cache.h>
21 #include <linux/compiler.h>
22 #include <linux/sprintf.h>
23 #include <linux/memblock.h>
24 #include <linux/string.h>
25 
26 #ifdef CONFIG_BOOT_CONFIG_EMBED
27 /* embedded_bootconfig_data is defined in bootconfig-data.S */
28 extern __visible const char embedded_bootconfig_data[];
29 extern __visible const char embedded_bootconfig_data_end[];
30 
31 const char * __init xbc_get_embedded_bootconfig(size_t *size)
32 {
33 	*size = embedded_bootconfig_data_end - embedded_bootconfig_data;
34 	return (*size) ? embedded_bootconfig_data : NULL;
35 }
36 #endif
37 #endif
38 
39 /*
40  * Extra Boot Config (XBC) is given as tree-structured ascii text of
41  * key-value pairs on memory.
42  * xbc_parse() parses the text to build a simple tree. Each tree node is
43  * simply a key word or a value. A key node may have a next key node or/and
44  * a child node (both key and value). A value node may have a next value
45  * node (for array).
46  */
47 
48 static struct xbc_node *xbc_nodes __initdata;
49 static int xbc_node_num __initdata;
50 static char *xbc_data __initdata;
51 static size_t xbc_data_size __initdata;
52 static struct xbc_node *last_parent __initdata;
53 static const char *xbc_err_msg __initdata;
54 static int xbc_err_pos __initdata;
55 static int open_brace[XBC_DEPTH_MAX] __initdata;
56 static int brace_index __initdata;
57 
58 #ifdef __KERNEL__
59 static inline void * __init xbc_alloc_mem(size_t size)
60 {
61 	return memblock_alloc(size, SMP_CACHE_BYTES);
62 }
63 
64 static inline void __init xbc_free_mem(void *addr, size_t size, bool early)
65 {
66 	if (early)
67 		memblock_free(addr, size);
68 	else if (addr)
69 		memblock_free(addr, size);
70 }
71 
72 #else /* !__KERNEL__ */
73 
74 static inline void *xbc_alloc_mem(size_t size)
75 {
76 	return calloc(1, size);
77 }
78 
79 static inline void xbc_free_mem(void *addr, size_t size, bool early)
80 {
81 	free(addr);
82 }
83 #endif
84 
85 /**
86  * xbc_get_info() - Get the information of loaded boot config
87  * @node_size: A pointer to store the number of nodes.
88  * @data_size: A pointer to store the size of bootconfig data.
89  *
90  * Get the number of used nodes in @node_size if it is not NULL,
91  * and the size of bootconfig data in @data_size if it is not NULL.
92  * Return 0 if the boot config is initialized, or return -ENODEV.
93  */
94 int __init xbc_get_info(int *node_size, size_t *data_size)
95 {
96 	if (!xbc_data)
97 		return -ENODEV;
98 
99 	if (node_size)
100 		*node_size = xbc_node_num;
101 	if (data_size)
102 		*data_size = xbc_data_size;
103 	return 0;
104 }
105 
106 static int __init xbc_parse_error(const char *msg, const char *p)
107 {
108 	xbc_err_msg = msg;
109 	xbc_err_pos = (int)(p - xbc_data);
110 
111 	return -EINVAL;
112 }
113 
114 /**
115  * xbc_root_node() - Get the root node of extended boot config
116  *
117  * Return the address of root node of extended boot config. If the
118  * extended boot config is not initialized, return NULL.
119  */
120 struct xbc_node * __init xbc_root_node(void)
121 {
122 	if (unlikely(!xbc_data))
123 		return NULL;
124 
125 	return xbc_nodes;
126 }
127 
128 /**
129  * xbc_node_index() - Get the index of XBC node
130  * @node: A target node of getting index.
131  *
132  * Return the index number of @node in XBC node list.
133  */
134 uint16_t __init xbc_node_index(struct xbc_node *node)
135 {
136 	return (uint16_t)(node - &xbc_nodes[0]);
137 }
138 
139 /**
140  * xbc_node_get_parent() - Get the parent XBC node
141  * @node: An XBC node.
142  *
143  * Return the parent node of @node. If the node is top node of the tree,
144  * return NULL.
145  */
146 struct xbc_node * __init xbc_node_get_parent(struct xbc_node *node)
147 {
148 	return node->parent == XBC_NODE_MAX ? NULL : &xbc_nodes[node->parent];
149 }
150 
151 /**
152  * xbc_node_get_child() - Get the child XBC node
153  * @node: An XBC node.
154  *
155  * Return the first child node of @node. If the node has no child, return
156  * NULL.
157  */
158 struct xbc_node * __init xbc_node_get_child(struct xbc_node *node)
159 {
160 	return node->child ? &xbc_nodes[node->child] : NULL;
161 }
162 
163 /**
164  * xbc_node_get_next() - Get the next sibling XBC node
165  * @node: An XBC node.
166  *
167  * Return the NEXT sibling node of @node. If the node has no next sibling,
168  * return NULL. Note that even if this returns NULL, it doesn't mean @node
169  * has no siblings. (You also has to check whether the parent's child node
170  * is @node or not.)
171  */
172 struct xbc_node * __init xbc_node_get_next(struct xbc_node *node)
173 {
174 	return node->next ? &xbc_nodes[node->next] : NULL;
175 }
176 
177 /**
178  * xbc_node_get_data() - Get the data of XBC node
179  * @node: An XBC node.
180  *
181  * Return the data (which is always a null terminated string) of @node.
182  * If the node has invalid data, warn and return NULL.
183  */
184 const char * __init xbc_node_get_data(struct xbc_node *node)
185 {
186 	size_t offset = node->data & ~XBC_VALUE;
187 
188 	if (WARN_ON(offset >= xbc_data_size))
189 		return NULL;
190 
191 	return xbc_data + offset;
192 }
193 
194 static bool __init
195 xbc_node_match_prefix(struct xbc_node *node, const char **prefix)
196 {
197 	const char *p = xbc_node_get_data(node);
198 	size_t len = strlen(p);
199 
200 	if (strncmp(*prefix, p, len))
201 		return false;
202 
203 	p = *prefix + len;
204 	if (*p == '.')
205 		p++;
206 	else if (*p != '\0')
207 		return false;
208 	*prefix = p;
209 
210 	return true;
211 }
212 
213 /**
214  * xbc_node_find_subkey() - Find a subkey node which matches given key
215  * @parent: An XBC node.
216  * @key: A key string.
217  *
218  * Search a key node under @parent which matches @key. The @key can contain
219  * several words jointed with '.'. If @parent is NULL, this searches the
220  * node from whole tree. Return NULL if no node is matched.
221  */
222 struct xbc_node * __init
223 xbc_node_find_subkey(struct xbc_node *parent, const char *key)
224 {
225 	struct xbc_node *node;
226 
227 	if (parent)
228 		node = xbc_node_get_subkey(parent);
229 	else
230 		node = xbc_root_node();
231 
232 	while (node && xbc_node_is_key(node)) {
233 		if (!xbc_node_match_prefix(node, &key))
234 			node = xbc_node_get_next(node);
235 		else if (*key != '\0')
236 			node = xbc_node_get_subkey(node);
237 		else
238 			break;
239 	}
240 
241 	return node;
242 }
243 
244 /**
245  * xbc_node_find_value() - Find a value node which matches given key
246  * @parent: An XBC node.
247  * @key: A key string.
248  * @vnode: A container pointer of found XBC node.
249  *
250  * Search a value node under @parent whose (parent) key node matches @key,
251  * store it in *@vnode, and returns the value string.
252  * The @key can contain several words jointed with '.'. If @parent is NULL,
253  * this searches the node from whole tree. Return the value string if a
254  * matched key found, return NULL if no node is matched.
255  * Note that this returns 0-length string and stores NULL in *@vnode if the
256  * key has no value. And also it will return the value of the first entry if
257  * the value is an array.
258  */
259 const char * __init
260 xbc_node_find_value(struct xbc_node *parent, const char *key,
261 		    struct xbc_node **vnode)
262 {
263 	struct xbc_node *node = xbc_node_find_subkey(parent, key);
264 
265 	if (!node || !xbc_node_is_key(node))
266 		return NULL;
267 
268 	node = xbc_node_get_child(node);
269 	if (node && !xbc_node_is_value(node))
270 		return NULL;
271 
272 	if (vnode)
273 		*vnode = node;
274 
275 	return node ? xbc_node_get_data(node) : "";
276 }
277 
278 /**
279  * xbc_node_compose_key_after() - Compose partial key string of the XBC node
280  * @root: Root XBC node
281  * @node: Target XBC node.
282  * @buf: A buffer to store the key.
283  * @size: The size of the @buf.
284  *
285  * Compose the partial key of the @node into @buf, which is starting right
286  * after @root (@root is not included.) If @root is NULL, this returns full
287  * key words of @node.
288  * Returns the total length of the key stored in @buf. Returns -EINVAL
289  * if @node is NULL or @root is not the ancestor of @node or @root is @node,
290  * or returns -ERANGE if the key depth is deeper than max depth.
291  * This is expected to be used with xbc_find_node() to list up all (child)
292  * keys under given key.
293  */
294 int __init xbc_node_compose_key_after(struct xbc_node *root,
295 				      struct xbc_node *node,
296 				      char *buf, size_t size)
297 {
298 	uint16_t keys[XBC_DEPTH_MAX];
299 	int depth = 0, ret = 0, total = 0;
300 
301 	if (!node || node == root)
302 		return -EINVAL;
303 
304 	if (xbc_node_is_value(node))
305 		node = xbc_node_get_parent(node);
306 
307 	while (node && node != root) {
308 		keys[depth++] = xbc_node_index(node);
309 		if (depth == XBC_DEPTH_MAX)
310 			return -ERANGE;
311 		node = xbc_node_get_parent(node);
312 	}
313 	if (!node && root)
314 		return -EINVAL;
315 
316 	while (--depth >= 0) {
317 		node = xbc_nodes + keys[depth];
318 		ret = snprintf(buf, size, "%s%s", xbc_node_get_data(node),
319 			       depth ? "." : "");
320 		if (ret < 0)
321 			return ret;
322 		if (ret >= size) {
323 			size = 0;
324 		} else {
325 			size -= ret;
326 			buf += ret;
327 		}
328 		total += ret;
329 	}
330 
331 	return total;
332 }
333 
334 /**
335  * xbc_node_find_next_leaf() - Find the next leaf node under given node
336  * @root: An XBC root node
337  * @node: An XBC node which starts from.
338  *
339  * Search the next leaf node (which means the terminal key node) of @node
340  * under @root node (including @root node itself).
341  * Return the next node or NULL if next leaf node is not found.
342  */
343 struct xbc_node * __init xbc_node_find_next_leaf(struct xbc_node *root,
344 						 struct xbc_node *node)
345 {
346 	struct xbc_node *next;
347 
348 	if (unlikely(!xbc_data))
349 		return NULL;
350 
351 	if (!node) {	/* First try */
352 		node = root;
353 		if (!node)
354 			node = xbc_nodes;
355 	} else {
356 		/* Leaf node may have a subkey */
357 		next = xbc_node_get_subkey(node);
358 		if (next) {
359 			node = next;
360 			goto found;
361 		}
362 
363 		if (node == root)	/* @root was a leaf, no child node. */
364 			return NULL;
365 
366 		while (!node->next) {
367 			node = xbc_node_get_parent(node);
368 			if (node == root)
369 				return NULL;
370 			/* User passed a node which is not under parent */
371 			if (WARN_ON(!node))
372 				return NULL;
373 		}
374 		node = xbc_node_get_next(node);
375 	}
376 
377 found:
378 	while (node && !xbc_node_is_leaf(node))
379 		node = xbc_node_get_child(node);
380 
381 	return node;
382 }
383 
384 /**
385  * xbc_node_find_next_key_value() - Find the next key-value pair nodes
386  * @root: An XBC root node
387  * @leaf: A container pointer of XBC node which starts from.
388  *
389  * Search the next leaf node (which means the terminal key node) of *@leaf
390  * under @root node. Returns the value and update *@leaf if next leaf node
391  * is found, or NULL if no next leaf node is found.
392  * Note that this returns 0-length string if the key has no value, or
393  * the value of the first entry if the value is an array.
394  */
395 const char * __init xbc_node_find_next_key_value(struct xbc_node *root,
396 						 struct xbc_node **leaf)
397 {
398 	/* tip must be passed */
399 	if (WARN_ON(!leaf))
400 		return NULL;
401 
402 	*leaf = xbc_node_find_next_leaf(root, *leaf);
403 	if (!*leaf)
404 		return NULL;
405 	if ((*leaf)->child)
406 		return xbc_node_get_data(xbc_node_get_child(*leaf));
407 	else
408 		return "";	/* No value key */
409 }
410 
411 /* XBC parse and tree build */
412 
413 static int __init xbc_init_node(struct xbc_node *node, char *data, uint16_t flag)
414 {
415 	long offset = data - xbc_data;
416 
417 	if (WARN_ON(offset < 0 || offset >= XBC_DATA_MAX))
418 		return -EINVAL;
419 
420 	node->data = (uint16_t)offset | flag;
421 	node->child = 0;
422 	node->next = 0;
423 
424 	return 0;
425 }
426 
427 static struct xbc_node * __init xbc_add_node(char *data, uint16_t flag)
428 {
429 	struct xbc_node *node;
430 
431 	if (xbc_node_num == XBC_NODE_MAX)
432 		return NULL;
433 
434 	node = &xbc_nodes[xbc_node_num];
435 	if (xbc_init_node(node, data, flag) < 0)
436 		return NULL;
437 	xbc_node_num++;
438 
439 	return node;
440 }
441 
442 static inline __init struct xbc_node *xbc_last_sibling(struct xbc_node *node)
443 {
444 	while (node->next)
445 		node = xbc_node_get_next(node);
446 
447 	return node;
448 }
449 
450 static inline __init struct xbc_node *xbc_last_child(struct xbc_node *node)
451 {
452 	while (node->child)
453 		node = xbc_node_get_child(node);
454 
455 	return node;
456 }
457 
458 static struct xbc_node * __init __xbc_add_sibling(char *data, uint16_t flag, bool head)
459 {
460 	struct xbc_node *sib, *node = xbc_add_node(data, flag);
461 
462 	if (node) {
463 		if (!last_parent) {
464 			/* Ignore @head in this case */
465 			node->parent = XBC_NODE_MAX;
466 			sib = xbc_last_sibling(xbc_nodes);
467 			sib->next = xbc_node_index(node);
468 		} else {
469 			node->parent = xbc_node_index(last_parent);
470 			if (!last_parent->child || head) {
471 				node->next = last_parent->child;
472 				last_parent->child = xbc_node_index(node);
473 			} else {
474 				sib = xbc_node_get_child(last_parent);
475 				sib = xbc_last_sibling(sib);
476 				sib->next = xbc_node_index(node);
477 			}
478 		}
479 	} else {
480 		xbc_parse_error("Too many nodes", data);
481 	}
482 
483 	return node;
484 }
485 
486 static inline struct xbc_node * __init xbc_add_sibling(char *data, uint16_t flag)
487 {
488 	return __xbc_add_sibling(data, flag, false);
489 }
490 
491 static inline struct xbc_node * __init xbc_add_head_sibling(char *data, uint16_t flag)
492 {
493 	return __xbc_add_sibling(data, flag, true);
494 }
495 
496 static inline __init struct xbc_node *xbc_add_child(char *data, uint16_t flag)
497 {
498 	struct xbc_node *node = xbc_add_sibling(data, flag);
499 
500 	if (node)
501 		last_parent = node;
502 
503 	return node;
504 }
505 
506 static inline __init bool xbc_valid_keyword(char *key)
507 {
508 	if (key[0] == '\0')
509 		return false;
510 
511 	while (isalnum(*key) || *key == '-' || *key == '_')
512 		key++;
513 
514 	return *key == '\0';
515 }
516 
517 static char *skip_comment(char *p)
518 {
519 	char *ret;
520 
521 	ret = strchr(p, '\n');
522 	if (!ret)
523 		ret = p + strlen(p);
524 	else
525 		ret++;
526 
527 	return ret;
528 }
529 
530 static char *skip_spaces_until_newline(char *p)
531 {
532 	while (isspace(*p) && *p != '\n')
533 		p++;
534 	return p;
535 }
536 
537 static int __init __xbc_open_brace(char *p)
538 {
539 	/* Push the last key as open brace */
540 	if (brace_index >= XBC_DEPTH_MAX)
541 		return xbc_parse_error("Exceed max depth of braces", p);
542 	open_brace[brace_index++] = xbc_node_index(last_parent);
543 
544 	return 0;
545 }
546 
547 static int __init __xbc_close_brace(char *p)
548 {
549 	brace_index--;
550 	if (!last_parent || brace_index < 0 ||
551 	    (open_brace[brace_index] != xbc_node_index(last_parent)))
552 		return xbc_parse_error("Unexpected closing brace", p);
553 
554 	if (brace_index == 0)
555 		last_parent = NULL;
556 	else
557 		last_parent = &xbc_nodes[open_brace[brace_index - 1]];
558 
559 	return 0;
560 }
561 
562 /*
563  * Return delimiter or error, no node added. As same as lib/cmdline.c,
564  * you can use " around spaces, but can't escape " for value.
565  * *@__v must point real value string. (not including spaces before value.)
566  */
567 static int __init __xbc_parse_value(char **__v, char **__n)
568 {
569 	char *p, *v = *__v;
570 	int c, quotes = 0;
571 
572 	if (*v == '"' || *v == '\'') {
573 		quotes = *v;
574 		v++;
575 	}
576 	p = v - 1;
577 	while ((c = *++p)) {
578 		if (!isprint(c) && !isspace(c))
579 			return xbc_parse_error("Non printable value", p);
580 		if (quotes) {
581 			if (c != quotes)
582 				continue;
583 			quotes = 0;
584 			*p++ = '\0';
585 			p = skip_spaces_until_newline(p);
586 			c = *p;
587 			if (c && !strchr(",;\n#}", c))
588 				return xbc_parse_error("No value delimiter", p);
589 			if (*p)
590 				p++;
591 			break;
592 		}
593 		if (strchr(",;\n#}", c)) {
594 			*p++ = '\0';
595 			v = strim(v);
596 			break;
597 		}
598 	}
599 	if (quotes)
600 		return xbc_parse_error("No closing quotes", p);
601 	if (c == '#') {
602 		p = skip_comment(p);
603 		c = '\n';	/* A comment must be treated as a newline */
604 	}
605 	*__n = p;
606 	*__v = v;
607 
608 	return c;
609 }
610 
611 static int __init xbc_parse_array(char **__v)
612 {
613 	struct xbc_node *node;
614 	char *next;
615 	int c = 0;
616 
617 	if (last_parent->child)
618 		last_parent = xbc_node_get_child(last_parent);
619 
620 	do {
621 		/* Search the next array value beyond comments and empty lines */
622 		next = skip_spaces(*__v);
623 		while (*next == '#') {
624 			next = skip_comment(next);
625 			next = skip_spaces(next);
626 		}
627 		*__v = next;
628 		c = __xbc_parse_value(__v, &next);
629 		if (c < 0)
630 			return c;
631 
632 		node = xbc_add_child(*__v, XBC_VALUE);
633 		if (!node)
634 			return -ENOMEM;
635 		*__v = next;
636 	} while (c == ',');
637 	node->child = 0;
638 
639 	return c;
640 }
641 
642 static inline __init
643 struct xbc_node *find_match_node(struct xbc_node *node, char *k)
644 {
645 	while (node) {
646 		if (!strcmp(xbc_node_get_data(node), k))
647 			break;
648 		node = xbc_node_get_next(node);
649 	}
650 	return node;
651 }
652 
653 static int __init __xbc_add_key(char *k)
654 {
655 	struct xbc_node *node, *child;
656 
657 	if (!xbc_valid_keyword(k))
658 		return xbc_parse_error("Invalid keyword", k);
659 
660 	if (unlikely(xbc_node_num == 0))
661 		goto add_node;
662 
663 	if (!last_parent) {	/* the first level */
664 		node = find_match_node(xbc_nodes, k);
665 	} else {
666 		child = xbc_node_get_child(last_parent);
667 		/* Since the value node is the first child, skip it. */
668 		if (child && xbc_node_is_value(child))
669 			child = xbc_node_get_next(child);
670 		node = find_match_node(child, k);
671 	}
672 
673 	if (node) {
674 		last_parent = node;
675 	} else {
676 add_node:
677 		node = xbc_add_child(k, XBC_KEY);
678 		if (!node)
679 			return -ENOMEM;
680 	}
681 	return 0;
682 }
683 
684 static int __init __xbc_parse_keys(char *k)
685 {
686 	char *p;
687 	int ret;
688 
689 	k = strim(k);
690 	while ((p = strchr(k, '.'))) {
691 		*p++ = '\0';
692 		ret = __xbc_add_key(k);
693 		if (ret)
694 			return ret;
695 		k = p;
696 	}
697 
698 	return __xbc_add_key(k);
699 }
700 
701 static int __init xbc_parse_kv(char **k, char *v, int op)
702 {
703 	struct xbc_node *prev_parent = last_parent;
704 	struct xbc_node *child;
705 	char *next;
706 	int c, ret;
707 
708 	ret = __xbc_parse_keys(*k);
709 	if (ret)
710 		return ret;
711 
712 	v = skip_spaces_until_newline(v);
713 	/* If there is a comment, this has an empty value. */
714 	if (*v == '#') {
715 		next = skip_comment(v);
716 		*v = '\0';
717 		c = '\n';
718 	} else {
719 		c = __xbc_parse_value(&v, &next);
720 		if (c < 0)
721 			return c;
722 	}
723 
724 	child = xbc_node_get_child(last_parent);
725 	if (child && xbc_node_is_value(child)) {
726 		if (op == '=')
727 			return xbc_parse_error("Value is redefined", v);
728 		if (op == ':') {
729 			unsigned short nidx = child->next;
730 
731 			if (xbc_init_node(child, v, XBC_VALUE) < 0)
732 				return xbc_parse_error("Failed to override value", v);
733 			child->next = nidx;	/* keep subkeys */
734 			goto array;
735 		}
736 		/* op must be '+' */
737 		last_parent = xbc_last_child(child);
738 	}
739 	/* The value node should always be the first child */
740 	if (!xbc_add_head_sibling(v, XBC_VALUE))
741 		return -ENOMEM;
742 
743 array:
744 	if (c == ',') {	/* Array */
745 		c = xbc_parse_array(&next);
746 		if (c < 0)
747 			return c;
748 	}
749 
750 	last_parent = prev_parent;
751 
752 	if (c == '}') {
753 		ret = __xbc_close_brace(next - 1);
754 		if (ret < 0)
755 			return ret;
756 	}
757 
758 	*k = next;
759 
760 	return 0;
761 }
762 
763 static int __init xbc_parse_key(char **k, char *n)
764 {
765 	struct xbc_node *prev_parent = last_parent;
766 	int ret;
767 
768 	*k = strim(*k);
769 	if (**k != '\0') {
770 		ret = __xbc_parse_keys(*k);
771 		if (ret)
772 			return ret;
773 		last_parent = prev_parent;
774 	}
775 	*k = n;
776 
777 	return 0;
778 }
779 
780 static int __init xbc_open_brace(char **k, char *n)
781 {
782 	int ret;
783 
784 	ret = __xbc_parse_keys(*k);
785 	if (ret)
786 		return ret;
787 	*k = n;
788 
789 	return __xbc_open_brace(n - 1);
790 }
791 
792 static int __init xbc_close_brace(char **k, char *n)
793 {
794 	int ret;
795 
796 	ret = xbc_parse_key(k, n);
797 	if (ret)
798 		return ret;
799 	/* k is updated in xbc_parse_key() */
800 
801 	return __xbc_close_brace(n - 1);
802 }
803 
804 static int __init xbc_verify_tree(void)
805 {
806 	int i, depth;
807 	size_t len, wlen;
808 	struct xbc_node *n, *m;
809 
810 	/* Brace closing */
811 	if (brace_index) {
812 		n = &xbc_nodes[open_brace[brace_index - 1]];
813 		return xbc_parse_error("Brace is not closed",
814 					xbc_node_get_data(n));
815 	}
816 
817 	/* Empty tree */
818 	if (xbc_node_num == 0) {
819 		xbc_parse_error("Empty config", xbc_data);
820 		return -ENOENT;
821 	}
822 
823 	for (i = 0; i < xbc_node_num; i++) {
824 		if (xbc_nodes[i].next >= xbc_node_num) {
825 			return xbc_parse_error("No closing brace",
826 				xbc_node_get_data(xbc_nodes + i));
827 		}
828 		if (xbc_nodes[i].child >= xbc_node_num) {
829 			return xbc_parse_error("Broken child node",
830 				xbc_node_get_data(xbc_nodes + i));
831 		}
832 	}
833 
834 	/* Key tree limitation check */
835 	n = &xbc_nodes[0];
836 	depth = 1;
837 	len = 0;
838 
839 	while (n) {
840 		wlen = strlen(xbc_node_get_data(n)) + 1;
841 		len += wlen;
842 		if (len > XBC_KEYLEN_MAX)
843 			return xbc_parse_error("Too long key length",
844 				xbc_node_get_data(n));
845 
846 		m = xbc_node_get_child(n);
847 		if (m && xbc_node_is_key(m)) {
848 			n = m;
849 			depth++;
850 			if (depth > XBC_DEPTH_MAX)
851 				return xbc_parse_error("Too many key words",
852 						xbc_node_get_data(n));
853 			continue;
854 		}
855 		len -= wlen;
856 		m = xbc_node_get_next(n);
857 		while (!m) {
858 			n = xbc_node_get_parent(n);
859 			if (!n)
860 				break;
861 			len -= strlen(xbc_node_get_data(n)) + 1;
862 			depth--;
863 			m = xbc_node_get_next(n);
864 		}
865 		n = m;
866 	}
867 
868 	return 0;
869 }
870 
871 /* Need to setup xbc_data and xbc_nodes before call this. */
872 static int __init xbc_parse_tree(void)
873 {
874 	char *p, *q;
875 	int ret = 0, c;
876 
877 	last_parent = NULL;
878 	p = xbc_data;
879 	do {
880 		q = strpbrk(p, "{}=+;:\n#");
881 		if (!q) {
882 			p = skip_spaces(p);
883 			if (*p != '\0')
884 				ret = xbc_parse_error("No delimiter", p);
885 			break;
886 		}
887 
888 		c = *q;
889 		*q++ = '\0';
890 		switch (c) {
891 		case ':':
892 		case '+':
893 			if (*q++ != '=') {
894 				ret = xbc_parse_error(c == '+' ?
895 						"Wrong '+' operator" :
896 						"Wrong ':' operator",
897 							q - 2);
898 				break;
899 			}
900 			fallthrough;
901 		case '=':
902 			ret = xbc_parse_kv(&p, q, c);
903 			break;
904 		case '{':
905 			ret = xbc_open_brace(&p, q);
906 			break;
907 		case '#':
908 			q = skip_comment(q);
909 			fallthrough;
910 		case ';':
911 		case '\n':
912 			ret = xbc_parse_key(&p, q);
913 			break;
914 		case '}':
915 			ret = xbc_close_brace(&p, q);
916 			break;
917 		}
918 	} while (!ret);
919 
920 	return ret;
921 }
922 
923 /**
924  * _xbc_exit() - Clean up all parsed bootconfig
925  * @early: Set true if this is called before budy system is initialized.
926  *
927  * This clears all data structures of parsed bootconfig on memory.
928  * If you need to reuse xbc_init() with new boot config, you can
929  * use this.
930  */
931 void __init _xbc_exit(bool early)
932 {
933 	xbc_free_mem(xbc_data, xbc_data_size, early);
934 	xbc_data = NULL;
935 	xbc_data_size = 0;
936 	xbc_node_num = 0;
937 	xbc_free_mem(xbc_nodes, sizeof(struct xbc_node) * XBC_NODE_MAX, early);
938 	xbc_nodes = NULL;
939 	brace_index = 0;
940 }
941 
942 /**
943  * xbc_init() - Parse given XBC file and build XBC internal tree
944  * @data: The boot config text original data
945  * @size: The size of @data
946  * @emsg: A pointer of const char * to store the error message
947  * @epos: A pointer of int to store the error position
948  *
949  * This parses the boot config text in @data. @size must be smaller
950  * than XBC_DATA_MAX.
951  * Return the number of stored nodes (>0) if succeeded, or -errno
952  * if there is any error.
953  * In error cases, @emsg will be updated with an error message and
954  * @epos will be updated with the error position which is the byte offset
955  * of @buf. If the error is not a parser error, @epos will be -1.
956  */
957 int __init xbc_init(const char *data, size_t size, const char **emsg, int *epos)
958 {
959 	int ret;
960 
961 	if (epos)
962 		*epos = -1;
963 
964 	if (xbc_data) {
965 		if (emsg)
966 			*emsg = "Bootconfig is already initialized";
967 		return -EBUSY;
968 	}
969 	if (size > XBC_DATA_MAX || size == 0) {
970 		if (emsg)
971 			*emsg = size ? "Config data is too big" :
972 				"Config data is empty";
973 		return -ERANGE;
974 	}
975 
976 	xbc_data = xbc_alloc_mem(size + 1);
977 	if (!xbc_data) {
978 		if (emsg)
979 			*emsg = "Failed to allocate bootconfig data";
980 		return -ENOMEM;
981 	}
982 	memcpy(xbc_data, data, size);
983 	xbc_data[size] = '\0';
984 	xbc_data_size = size + 1;
985 
986 	xbc_nodes = xbc_alloc_mem(sizeof(struct xbc_node) * XBC_NODE_MAX);
987 	if (!xbc_nodes) {
988 		if (emsg)
989 			*emsg = "Failed to allocate bootconfig nodes";
990 		_xbc_exit(true);
991 		return -ENOMEM;
992 	}
993 
994 	ret = xbc_parse_tree();
995 	if (!ret)
996 		ret = xbc_verify_tree();
997 
998 	if (ret < 0) {
999 		if (epos)
1000 			*epos = xbc_err_pos;
1001 		if (emsg)
1002 			*emsg = xbc_err_msg;
1003 		_xbc_exit(true);
1004 	} else {
1005 		ret = xbc_node_num;
1006 	}
1007 
1008 	return ret;
1009 }
1010