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