xref: /openbmc/u-boot/lib/libfdt/fdt_region.c (revision e3963c09)
1 // SPDX-License-Identifier: GPL-2.0+ OR BSD-2-Clause
2 /*
3  * libfdt - Flat Device Tree manipulation
4  * Copyright (C) 2013 Google, Inc
5  * Written by Simon Glass <sjg@chromium.org>
6  */
7 
8 #include <linux/libfdt_env.h>
9 
10 #ifndef USE_HOSTCC
11 #include <fdt.h>
12 #include <linux/libfdt.h>
13 #else
14 #include "fdt_host.h"
15 #endif
16 
17 #define FDT_MAX_DEPTH	32
18 
19 static int str_in_list(const char *str, char * const list[], int count)
20 {
21 	int i;
22 
23 	for (i = 0; i < count; i++)
24 		if (!strcmp(list[i], str))
25 			return 1;
26 
27 	return 0;
28 }
29 
30 int fdt_find_regions(const void *fdt, char * const inc[], int inc_count,
31 		     char * const exc_prop[], int exc_prop_count,
32 		     struct fdt_region region[], int max_regions,
33 		     char *path, int path_len, int add_string_tab)
34 {
35 	int stack[FDT_MAX_DEPTH] = { 0 };
36 	char *end;
37 	int nextoffset = 0;
38 	uint32_t tag;
39 	int count = 0;
40 	int start = -1;
41 	int depth = -1;
42 	int want = 0;
43 	int base = fdt_off_dt_struct(fdt);
44 
45 	end = path;
46 	*end = '\0';
47 	do {
48 		const struct fdt_property *prop;
49 		const char *name;
50 		const char *str;
51 		int include = 0;
52 		int stop_at = 0;
53 		int offset;
54 		int len;
55 
56 		offset = nextoffset;
57 		tag = fdt_next_tag(fdt, offset, &nextoffset);
58 		stop_at = nextoffset;
59 
60 		switch (tag) {
61 		case FDT_PROP:
62 			include = want >= 2;
63 			stop_at = offset;
64 			prop = fdt_get_property_by_offset(fdt, offset, NULL);
65 			str = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
66 			if (str_in_list(str, exc_prop, exc_prop_count))
67 				include = 0;
68 			break;
69 
70 		case FDT_NOP:
71 			include = want >= 2;
72 			stop_at = offset;
73 			break;
74 
75 		case FDT_BEGIN_NODE:
76 			depth++;
77 			if (depth == FDT_MAX_DEPTH)
78 				return -FDT_ERR_BADSTRUCTURE;
79 			name = fdt_get_name(fdt, offset, &len);
80 			if (end - path + 2 + len >= path_len)
81 				return -FDT_ERR_NOSPACE;
82 			if (end != path + 1)
83 				*end++ = '/';
84 			strcpy(end, name);
85 			end += len;
86 			stack[depth] = want;
87 			if (want == 1)
88 				stop_at = offset;
89 			if (str_in_list(path, inc, inc_count))
90 				want = 2;
91 			else if (want)
92 				want--;
93 			else
94 				stop_at = offset;
95 			include = want;
96 			break;
97 
98 		case FDT_END_NODE:
99 			/* Depth must never go below -1 */
100 			if (depth < 0)
101 				return -FDT_ERR_BADSTRUCTURE;
102 			include = want;
103 			want = stack[depth--];
104 			while (end > path && *--end != '/')
105 				;
106 			*end = '\0';
107 			break;
108 
109 		case FDT_END:
110 			include = 1;
111 			break;
112 		}
113 
114 		if (include && start == -1) {
115 			/* Should we merge with previous? */
116 			if (count && count <= max_regions &&
117 			    offset == region[count - 1].offset +
118 					region[count - 1].size - base)
119 				start = region[--count].offset - base;
120 			else
121 				start = offset;
122 		}
123 
124 		if (!include && start != -1) {
125 			if (count < max_regions) {
126 				region[count].offset = base + start;
127 				region[count].size = stop_at - start;
128 			}
129 			count++;
130 			start = -1;
131 		}
132 	} while (tag != FDT_END);
133 
134 	if (nextoffset != fdt_size_dt_struct(fdt))
135 		return -FDT_ERR_BADLAYOUT;
136 
137 	/* Add a region for the END tag and the string table */
138 	if (count < max_regions) {
139 		region[count].offset = base + start;
140 		region[count].size = nextoffset - start;
141 		if (add_string_tab)
142 			region[count].size += fdt_size_dt_strings(fdt);
143 	}
144 	count++;
145 
146 	return count;
147 }
148 
149 /**
150  * fdt_add_region() - Add a new region to our list
151  * @info:	State information
152  * @offset:	Start offset of region
153  * @size:	Size of region
154  *
155  * The region is added if there is space, but in any case we increment the
156  * count. If permitted, and the new region overlaps the last one, we merge
157  * them.
158  */
159 static int fdt_add_region(struct fdt_region_state *info, int offset, int size)
160 {
161 	struct fdt_region *reg;
162 
163 	reg = info->region ? &info->region[info->count - 1] : NULL;
164 	if (info->can_merge && info->count &&
165 	    info->count <= info->max_regions &&
166 	    reg && offset <= reg->offset + reg->size) {
167 		reg->size = offset + size - reg->offset;
168 	} else if (info->count++ < info->max_regions) {
169 		if (reg) {
170 			reg++;
171 			reg->offset = offset;
172 			reg->size = size;
173 		}
174 	} else {
175 		return -1;
176 	}
177 
178 	return 0;
179 }
180 
181 static int region_list_contains_offset(struct fdt_region_state *info,
182 				       const void *fdt, int target)
183 {
184 	struct fdt_region *reg;
185 	int num;
186 
187 	target += fdt_off_dt_struct(fdt);
188 	for (reg = info->region, num = 0; num < info->count; reg++, num++) {
189 		if (target >= reg->offset && target < reg->offset + reg->size)
190 			return 1;
191 	}
192 
193 	return 0;
194 }
195 
196 /**
197  * fdt_add_alias_regions() - Add regions covering the aliases that we want
198  *
199  * The /aliases node is not automatically included by fdtgrep unless the
200  * command-line arguments cause to be included (or not excluded). However
201  * aliases are special in that we generally want to include those which
202  * reference a node that fdtgrep includes.
203  *
204  * In fact we want to include only aliases for those nodes still included in
205  * the fdt, and drop the other aliases since they point to nodes that will not
206  * be present.
207  *
208  * This function scans the aliases and adds regions for those which we want
209  * to keep.
210  *
211  * @fdt: Device tree to scan
212  * @region: List of regions
213  * @count: Number of regions in the list so far (i.e. starting point for this
214  *	function)
215  * @max_regions: Maximum number of regions in @region list
216  * @info: Place to put the region state
217  * @return number of regions after processing, or -FDT_ERR_NOSPACE if we did
218  * not have enough room in the regions table for the regions we wanted to add.
219  */
220 int fdt_add_alias_regions(const void *fdt, struct fdt_region *region, int count,
221 			  int max_regions, struct fdt_region_state *info)
222 {
223 	int base = fdt_off_dt_struct(fdt);
224 	int node, node_end, offset;
225 	int did_alias_header;
226 
227 	node = fdt_subnode_offset(fdt, 0, "aliases");
228 	if (node < 0)
229 		return -FDT_ERR_NOTFOUND;
230 
231 	/*
232 	 * Find the next node so that we know where the /aliases node ends. We
233 	 * need special handling if /aliases is the last node.
234 	 */
235 	node_end = fdt_next_subnode(fdt, node);
236 	if (node_end == -FDT_ERR_NOTFOUND)
237 		/* Move back to the FDT_END_NODE tag of '/' */
238 		node_end = fdt_size_dt_struct(fdt) - sizeof(fdt32_t) * 2;
239 	else if (node_end < 0) /* other error */
240 		return node_end;
241 	node_end -= sizeof(fdt32_t);  /* Move to FDT_END_NODE tag of /aliases */
242 
243 	did_alias_header = 0;
244 	info->region = region;
245 	info->count = count;
246 	info->can_merge = 0;
247 	info->max_regions = max_regions;
248 
249 	for (offset = fdt_first_property_offset(fdt, node);
250 	     offset >= 0;
251 	     offset = fdt_next_property_offset(fdt, offset)) {
252 		const struct fdt_property *prop;
253 		const char *name;
254 		int target, next;
255 
256 		prop = fdt_get_property_by_offset(fdt, offset, NULL);
257 		name = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
258 		target = fdt_path_offset(fdt, name);
259 		if (!region_list_contains_offset(info, fdt, target))
260 			continue;
261 		next = fdt_next_property_offset(fdt, offset);
262 		if (next < 0)
263 			next = node_end;
264 
265 		if (!did_alias_header) {
266 			fdt_add_region(info, base + node, 12);
267 			did_alias_header = 1;
268 		}
269 		fdt_add_region(info, base + offset, next - offset);
270 	}
271 
272 	/* Add the FDT_END_NODE tag */
273 	if (did_alias_header)
274 		fdt_add_region(info, base + node_end, sizeof(fdt32_t));
275 
276 	return info->count < max_regions ? info->count : -FDT_ERR_NOSPACE;
277 }
278 
279 /**
280  * fdt_include_supernodes() - Include supernodes required by this node
281  * @info:	State information
282  * @depth:	Current stack depth
283  *
284  * When we decided to include a node or property which is not at the top
285  * level, this function forces the inclusion of higher level nodes. For
286  * example, given this tree:
287  *
288  * / {
289  *     testing {
290  *     }
291  * }
292  *
293  * If we decide to include testing then we need the root node to have a valid
294  * tree. This function adds those regions.
295  */
296 static int fdt_include_supernodes(struct fdt_region_state *info, int depth)
297 {
298 	int base = fdt_off_dt_struct(info->fdt);
299 	int start, stop_at;
300 	int i;
301 
302 	/*
303 	 * Work down the stack looking for supernodes that we didn't include.
304 	 * The algortihm here is actually pretty simple, since we know that
305 	 * no previous subnode had to include these nodes, or if it did, we
306 	 * marked them as included (on the stack) already.
307 	 */
308 	for (i = 0; i <= depth; i++) {
309 		if (!info->stack[i].included) {
310 			start = info->stack[i].offset;
311 
312 			/* Add the FDT_BEGIN_NODE tag of this supernode */
313 			fdt_next_tag(info->fdt, start, &stop_at);
314 			if (fdt_add_region(info, base + start, stop_at - start))
315 				return -1;
316 
317 			/* Remember that this supernode is now included */
318 			info->stack[i].included = 1;
319 			info->can_merge = 1;
320 		}
321 
322 		/* Force (later) generation of the FDT_END_NODE tag */
323 		if (!info->stack[i].want)
324 			info->stack[i].want = WANT_NODES_ONLY;
325 	}
326 
327 	return 0;
328 }
329 
330 enum {
331 	FDT_DONE_NOTHING,
332 	FDT_DONE_MEM_RSVMAP,
333 	FDT_DONE_STRUCT,
334 	FDT_DONE_END,
335 	FDT_DONE_STRINGS,
336 	FDT_DONE_ALL,
337 };
338 
339 int fdt_first_region(const void *fdt,
340 		int (*h_include)(void *priv, const void *fdt, int offset,
341 				 int type, const char *data, int size),
342 		void *priv, struct fdt_region *region,
343 		char *path, int path_len, int flags,
344 		struct fdt_region_state *info)
345 {
346 	struct fdt_region_ptrs *p = &info->ptrs;
347 
348 	/* Set up our state */
349 	info->fdt = fdt;
350 	info->can_merge = 1;
351 	info->max_regions = 1;
352 	info->start = -1;
353 	p->want = WANT_NOTHING;
354 	p->end = path;
355 	*p->end = '\0';
356 	p->nextoffset = 0;
357 	p->depth = -1;
358 	p->done = FDT_DONE_NOTHING;
359 
360 	return fdt_next_region(fdt, h_include, priv, region,
361 			       path, path_len, flags, info);
362 }
363 
364 /***********************************************************************
365  *
366  *	Theory of operation
367  *
368  * Note: in this description 'included' means that a node (or other part
369  * of the tree) should be included in the region list, i.e. it will have
370  * a region which covers its part of the tree.
371  *
372  * This function maintains some state from the last time it is called.
373  * It checks the next part of the tree that it is supposed to look at
374  * (p.nextoffset) to see if that should be included or not. When it
375  * finds something to include, it sets info->start to its offset. This
376  * marks the start of the region we want to include.
377  *
378  * Once info->start is set to the start (i.e. not -1), we continue
379  * scanning until we find something that we don't want included. This
380  * will be the end of a region. At this point we can close off the
381  * region and add it to the list. So we do so, and reset info->start
382  * to -1.
383  *
384  * One complication here is that we want to merge regions. So when we
385  * come to add another region later, we may in fact merge it with the
386  * previous one if one ends where the other starts.
387  *
388  * The function fdt_add_region() will return -1 if it fails to add the
389  * region, because we already have a region ready to be returned, and
390  * the new one cannot be merged in with it. In this case, we must return
391  * the region we found, and wait for another call to this function.
392  * When it comes, we will repeat the processing of the tag and again
393  * try to add a region. This time it will succeed.
394  *
395  * The current state of the pointers (stack, offset, etc.) is maintained
396  * in a ptrs member. At the start of every loop iteration we make a copy
397  * of it.  The copy is then updated as the tag is processed. Only if we
398  * get to the end of the loop iteration (and successfully call
399  * fdt_add_region() if we need to) can we commit the changes we have
400  * made to these pointers. For example, if we see an FDT_END_NODE tag,
401  * we will decrement the depth value. But if we need to add a region
402  * for this tag (let's say because the previous tag is included and this
403  * FDT_END_NODE tag is not included) then we will only commit the result
404  * if we were able to add the region. That allows us to retry again next
405  * time.
406  *
407  * We keep track of a variable called 'want' which tells us what we want
408  * to include when there is no specific information provided by the
409  * h_include function for a particular property. This basically handles
410  * the inclusion of properties which are pulled in by virtue of the node
411  * they are in. So if you include a node, its properties are also
412  * included.  In this case 'want' will be WANT_NODES_AND_PROPS. The
413  * FDT_REG_DIRECT_SUBNODES feature also makes use of 'want'. While we
414  * are inside the subnode, 'want' will be set to WANT_NODES_ONLY, so
415  * that only the subnode's FDT_BEGIN_NODE and FDT_END_NODE tags will be
416  * included, and properties will be skipped. If WANT_NOTHING is
417  * selected, then we will just rely on what the h_include() function
418  * tells us.
419  *
420  * Using 'want' we work out 'include', which tells us whether this
421  * current tag should be included or not. As you can imagine, if the
422  * value of 'include' changes, that means we are on a boundary between
423  * nodes to include and nodes to exclude. At this point we either close
424  * off a previous region and add it to the list, or mark the start of a
425  * new region.
426  *
427  * Apart from the nodes, we have mem_rsvmap, the FDT_END tag and the
428  * string list. Each of these dealt with as a whole (i.e. we create a
429  * region for each if it is to be included). For mem_rsvmap we don't
430  * allow it to merge with the first struct region. For the stringlist,
431  * we don't allow it to merge with the last struct region (which
432  * contains at minimum the FDT_END tag).
433  *
434  *********************************************************************/
435 
436 int fdt_next_region(const void *fdt,
437 		int (*h_include)(void *priv, const void *fdt, int offset,
438 				 int type, const char *data, int size),
439 		void *priv, struct fdt_region *region,
440 		char *path, int path_len, int flags,
441 		struct fdt_region_state *info)
442 {
443 	int base = fdt_off_dt_struct(fdt);
444 	int last_node = 0;
445 	const char *str;
446 
447 	info->region = region;
448 	info->count = 0;
449 	if (info->ptrs.done < FDT_DONE_MEM_RSVMAP &&
450 	    (flags & FDT_REG_ADD_MEM_RSVMAP)) {
451 		/* Add the memory reserve map into its own region */
452 		if (fdt_add_region(info, fdt_off_mem_rsvmap(fdt),
453 				   fdt_off_dt_struct(fdt) -
454 				   fdt_off_mem_rsvmap(fdt)))
455 			return 0;
456 		info->can_merge = 0;	/* Don't allow merging with this */
457 		info->ptrs.done = FDT_DONE_MEM_RSVMAP;
458 	}
459 
460 	/*
461 	 * Work through the tags one by one, deciding whether each needs to
462 	 * be included or not. We set the variable 'include' to indicate our
463 	 * decision. 'want' is used to track what we want to include - it
464 	 * allows us to pick up all the properties (and/or subnode tags) of
465 	 * a node.
466 	 */
467 	while (info->ptrs.done < FDT_DONE_STRUCT) {
468 		const struct fdt_property *prop;
469 		struct fdt_region_ptrs p;
470 		const char *name;
471 		int include = 0;
472 		int stop_at = 0;
473 		uint32_t tag;
474 		int offset;
475 		int val;
476 		int len;
477 
478 		/*
479 		 * Make a copy of our pointers. If we make it to the end of
480 		 * this block then we will commit them back to info->ptrs.
481 		 * Otherwise we can try again from the same starting state
482 		 * next time we are called.
483 		 */
484 		p = info->ptrs;
485 
486 		/*
487 		 * Find the tag, and the offset of the next one. If we need to
488 		 * stop including tags, then by default we stop *after*
489 		 * including the current tag
490 		 */
491 		offset = p.nextoffset;
492 		tag = fdt_next_tag(fdt, offset, &p.nextoffset);
493 		stop_at = p.nextoffset;
494 
495 		switch (tag) {
496 		case FDT_PROP:
497 			stop_at = offset;
498 			prop = fdt_get_property_by_offset(fdt, offset, NULL);
499 			str = fdt_string(fdt, fdt32_to_cpu(prop->nameoff));
500 			val = h_include(priv, fdt, last_node, FDT_IS_PROP, str,
501 					    strlen(str) + 1);
502 			if (val == -1) {
503 				include = p.want >= WANT_NODES_AND_PROPS;
504 			} else {
505 				include = val;
506 				/*
507 				 * Make sure we include the } for this block.
508 				 * It might be more correct to have this done
509 				 * by the call to fdt_include_supernodes() in
510 				 * the case where it adds the node we are
511 				 * currently in, but this is equivalent.
512 				 */
513 				if ((flags & FDT_REG_SUPERNODES) && val &&
514 				    !p.want)
515 					p.want = WANT_NODES_ONLY;
516 			}
517 
518 			/* Value grepping is not yet supported */
519 			break;
520 
521 		case FDT_NOP:
522 			include = p.want >= WANT_NODES_AND_PROPS;
523 			stop_at = offset;
524 			break;
525 
526 		case FDT_BEGIN_NODE:
527 			last_node = offset;
528 			p.depth++;
529 			if (p.depth == FDT_MAX_DEPTH)
530 				return -FDT_ERR_BADSTRUCTURE;
531 			name = fdt_get_name(fdt, offset, &len);
532 			if (p.end - path + 2 + len >= path_len)
533 				return -FDT_ERR_NOSPACE;
534 
535 			/* Build the full path of this node */
536 			if (p.end != path + 1)
537 				*p.end++ = '/';
538 			strcpy(p.end, name);
539 			p.end += len;
540 			info->stack[p.depth].want = p.want;
541 			info->stack[p.depth].offset = offset;
542 
543 			/*
544 			 * If we are not intending to include this node unless
545 			 * it matches, make sure we stop *before* its tag.
546 			 */
547 			if (p.want == WANT_NODES_ONLY ||
548 			    !(flags & (FDT_REG_DIRECT_SUBNODES |
549 				       FDT_REG_ALL_SUBNODES))) {
550 				stop_at = offset;
551 				p.want = WANT_NOTHING;
552 			}
553 			val = h_include(priv, fdt, offset, FDT_IS_NODE, path,
554 					p.end - path + 1);
555 
556 			/* Include this if requested */
557 			if (val) {
558 				p.want = (flags & FDT_REG_ALL_SUBNODES) ?
559 					WANT_ALL_NODES_AND_PROPS :
560 					WANT_NODES_AND_PROPS;
561 			}
562 
563 			/* If not requested, decay our 'p.want' value */
564 			else if (p.want) {
565 				if (p.want != WANT_ALL_NODES_AND_PROPS)
566 					p.want--;
567 
568 			/* Not including this tag, so stop now */
569 			} else {
570 				stop_at = offset;
571 			}
572 
573 			/*
574 			 * Decide whether to include this tag, and update our
575 			 * stack with the state for this node
576 			 */
577 			include = p.want;
578 			info->stack[p.depth].included = include;
579 			break;
580 
581 		case FDT_END_NODE:
582 			include = p.want;
583 			if (p.depth < 0)
584 				return -FDT_ERR_BADSTRUCTURE;
585 
586 			/*
587 			 * If we don't want this node, stop right away, unless
588 			 * we are including subnodes
589 			 */
590 			if (!p.want && !(flags & FDT_REG_DIRECT_SUBNODES))
591 				stop_at = offset;
592 			p.want = info->stack[p.depth].want;
593 			p.depth--;
594 			while (p.end > path && *--p.end != '/')
595 				;
596 			*p.end = '\0';
597 			break;
598 
599 		case FDT_END:
600 			/* We always include the end tag */
601 			include = 1;
602 			p.done = FDT_DONE_STRUCT;
603 			break;
604 		}
605 
606 		/* If this tag is to be included, mark it as region start */
607 		if (include && info->start == -1) {
608 			/* Include any supernodes required by this one */
609 			if (flags & FDT_REG_SUPERNODES) {
610 				if (fdt_include_supernodes(info, p.depth))
611 					return 0;
612 			}
613 			info->start = offset;
614 		}
615 
616 		/*
617 		 * If this tag is not to be included, finish up the current
618 		 * region.
619 		 */
620 		if (!include && info->start != -1) {
621 			if (fdt_add_region(info, base + info->start,
622 					   stop_at - info->start))
623 				return 0;
624 			info->start = -1;
625 			info->can_merge = 1;
626 		}
627 
628 		/* If we have made it this far, we can commit our pointers */
629 		info->ptrs = p;
630 	}
631 
632 	/* Add a region for the END tag and a separate one for string table */
633 	if (info->ptrs.done < FDT_DONE_END) {
634 		if (info->ptrs.nextoffset != fdt_size_dt_struct(fdt))
635 			return -FDT_ERR_BADSTRUCTURE;
636 
637 		if (fdt_add_region(info, base + info->start,
638 				   info->ptrs.nextoffset - info->start))
639 			return 0;
640 		info->ptrs.done++;
641 	}
642 	if (info->ptrs.done < FDT_DONE_STRINGS) {
643 		if (flags & FDT_REG_ADD_STRING_TAB) {
644 			info->can_merge = 0;
645 			if (fdt_off_dt_strings(fdt) <
646 			    base + info->ptrs.nextoffset)
647 				return -FDT_ERR_BADLAYOUT;
648 			if (fdt_add_region(info, fdt_off_dt_strings(fdt),
649 					   fdt_size_dt_strings(fdt)))
650 				return 0;
651 		}
652 		info->ptrs.done++;
653 	}
654 
655 	return info->count > 0 ? 0 : -FDT_ERR_NOTFOUND;
656 }
657