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