xref: /openbmc/linux/drivers/of/overlay.c (revision 39a751a4cb7e4798f0ce1169ec92de4a1aae39e3)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Functions for working with device tree overlays
4  *
5  * Copyright (C) 2012 Pantelis Antoniou <panto@antoniou-consulting.com>
6  * Copyright (C) 2012 Texas Instruments Inc.
7  */
8 
9 #define pr_fmt(fmt)	"OF: overlay: " fmt
10 
11 #include <linux/kernel.h>
12 #include <linux/module.h>
13 #include <linux/of.h>
14 #include <linux/of_device.h>
15 #include <linux/of_fdt.h>
16 #include <linux/string.h>
17 #include <linux/ctype.h>
18 #include <linux/errno.h>
19 #include <linux/slab.h>
20 #include <linux/libfdt.h>
21 #include <linux/err.h>
22 #include <linux/idr.h>
23 
24 #include "of_private.h"
25 
26 /**
27  * struct fragment - info about fragment nodes in overlay expanded device tree
28  * @target:	target of the overlay operation
29  * @overlay:	pointer to the __overlay__ node
30  */
31 struct fragment {
32 	struct device_node *target;
33 	struct device_node *overlay;
34 };
35 
36 /**
37  * struct overlay_changeset
38  * @id:			changeset identifier
39  * @ovcs_list:		list on which we are located
40  * @fdt:		FDT that was unflattened to create @overlay_tree
41  * @overlay_tree:	expanded device tree that contains the fragment nodes
42  * @count:		count of fragment structures
43  * @fragments:		fragment nodes in the overlay expanded device tree
44  * @symbols_fragment:	last element of @fragments[] is the  __symbols__ node
45  * @cset:		changeset to apply fragments to live device tree
46  */
47 struct overlay_changeset {
48 	int id;
49 	struct list_head ovcs_list;
50 	const void *fdt;
51 	struct device_node *overlay_tree;
52 	int count;
53 	struct fragment *fragments;
54 	bool symbols_fragment;
55 	struct of_changeset cset;
56 };
57 
58 /* flags are sticky - once set, do not reset */
59 static int devicetree_state_flags;
60 #define DTSF_APPLY_FAIL		0x01
61 #define DTSF_REVERT_FAIL	0x02
62 
63 /*
64  * If a changeset apply or revert encounters an error, an attempt will
65  * be made to undo partial changes, but may fail.  If the undo fails
66  * we do not know the state of the devicetree.
67  */
68 static int devicetree_corrupt(void)
69 {
70 	return devicetree_state_flags &
71 		(DTSF_APPLY_FAIL | DTSF_REVERT_FAIL);
72 }
73 
74 static int build_changeset_next_level(struct overlay_changeset *ovcs,
75 		struct device_node *target_node,
76 		const struct device_node *overlay_node);
77 
78 /*
79  * of_resolve_phandles() finds the largest phandle in the live tree.
80  * of_overlay_apply() may add a larger phandle to the live tree.
81  * Do not allow race between two overlays being applied simultaneously:
82  *    mutex_lock(&of_overlay_phandle_mutex)
83  *    of_resolve_phandles()
84  *    of_overlay_apply()
85  *    mutex_unlock(&of_overlay_phandle_mutex)
86  */
87 static DEFINE_MUTEX(of_overlay_phandle_mutex);
88 
89 void of_overlay_mutex_lock(void)
90 {
91 	mutex_lock(&of_overlay_phandle_mutex);
92 }
93 
94 void of_overlay_mutex_unlock(void)
95 {
96 	mutex_unlock(&of_overlay_phandle_mutex);
97 }
98 
99 
100 static LIST_HEAD(ovcs_list);
101 static DEFINE_IDR(ovcs_idr);
102 
103 static BLOCKING_NOTIFIER_HEAD(overlay_notify_chain);
104 
105 int of_overlay_notifier_register(struct notifier_block *nb)
106 {
107 	return blocking_notifier_chain_register(&overlay_notify_chain, nb);
108 }
109 EXPORT_SYMBOL_GPL(of_overlay_notifier_register);
110 
111 int of_overlay_notifier_unregister(struct notifier_block *nb)
112 {
113 	return blocking_notifier_chain_unregister(&overlay_notify_chain, nb);
114 }
115 EXPORT_SYMBOL_GPL(of_overlay_notifier_unregister);
116 
117 static char *of_overlay_action_name[] = {
118 	"pre-apply",
119 	"post-apply",
120 	"pre-remove",
121 	"post-remove",
122 };
123 
124 static int overlay_notify(struct overlay_changeset *ovcs,
125 		enum of_overlay_notify_action action)
126 {
127 	struct of_overlay_notify_data nd;
128 	int i, ret;
129 
130 	for (i = 0; i < ovcs->count; i++) {
131 		struct fragment *fragment = &ovcs->fragments[i];
132 
133 		nd.target = fragment->target;
134 		nd.overlay = fragment->overlay;
135 
136 		ret = blocking_notifier_call_chain(&overlay_notify_chain,
137 						   action, &nd);
138 		if (ret == NOTIFY_OK || ret == NOTIFY_STOP)
139 			return 0;
140 		if (ret) {
141 			ret = notifier_to_errno(ret);
142 			pr_err("overlay changeset %s notifier error %d, target: %pOF\n",
143 			       of_overlay_action_name[action], ret, nd.target);
144 			return ret;
145 		}
146 	}
147 
148 	return 0;
149 }
150 
151 /*
152  * The values of properties in the "/__symbols__" node are paths in
153  * the ovcs->overlay_tree.  When duplicating the properties, the paths
154  * need to be adjusted to be the correct path for the live device tree.
155  *
156  * The paths refer to a node in the subtree of a fragment node's "__overlay__"
157  * node, for example "/fragment@0/__overlay__/symbol_path_tail",
158  * where symbol_path_tail can be a single node or it may be a multi-node path.
159  *
160  * The duplicated property value will be modified by replacing the
161  * "/fragment_name/__overlay/" portion of the value  with the target
162  * path from the fragment node.
163  */
164 static struct property *dup_and_fixup_symbol_prop(
165 		struct overlay_changeset *ovcs, const struct property *prop)
166 {
167 	struct fragment *fragment;
168 	struct property *new_prop;
169 	struct device_node *fragment_node;
170 	struct device_node *overlay_node;
171 	const char *path;
172 	const char *path_tail;
173 	const char *target_path;
174 	int k;
175 	int overlay_name_len;
176 	int path_len;
177 	int path_tail_len;
178 	int target_path_len;
179 
180 	if (!prop->value)
181 		return NULL;
182 	if (strnlen(prop->value, prop->length) >= prop->length)
183 		return NULL;
184 	path = prop->value;
185 	path_len = strlen(path);
186 
187 	if (path_len < 1)
188 		return NULL;
189 	fragment_node = __of_find_node_by_path(ovcs->overlay_tree, path + 1);
190 	overlay_node = __of_find_node_by_path(fragment_node, "__overlay__/");
191 	of_node_put(fragment_node);
192 	of_node_put(overlay_node);
193 
194 	for (k = 0; k < ovcs->count; k++) {
195 		fragment = &ovcs->fragments[k];
196 		if (fragment->overlay == overlay_node)
197 			break;
198 	}
199 	if (k >= ovcs->count)
200 		return NULL;
201 
202 	overlay_name_len = snprintf(NULL, 0, "%pOF", fragment->overlay);
203 
204 	if (overlay_name_len > path_len)
205 		return NULL;
206 	path_tail = path + overlay_name_len;
207 	path_tail_len = strlen(path_tail);
208 
209 	target_path = kasprintf(GFP_KERNEL, "%pOF", fragment->target);
210 	if (!target_path)
211 		return NULL;
212 	target_path_len = strlen(target_path);
213 
214 	new_prop = kzalloc(sizeof(*new_prop), GFP_KERNEL);
215 	if (!new_prop)
216 		goto err_free_target_path;
217 
218 	new_prop->name = kstrdup(prop->name, GFP_KERNEL);
219 	new_prop->length = target_path_len + path_tail_len + 1;
220 	new_prop->value = kzalloc(new_prop->length, GFP_KERNEL);
221 	if (!new_prop->name || !new_prop->value)
222 		goto err_free_new_prop;
223 
224 	strcpy(new_prop->value, target_path);
225 	strcpy(new_prop->value + target_path_len, path_tail);
226 
227 	of_property_set_flag(new_prop, OF_DYNAMIC);
228 
229 	return new_prop;
230 
231 err_free_new_prop:
232 	kfree(new_prop->name);
233 	kfree(new_prop->value);
234 	kfree(new_prop);
235 err_free_target_path:
236 	kfree(target_path);
237 
238 	return NULL;
239 }
240 
241 /**
242  * add_changeset_property() - add @overlay_prop to overlay changeset
243  * @ovcs:		overlay changeset
244  * @target_node:	where to place @overlay_prop in live tree
245  * @overlay_prop:	property to add or update, from overlay tree
246  * @is_symbols_prop:	1 if @overlay_prop is from node "/__symbols__"
247  *
248  * If @overlay_prop does not already exist in @target_node, add changeset entry
249  * to add @overlay_prop in @target_node, else add changeset entry to update
250  * value of @overlay_prop.
251  *
252  * Some special properties are not updated (no error returned).
253  *
254  * Update of property in symbols node is not allowed.
255  *
256  * Returns 0 on success, -ENOMEM if memory allocation failure, or -EINVAL if
257  * invalid @overlay.
258  */
259 static int add_changeset_property(struct overlay_changeset *ovcs,
260 		struct device_node *target_node,
261 		struct property *overlay_prop,
262 		bool is_symbols_prop)
263 {
264 	struct property *new_prop = NULL, *prop;
265 	int ret = 0;
266 
267 	prop = of_find_property(target_node, overlay_prop->name, NULL);
268 
269 	if (!of_prop_cmp(overlay_prop->name, "name") ||
270 	    !of_prop_cmp(overlay_prop->name, "phandle") ||
271 	    !of_prop_cmp(overlay_prop->name, "linux,phandle"))
272 		return 0;
273 
274 	if (is_symbols_prop) {
275 		if (prop)
276 			return -EINVAL;
277 		new_prop = dup_and_fixup_symbol_prop(ovcs, overlay_prop);
278 	} else {
279 		new_prop = __of_prop_dup(overlay_prop, GFP_KERNEL);
280 	}
281 
282 	if (!new_prop)
283 		return -ENOMEM;
284 
285 	if (!prop)
286 		ret = of_changeset_add_property(&ovcs->cset, target_node,
287 						new_prop);
288 	else
289 		ret = of_changeset_update_property(&ovcs->cset, target_node,
290 						   new_prop);
291 
292 	if (ret) {
293 		kfree(new_prop->name);
294 		kfree(new_prop->value);
295 		kfree(new_prop);
296 	}
297 	return ret;
298 }
299 
300 /**
301  * add_changeset_node() - add @node (and children) to overlay changeset
302  * @ovcs:		overlay changeset
303  * @target_node:	where to place @node in live tree
304  * @node:		node from within overlay device tree fragment
305  *
306  * If @node does not already exist in @target_node, add changeset entry
307  * to add @node in @target_node.
308  *
309  * If @node already exists in @target_node, and the existing node has
310  * a phandle, the overlay node is not allowed to have a phandle.
311  *
312  * If @node has child nodes, add the children recursively via
313  * build_changeset_next_level().
314  *
315  * NOTE: Multiple mods of created nodes not supported.
316  *       If more than one fragment contains a node that does not already exist
317  *       in the live tree, then for each fragment of_changeset_attach_node()
318  *       will add a changeset entry to add the node.  When the changeset is
319  *       applied, __of_attach_node() will attach the node twice (once for
320  *       each fragment).  At this point the device tree will be corrupted.
321  *
322  *       TODO: add integrity check to ensure that multiple fragments do not
323  *             create the same node.
324  *
325  * Returns 0 on success, -ENOMEM if memory allocation failure, or -EINVAL if
326  * invalid @overlay.
327  */
328 static int add_changeset_node(struct overlay_changeset *ovcs,
329 		struct device_node *target_node, struct device_node *node)
330 {
331 	const char *node_kbasename;
332 	struct device_node *tchild;
333 	int ret = 0;
334 
335 	node_kbasename = kbasename(node->full_name);
336 
337 	for_each_child_of_node(target_node, tchild)
338 		if (!of_node_cmp(node_kbasename, kbasename(tchild->full_name)))
339 			break;
340 
341 	if (!tchild) {
342 		tchild = __of_node_dup(node, "%pOF/%s",
343 				       target_node, node_kbasename);
344 		if (!tchild)
345 			return -ENOMEM;
346 
347 		tchild->parent = target_node;
348 
349 		ret = of_changeset_attach_node(&ovcs->cset, tchild);
350 		if (ret)
351 			return ret;
352 
353 		return build_changeset_next_level(ovcs, tchild, node);
354 	}
355 
356 	if (node->phandle && tchild->phandle)
357 		ret = -EINVAL;
358 	else
359 		ret = build_changeset_next_level(ovcs, tchild, node);
360 	of_node_put(tchild);
361 
362 	return ret;
363 }
364 
365 /**
366  * build_changeset_next_level() - add level of overlay changeset
367  * @ovcs:		overlay changeset
368  * @target_node:	where to place @overlay_node in live tree
369  * @overlay_node:	node from within an overlay device tree fragment
370  *
371  * Add the properties (if any) and nodes (if any) from @overlay_node to the
372  * @ovcs->cset changeset.  If an added node has child nodes, they will
373  * be added recursively.
374  *
375  * Do not allow symbols node to have any children.
376  *
377  * Returns 0 on success, -ENOMEM if memory allocation failure, or -EINVAL if
378  * invalid @overlay_node.
379  */
380 static int build_changeset_next_level(struct overlay_changeset *ovcs,
381 		struct device_node *target_node,
382 		const struct device_node *overlay_node)
383 {
384 	struct device_node *child;
385 	struct property *prop;
386 	int ret;
387 
388 	for_each_property_of_node(overlay_node, prop) {
389 		ret = add_changeset_property(ovcs, target_node, prop, 0);
390 		if (ret) {
391 			pr_debug("Failed to apply prop @%pOF/%s, err=%d\n",
392 				 target_node, prop->name, ret);
393 			return ret;
394 		}
395 	}
396 
397 	for_each_child_of_node(overlay_node, child) {
398 		ret = add_changeset_node(ovcs, target_node, child);
399 		if (ret) {
400 			pr_debug("Failed to apply node @%pOF/%s, err=%d\n",
401 				 target_node, child->name, ret);
402 			of_node_put(child);
403 			return ret;
404 		}
405 	}
406 
407 	return 0;
408 }
409 
410 /*
411  * Add the properties from __overlay__ node to the @ovcs->cset changeset.
412  */
413 static int build_changeset_symbols_node(struct overlay_changeset *ovcs,
414 		struct device_node *target_node,
415 		const struct device_node *overlay_symbols_node)
416 {
417 	struct property *prop;
418 	int ret;
419 
420 	for_each_property_of_node(overlay_symbols_node, prop) {
421 		ret = add_changeset_property(ovcs, target_node, prop, 1);
422 		if (ret) {
423 			pr_debug("Failed to apply prop @%pOF/%s, err=%d\n",
424 				 target_node, prop->name, ret);
425 			return ret;
426 		}
427 	}
428 
429 	return 0;
430 }
431 
432 /**
433  * build_changeset() - populate overlay changeset in @ovcs from @ovcs->fragments
434  * @ovcs:	Overlay changeset
435  *
436  * Create changeset @ovcs->cset to contain the nodes and properties of the
437  * overlay device tree fragments in @ovcs->fragments[].  If an error occurs,
438  * any portions of the changeset that were successfully created will remain
439  * in @ovcs->cset.
440  *
441  * Returns 0 on success, -ENOMEM if memory allocation failure, or -EINVAL if
442  * invalid overlay in @ovcs->fragments[].
443  */
444 static int build_changeset(struct overlay_changeset *ovcs)
445 {
446 	struct fragment *fragment;
447 	int fragments_count, i, ret;
448 
449 	/*
450 	 * if there is a symbols fragment in ovcs->fragments[i] it is
451 	 * the final element in the array
452 	 */
453 	if (ovcs->symbols_fragment)
454 		fragments_count = ovcs->count - 1;
455 	else
456 		fragments_count = ovcs->count;
457 
458 	for (i = 0; i < fragments_count; i++) {
459 		fragment = &ovcs->fragments[i];
460 
461 		ret = build_changeset_next_level(ovcs, fragment->target,
462 						 fragment->overlay);
463 		if (ret) {
464 			pr_debug("apply failed '%pOF'\n", fragment->target);
465 			return ret;
466 		}
467 	}
468 
469 	if (ovcs->symbols_fragment) {
470 		fragment = &ovcs->fragments[ovcs->count - 1];
471 		ret = build_changeset_symbols_node(ovcs, fragment->target,
472 						   fragment->overlay);
473 		if (ret) {
474 			pr_debug("apply failed '%pOF'\n", fragment->target);
475 			return ret;
476 		}
477 	}
478 
479 	return 0;
480 }
481 
482 /*
483  * Find the target node using a number of different strategies
484  * in order of preference:
485  *
486  * 1) "target" property containing the phandle of the target
487  * 2) "target-path" property containing the path of the target
488  */
489 static struct device_node *find_target_node(struct device_node *info_node)
490 {
491 	const char *path;
492 	u32 val;
493 	int ret;
494 
495 	ret = of_property_read_u32(info_node, "target", &val);
496 	if (!ret)
497 		return of_find_node_by_phandle(val);
498 
499 	ret = of_property_read_string(info_node, "target-path", &path);
500 	if (!ret)
501 		return of_find_node_by_path(path);
502 
503 	pr_err("Failed to find target for node %p (%s)\n",
504 		info_node, info_node->name);
505 
506 	return NULL;
507 }
508 
509 /**
510  * init_overlay_changeset() - initialize overlay changeset from overlay tree
511  * @ovcs:	Overlay changeset to build
512  * @fdt:	the FDT that was unflattened to create @tree
513  * @tree:	Contains all the overlay fragments and overlay fixup nodes
514  *
515  * Initialize @ovcs.  Populate @ovcs->fragments with node information from
516  * the top level of @tree.  The relevant top level nodes are the fragment
517  * nodes and the __symbols__ node.  Any other top level node will be ignored.
518  *
519  * Returns 0 on success, -ENOMEM if memory allocation failure, -EINVAL if error
520  * detected in @tree, or -ENOSPC if idr_alloc() error.
521  */
522 static int init_overlay_changeset(struct overlay_changeset *ovcs,
523 		const void *fdt, struct device_node *tree)
524 {
525 	struct device_node *node, *overlay_node;
526 	struct fragment *fragment;
527 	struct fragment *fragments;
528 	int cnt, id, ret;
529 
530 	/*
531 	 * Warn for some issues.  Can not return -EINVAL for these until
532 	 * of_unittest_apply_overlay() is fixed to pass these checks.
533 	 */
534 	if (!of_node_check_flag(tree, OF_DYNAMIC))
535 		pr_debug("%s() tree is not dynamic\n", __func__);
536 
537 	if (!of_node_check_flag(tree, OF_DETACHED))
538 		pr_debug("%s() tree is not detached\n", __func__);
539 
540 	if (!of_node_is_root(tree))
541 		pr_debug("%s() tree is not root\n", __func__);
542 
543 	ovcs->overlay_tree = tree;
544 	ovcs->fdt = fdt;
545 
546 	INIT_LIST_HEAD(&ovcs->ovcs_list);
547 
548 	of_changeset_init(&ovcs->cset);
549 
550 	id = idr_alloc(&ovcs_idr, ovcs, 1, 0, GFP_KERNEL);
551 	if (id <= 0)
552 		return id;
553 
554 	cnt = 0;
555 
556 	/* fragment nodes */
557 	for_each_child_of_node(tree, node) {
558 		overlay_node = of_get_child_by_name(node, "__overlay__");
559 		if (overlay_node) {
560 			cnt++;
561 			of_node_put(overlay_node);
562 		}
563 	}
564 
565 	node = of_get_child_by_name(tree, "__symbols__");
566 	if (node) {
567 		cnt++;
568 		of_node_put(node);
569 	}
570 
571 	fragments = kcalloc(cnt, sizeof(*fragments), GFP_KERNEL);
572 	if (!fragments) {
573 		ret = -ENOMEM;
574 		goto err_free_idr;
575 	}
576 
577 	cnt = 0;
578 	for_each_child_of_node(tree, node) {
579 		overlay_node = of_get_child_by_name(node, "__overlay__");
580 		if (!overlay_node)
581 			continue;
582 
583 		fragment = &fragments[cnt];
584 		fragment->overlay = overlay_node;
585 		fragment->target = find_target_node(node);
586 		if (!fragment->target) {
587 			of_node_put(fragment->overlay);
588 			ret = -EINVAL;
589 			goto err_free_fragments;
590 		}
591 
592 		cnt++;
593 	}
594 
595 	/*
596 	 * if there is a symbols fragment in ovcs->fragments[i] it is
597 	 * the final element in the array
598 	 */
599 	node = of_get_child_by_name(tree, "__symbols__");
600 	if (node) {
601 		ovcs->symbols_fragment = 1;
602 		fragment = &fragments[cnt];
603 		fragment->overlay = node;
604 		fragment->target = of_find_node_by_path("/__symbols__");
605 
606 		if (!fragment->target) {
607 			pr_err("symbols in overlay, but not in live tree\n");
608 			ret = -EINVAL;
609 			goto err_free_fragments;
610 		}
611 
612 		cnt++;
613 	}
614 
615 	if (!cnt) {
616 		pr_err("no fragments or symbols in overlay\n");
617 		ret = -EINVAL;
618 		goto err_free_fragments;
619 	}
620 
621 	ovcs->id = id;
622 	ovcs->count = cnt;
623 	ovcs->fragments = fragments;
624 
625 	return 0;
626 
627 err_free_fragments:
628 	kfree(fragments);
629 err_free_idr:
630 	idr_remove(&ovcs_idr, id);
631 
632 	pr_err("%s() failed, ret = %d\n", __func__, ret);
633 
634 	return ret;
635 }
636 
637 static void free_overlay_changeset(struct overlay_changeset *ovcs)
638 {
639 	int i;
640 
641 	if (ovcs->cset.entries.next)
642 		of_changeset_destroy(&ovcs->cset);
643 
644 	if (ovcs->id)
645 		idr_remove(&ovcs_idr, ovcs->id);
646 
647 	for (i = 0; i < ovcs->count; i++) {
648 		of_node_put(ovcs->fragments[i].target);
649 		of_node_put(ovcs->fragments[i].overlay);
650 	}
651 	kfree(ovcs->fragments);
652 
653 	/*
654 	 * TODO
655 	 *
656 	 * would like to: kfree(ovcs->overlay_tree);
657 	 * but can not since drivers may have pointers into this data
658 	 *
659 	 * would like to: kfree(ovcs->fdt);
660 	 * but can not since drivers may have pointers into this data
661 	 */
662 
663 	kfree(ovcs);
664 }
665 
666 /*
667  * internal documentation
668  *
669  * of_overlay_apply() - Create and apply an overlay changeset
670  * @fdt:	the FDT that was unflattened to create @tree
671  * @tree:	Expanded overlay device tree
672  * @ovcs_id:	Pointer to overlay changeset id
673  *
674  * Creates and applies an overlay changeset.
675  *
676  * If an error occurs in a pre-apply notifier, then no changes are made
677  * to the device tree.
678  *
679 
680  * A non-zero return value will not have created the changeset if error is from:
681  *   - parameter checks
682  *   - building the changeset
683  *   - overlay changeset pre-apply notifier
684  *
685  * If an error is returned by an overlay changeset pre-apply notifier
686  * then no further overlay changeset pre-apply notifier will be called.
687  *
688  * A non-zero return value will have created the changeset if error is from:
689  *   - overlay changeset entry notifier
690  *   - overlay changeset post-apply notifier
691  *
692  * If an error is returned by an overlay changeset post-apply notifier
693  * then no further overlay changeset post-apply notifier will be called.
694  *
695  * If more than one notifier returns an error, then the last notifier
696  * error to occur is returned.
697  *
698  * If an error occurred while applying the overlay changeset, then an
699  * attempt is made to revert any changes that were made to the
700  * device tree.  If there were any errors during the revert attempt
701  * then the state of the device tree can not be determined, and any
702  * following attempt to apply or remove an overlay changeset will be
703  * refused.
704  *
705  * Returns 0 on success, or a negative error number.  Overlay changeset
706  * id is returned to *ovcs_id.
707  */
708 
709 static int of_overlay_apply(const void *fdt, struct device_node *tree,
710 		int *ovcs_id)
711 {
712 	struct overlay_changeset *ovcs;
713 	int ret = 0, ret_revert, ret_tmp;
714 
715 	/*
716 	 * As of this point, fdt and tree belong to the overlay changeset.
717 	 * overlay changeset code is responsible for freeing them.
718 	 */
719 
720 	if (devicetree_corrupt()) {
721 		pr_err("devicetree state suspect, refuse to apply overlay\n");
722 		kfree(fdt);
723 		kfree(tree);
724 		ret = -EBUSY;
725 		goto out;
726 	}
727 
728 	ovcs = kzalloc(sizeof(*ovcs), GFP_KERNEL);
729 	if (!ovcs) {
730 		kfree(fdt);
731 		kfree(tree);
732 		ret = -ENOMEM;
733 		goto out;
734 	}
735 
736 	of_overlay_mutex_lock();
737 	mutex_lock(&of_mutex);
738 
739 	ret = of_resolve_phandles(tree);
740 	if (ret)
741 		goto err_free_tree;
742 
743 	ret = init_overlay_changeset(ovcs, fdt, tree);
744 	if (ret)
745 		goto err_free_tree;
746 
747 	/*
748 	 * after overlay_notify(), ovcs->overlay_tree related pointers may have
749 	 * leaked to drivers, so can not kfree() tree, aka ovcs->overlay_tree;
750 	 * and can not free fdt, aka ovcs->fdt
751 	 */
752 	ret = overlay_notify(ovcs, OF_OVERLAY_PRE_APPLY);
753 	if (ret) {
754 		pr_err("overlay changeset pre-apply notify error %d\n", ret);
755 		goto err_free_overlay_changeset;
756 	}
757 
758 	ret = build_changeset(ovcs);
759 	if (ret)
760 		goto err_free_overlay_changeset;
761 
762 	ret_revert = 0;
763 	ret = __of_changeset_apply_entries(&ovcs->cset, &ret_revert);
764 	if (ret) {
765 		if (ret_revert) {
766 			pr_debug("overlay changeset revert error %d\n",
767 				 ret_revert);
768 			devicetree_state_flags |= DTSF_APPLY_FAIL;
769 		}
770 		goto err_free_overlay_changeset;
771 	}
772 
773 	ret = __of_changeset_apply_notify(&ovcs->cset);
774 	if (ret)
775 		pr_err("overlay changeset entry notify error %d\n", ret);
776 	/* notify failure is not fatal, continue */
777 
778 	list_add_tail(&ovcs->ovcs_list, &ovcs_list);
779 	*ovcs_id = ovcs->id;
780 
781 	ret_tmp = overlay_notify(ovcs, OF_OVERLAY_POST_APPLY);
782 	if (ret_tmp) {
783 		pr_err("overlay changeset post-apply notify error %d\n",
784 		       ret_tmp);
785 		if (!ret)
786 			ret = ret_tmp;
787 	}
788 
789 	goto out_unlock;
790 
791 err_free_tree:
792 	kfree(fdt);
793 	kfree(tree);
794 
795 err_free_overlay_changeset:
796 	free_overlay_changeset(ovcs);
797 
798 out_unlock:
799 	mutex_unlock(&of_mutex);
800 	of_overlay_mutex_unlock();
801 
802 out:
803 	pr_debug("%s() err=%d\n", __func__, ret);
804 
805 	return ret;
806 }
807 
808 int of_overlay_fdt_apply(const void *overlay_fdt, u32 overlay_fdt_size,
809 			 int *ovcs_id)
810 {
811 	const void *new_fdt;
812 	int ret;
813 	u32 size;
814 	struct device_node *overlay_root;
815 
816 	*ovcs_id = 0;
817 	ret = 0;
818 
819 	if (overlay_fdt_size < sizeof(struct fdt_header) ||
820 	    fdt_check_header(overlay_fdt)) {
821 		pr_err("Invalid overlay_fdt header\n");
822 		return -EINVAL;
823 	}
824 
825 	size = fdt_totalsize(overlay_fdt);
826 	if (overlay_fdt_size < size)
827 		return -EINVAL;
828 
829 	/*
830 	 * Must create permanent copy of FDT because of_fdt_unflatten_tree()
831 	 * will create pointers to the passed in FDT in the unflattened tree.
832 	 */
833 	new_fdt = kmemdup(overlay_fdt, size, GFP_KERNEL);
834 	if (!new_fdt)
835 		return -ENOMEM;
836 
837 	of_fdt_unflatten_tree(new_fdt, NULL, &overlay_root);
838 	if (!overlay_root) {
839 		pr_err("unable to unflatten overlay_fdt\n");
840 		ret = -EINVAL;
841 		goto out_free_new_fdt;
842 	}
843 
844 	ret = of_overlay_apply(new_fdt, overlay_root, ovcs_id);
845 	if (ret < 0) {
846 		/*
847 		 * new_fdt and overlay_root now belong to the overlay
848 		 * changeset.
849 		 * overlay changeset code is responsible for freeing them.
850 		 */
851 		goto out;
852 	}
853 
854 	return 0;
855 
856 
857 out_free_new_fdt:
858 	kfree(new_fdt);
859 
860 out:
861 	return ret;
862 }
863 EXPORT_SYMBOL_GPL(of_overlay_fdt_apply);
864 
865 /*
866  * Find @np in @tree.
867  *
868  * Returns 1 if @np is @tree or is contained in @tree, else 0
869  */
870 static int find_node(struct device_node *tree, struct device_node *np)
871 {
872 	struct device_node *child;
873 
874 	if (tree == np)
875 		return 1;
876 
877 	for_each_child_of_node(tree, child) {
878 		if (find_node(child, np)) {
879 			of_node_put(child);
880 			return 1;
881 		}
882 	}
883 
884 	return 0;
885 }
886 
887 /*
888  * Is @remove_ce_node a child of, a parent of, or the same as any
889  * node in an overlay changeset more topmost than @remove_ovcs?
890  *
891  * Returns 1 if found, else 0
892  */
893 static int node_overlaps_later_cs(struct overlay_changeset *remove_ovcs,
894 		struct device_node *remove_ce_node)
895 {
896 	struct overlay_changeset *ovcs;
897 	struct of_changeset_entry *ce;
898 
899 	list_for_each_entry_reverse(ovcs, &ovcs_list, ovcs_list) {
900 		if (ovcs == remove_ovcs)
901 			break;
902 
903 		list_for_each_entry(ce, &ovcs->cset.entries, node) {
904 			if (find_node(ce->np, remove_ce_node)) {
905 				pr_err("%s: #%d overlaps with #%d @%pOF\n",
906 					__func__, remove_ovcs->id, ovcs->id,
907 					remove_ce_node);
908 				return 1;
909 			}
910 			if (find_node(remove_ce_node, ce->np)) {
911 				pr_err("%s: #%d overlaps with #%d @%pOF\n",
912 					__func__, remove_ovcs->id, ovcs->id,
913 					remove_ce_node);
914 				return 1;
915 			}
916 		}
917 	}
918 
919 	return 0;
920 }
921 
922 /*
923  * We can safely remove the overlay only if it's the top-most one.
924  * Newly applied overlays are inserted at the tail of the overlay list,
925  * so a top most overlay is the one that is closest to the tail.
926  *
927  * The topmost check is done by exploiting this property. For each
928  * affected device node in the log list we check if this overlay is
929  * the one closest to the tail. If another overlay has affected this
930  * device node and is closest to the tail, then removal is not permited.
931  */
932 static int overlay_removal_is_ok(struct overlay_changeset *remove_ovcs)
933 {
934 	struct of_changeset_entry *remove_ce;
935 
936 	list_for_each_entry(remove_ce, &remove_ovcs->cset.entries, node) {
937 		if (node_overlaps_later_cs(remove_ovcs, remove_ce->np)) {
938 			pr_err("overlay #%d is not topmost\n", remove_ovcs->id);
939 			return 0;
940 		}
941 	}
942 
943 	return 1;
944 }
945 
946 /**
947  * of_overlay_remove() - Revert and free an overlay changeset
948  * @ovcs_id:	Pointer to overlay changeset id
949  *
950  * Removes an overlay if it is permissible.  @ovcs_id was previously returned
951  * by of_overlay_apply().
952  *
953  * If an error occurred while attempting to revert the overlay changeset,
954  * then an attempt is made to re-apply any changeset entry that was
955  * reverted.  If an error occurs on re-apply then the state of the device
956  * tree can not be determined, and any following attempt to apply or remove
957  * an overlay changeset will be refused.
958  *
959  * A non-zero return value will not revert the changeset if error is from:
960  *   - parameter checks
961  *   - overlay changeset pre-remove notifier
962  *   - overlay changeset entry revert
963  *
964  * If an error is returned by an overlay changeset pre-remove notifier
965  * then no further overlay changeset pre-remove notifier will be called.
966  *
967  * If more than one notifier returns an error, then the last notifier
968  * error to occur is returned.
969  *
970  * A non-zero return value will revert the changeset if error is from:
971  *   - overlay changeset entry notifier
972  *   - overlay changeset post-remove notifier
973  *
974  * If an error is returned by an overlay changeset post-remove notifier
975  * then no further overlay changeset post-remove notifier will be called.
976  *
977  * Returns 0 on success, or a negative error number.  *ovcs_id is set to
978  * zero after reverting the changeset, even if a subsequent error occurs.
979  */
980 int of_overlay_remove(int *ovcs_id)
981 {
982 	struct overlay_changeset *ovcs;
983 	int ret, ret_apply, ret_tmp;
984 
985 	ret = 0;
986 
987 	if (devicetree_corrupt()) {
988 		pr_err("suspect devicetree state, refuse to remove overlay\n");
989 		ret = -EBUSY;
990 		goto out;
991 	}
992 
993 	mutex_lock(&of_mutex);
994 
995 	ovcs = idr_find(&ovcs_idr, *ovcs_id);
996 	if (!ovcs) {
997 		ret = -ENODEV;
998 		pr_err("remove: Could not find overlay #%d\n", *ovcs_id);
999 		goto out_unlock;
1000 	}
1001 
1002 	if (!overlay_removal_is_ok(ovcs)) {
1003 		ret = -EBUSY;
1004 		goto out_unlock;
1005 	}
1006 
1007 	ret = overlay_notify(ovcs, OF_OVERLAY_PRE_REMOVE);
1008 	if (ret) {
1009 		pr_err("overlay changeset pre-remove notify error %d\n", ret);
1010 		goto out_unlock;
1011 	}
1012 
1013 	list_del(&ovcs->ovcs_list);
1014 
1015 	ret_apply = 0;
1016 	ret = __of_changeset_revert_entries(&ovcs->cset, &ret_apply);
1017 	if (ret) {
1018 		if (ret_apply)
1019 			devicetree_state_flags |= DTSF_REVERT_FAIL;
1020 		goto out_unlock;
1021 	}
1022 
1023 	ret = __of_changeset_revert_notify(&ovcs->cset);
1024 	if (ret)
1025 		pr_err("overlay changeset entry notify error %d\n", ret);
1026 	/* notify failure is not fatal, continue */
1027 
1028 	*ovcs_id = 0;
1029 
1030 	ret_tmp = overlay_notify(ovcs, OF_OVERLAY_POST_REMOVE);
1031 	if (ret_tmp) {
1032 		pr_err("overlay changeset post-remove notify error %d\n",
1033 		       ret_tmp);
1034 		if (!ret)
1035 			ret = ret_tmp;
1036 	}
1037 
1038 	free_overlay_changeset(ovcs);
1039 
1040 out_unlock:
1041 	mutex_unlock(&of_mutex);
1042 
1043 out:
1044 	pr_debug("%s() err=%d\n", __func__, ret);
1045 
1046 	return ret;
1047 }
1048 EXPORT_SYMBOL_GPL(of_overlay_remove);
1049 
1050 /**
1051  * of_overlay_remove_all() - Reverts and frees all overlay changesets
1052  *
1053  * Removes all overlays from the system in the correct order.
1054  *
1055  * Returns 0 on success, or a negative error number
1056  */
1057 int of_overlay_remove_all(void)
1058 {
1059 	struct overlay_changeset *ovcs, *ovcs_n;
1060 	int ret;
1061 
1062 	/* the tail of list is guaranteed to be safe to remove */
1063 	list_for_each_entry_safe_reverse(ovcs, ovcs_n, &ovcs_list, ovcs_list) {
1064 		ret = of_overlay_remove(&ovcs->id);
1065 		if (ret)
1066 			return ret;
1067 	}
1068 
1069 	return 0;
1070 }
1071 EXPORT_SYMBOL_GPL(of_overlay_remove_all);
1072