xref: /openbmc/linux/drivers/of/overlay.c (revision 74de3792)
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 target - info about current target node as recursing through overlay
28  * @np:			node where current level of overlay will be applied
29  * @in_livetree:	@np is a node in the live devicetree
30  *
31  * Used in the algorithm to create the portion of a changeset that describes
32  * an overlay fragment, which is a devicetree subtree.  Initially @np is a node
33  * in the live devicetree where the overlay subtree is targeted to be grafted
34  * into.  When recursing to the next level of the overlay subtree, the target
35  * also recurses to the next level of the live devicetree, as long as overlay
36  * subtree node also exists in the live devicetree.  When a node in the overlay
37  * subtree does not exist at the same level in the live devicetree, target->np
38  * points to a newly allocated node, and all subsequent targets in the subtree
39  * will be newly allocated nodes.
40  */
41 struct target {
42 	struct device_node *np;
43 	bool in_livetree;
44 };
45 
46 /**
47  * struct fragment - info about fragment nodes in overlay expanded device tree
48  * @target:	target of the overlay operation
49  * @overlay:	pointer to the __overlay__ node
50  */
51 struct fragment {
52 	struct device_node *overlay;
53 	struct device_node *target;
54 };
55 
56 /**
57  * struct overlay_changeset
58  * @id:			changeset identifier
59  * @ovcs_list:		list on which we are located
60  * @new_fdt:		Memory allocated to hold unflattened aligned FDT
61  * @overlay_mem:	the memory chunk that contains @overlay_root
62  * @overlay_root:	expanded device tree that contains the fragment nodes
63  * @notify_state:	most recent notify action used on overlay
64  * @count:		count of fragment structures
65  * @fragments:		fragment nodes in the overlay expanded device tree
66  * @symbols_fragment:	last element of @fragments[] is the  __symbols__ node
67  * @cset:		changeset to apply fragments to live device tree
68  */
69 struct overlay_changeset {
70 	int id;
71 	struct list_head ovcs_list;
72 	const void *new_fdt;
73 	const void *overlay_mem;
74 	struct device_node *overlay_root;
75 	enum of_overlay_notify_action notify_state;
76 	int count;
77 	struct fragment *fragments;
78 	bool symbols_fragment;
79 	struct of_changeset cset;
80 };
81 
82 /* flags are sticky - once set, do not reset */
83 static int devicetree_state_flags;
84 #define DTSF_APPLY_FAIL		0x01
85 #define DTSF_REVERT_FAIL	0x02
86 
87 /*
88  * If a changeset apply or revert encounters an error, an attempt will
89  * be made to undo partial changes, but may fail.  If the undo fails
90  * we do not know the state of the devicetree.
91  */
92 static int devicetree_corrupt(void)
93 {
94 	return devicetree_state_flags &
95 		(DTSF_APPLY_FAIL | DTSF_REVERT_FAIL);
96 }
97 
98 static int build_changeset_next_level(struct overlay_changeset *ovcs,
99 		struct target *target, const struct device_node *overlay_node);
100 
101 /*
102  * of_resolve_phandles() finds the largest phandle in the live tree.
103  * of_overlay_apply() may add a larger phandle to the live tree.
104  * Do not allow race between two overlays being applied simultaneously:
105  *    mutex_lock(&of_overlay_phandle_mutex)
106  *    of_resolve_phandles()
107  *    of_overlay_apply()
108  *    mutex_unlock(&of_overlay_phandle_mutex)
109  */
110 static DEFINE_MUTEX(of_overlay_phandle_mutex);
111 
112 void of_overlay_mutex_lock(void)
113 {
114 	mutex_lock(&of_overlay_phandle_mutex);
115 }
116 
117 void of_overlay_mutex_unlock(void)
118 {
119 	mutex_unlock(&of_overlay_phandle_mutex);
120 }
121 
122 static LIST_HEAD(ovcs_list);
123 static DEFINE_IDR(ovcs_idr);
124 
125 static BLOCKING_NOTIFIER_HEAD(overlay_notify_chain);
126 
127 /**
128  * of_overlay_notifier_register() - Register notifier for overlay operations
129  * @nb:		Notifier block to register
130  *
131  * Register for notification on overlay operations on device tree nodes. The
132  * reported actions definied by @of_reconfig_change. The notifier callback
133  * furthermore receives a pointer to the affected device tree node.
134  *
135  * Note that a notifier callback is not supposed to store pointers to a device
136  * tree node or its content beyond @OF_OVERLAY_POST_REMOVE corresponding to the
137  * respective node it received.
138  */
139 int of_overlay_notifier_register(struct notifier_block *nb)
140 {
141 	return blocking_notifier_chain_register(&overlay_notify_chain, nb);
142 }
143 EXPORT_SYMBOL_GPL(of_overlay_notifier_register);
144 
145 /**
146  * of_overlay_notifier_unregister() - Unregister notifier for overlay operations
147  * @nb:		Notifier block to unregister
148  */
149 int of_overlay_notifier_unregister(struct notifier_block *nb)
150 {
151 	return blocking_notifier_chain_unregister(&overlay_notify_chain, nb);
152 }
153 EXPORT_SYMBOL_GPL(of_overlay_notifier_unregister);
154 
155 static char *of_overlay_action_name[] = {
156 	"pre-apply",
157 	"post-apply",
158 	"pre-remove",
159 	"post-remove",
160 };
161 
162 static int overlay_notify(struct overlay_changeset *ovcs,
163 		enum of_overlay_notify_action action)
164 {
165 	struct of_overlay_notify_data nd;
166 	int i, ret;
167 
168 	ovcs->notify_state = action;
169 
170 	for (i = 0; i < ovcs->count; i++) {
171 		struct fragment *fragment = &ovcs->fragments[i];
172 
173 		nd.target = fragment->target;
174 		nd.overlay = fragment->overlay;
175 
176 		ret = blocking_notifier_call_chain(&overlay_notify_chain,
177 						   action, &nd);
178 		if (notifier_to_errno(ret)) {
179 			ret = notifier_to_errno(ret);
180 			pr_err("overlay changeset %s notifier error %d, target: %pOF\n",
181 			       of_overlay_action_name[action], ret, nd.target);
182 			return ret;
183 		}
184 	}
185 
186 	return 0;
187 }
188 
189 /*
190  * The values of properties in the "/__symbols__" node are paths in
191  * the ovcs->overlay_root.  When duplicating the properties, the paths
192  * need to be adjusted to be the correct path for the live device tree.
193  *
194  * The paths refer to a node in the subtree of a fragment node's "__overlay__"
195  * node, for example "/fragment@0/__overlay__/symbol_path_tail",
196  * where symbol_path_tail can be a single node or it may be a multi-node path.
197  *
198  * The duplicated property value will be modified by replacing the
199  * "/fragment_name/__overlay/" portion of the value  with the target
200  * path from the fragment node.
201  */
202 static struct property *dup_and_fixup_symbol_prop(
203 		struct overlay_changeset *ovcs, const struct property *prop)
204 {
205 	struct fragment *fragment;
206 	struct property *new_prop;
207 	struct device_node *fragment_node;
208 	struct device_node *overlay_node;
209 	const char *path;
210 	const char *path_tail;
211 	const char *target_path;
212 	int k;
213 	int overlay_name_len;
214 	int path_len;
215 	int path_tail_len;
216 	int target_path_len;
217 
218 	if (!prop->value)
219 		return NULL;
220 	if (strnlen(prop->value, prop->length) >= prop->length)
221 		return NULL;
222 	path = prop->value;
223 	path_len = strlen(path);
224 
225 	if (path_len < 1)
226 		return NULL;
227 	fragment_node = __of_find_node_by_path(ovcs->overlay_root, path + 1);
228 	overlay_node = __of_find_node_by_path(fragment_node, "__overlay__/");
229 	of_node_put(fragment_node);
230 	of_node_put(overlay_node);
231 
232 	for (k = 0; k < ovcs->count; k++) {
233 		fragment = &ovcs->fragments[k];
234 		if (fragment->overlay == overlay_node)
235 			break;
236 	}
237 	if (k >= ovcs->count)
238 		return NULL;
239 
240 	overlay_name_len = snprintf(NULL, 0, "%pOF", fragment->overlay);
241 
242 	if (overlay_name_len > path_len)
243 		return NULL;
244 	path_tail = path + overlay_name_len;
245 	path_tail_len = strlen(path_tail);
246 
247 	target_path = kasprintf(GFP_KERNEL, "%pOF", fragment->target);
248 	if (!target_path)
249 		return NULL;
250 	target_path_len = strlen(target_path);
251 
252 	new_prop = kzalloc(sizeof(*new_prop), GFP_KERNEL);
253 	if (!new_prop)
254 		goto err_free_target_path;
255 
256 	new_prop->name = kstrdup(prop->name, GFP_KERNEL);
257 	new_prop->length = target_path_len + path_tail_len + 1;
258 	new_prop->value = kzalloc(new_prop->length, GFP_KERNEL);
259 	if (!new_prop->name || !new_prop->value)
260 		goto err_free_new_prop;
261 
262 	strcpy(new_prop->value, target_path);
263 	strcpy(new_prop->value + target_path_len, path_tail);
264 
265 	of_property_set_flag(new_prop, OF_DYNAMIC);
266 
267 	kfree(target_path);
268 
269 	return new_prop;
270 
271 err_free_new_prop:
272 	kfree(new_prop->name);
273 	kfree(new_prop->value);
274 	kfree(new_prop);
275 err_free_target_path:
276 	kfree(target_path);
277 
278 	return NULL;
279 }
280 
281 /**
282  * add_changeset_property() - add @overlay_prop to overlay changeset
283  * @ovcs:		overlay changeset
284  * @target:		where @overlay_prop will be placed
285  * @overlay_prop:	property to add or update, from overlay tree
286  * @is_symbols_prop:	1 if @overlay_prop is from node "/__symbols__"
287  *
288  * If @overlay_prop does not already exist in live devicetree, add changeset
289  * entry to add @overlay_prop in @target, else add changeset entry to update
290  * value of @overlay_prop.
291  *
292  * @target may be either in the live devicetree or in a new subtree that
293  * is contained in the changeset.
294  *
295  * Some special properties are not added or updated (no error returned):
296  * "name", "phandle", "linux,phandle".
297  *
298  * Properties "#address-cells" and "#size-cells" are not updated if they
299  * are already in the live tree, but if present in the live tree, the values
300  * in the overlay must match the values in the live tree.
301  *
302  * Update of property in symbols node is not allowed.
303  *
304  * Return: 0 on success, -ENOMEM if memory allocation failure, or -EINVAL if
305  * invalid @overlay.
306  */
307 static int add_changeset_property(struct overlay_changeset *ovcs,
308 		struct target *target, struct property *overlay_prop,
309 		bool is_symbols_prop)
310 {
311 	struct property *new_prop = NULL, *prop;
312 	int ret = 0;
313 
314 	if (target->in_livetree)
315 		if (!of_prop_cmp(overlay_prop->name, "name") ||
316 		    !of_prop_cmp(overlay_prop->name, "phandle") ||
317 		    !of_prop_cmp(overlay_prop->name, "linux,phandle"))
318 			return 0;
319 
320 	if (target->in_livetree)
321 		prop = of_find_property(target->np, overlay_prop->name, NULL);
322 	else
323 		prop = NULL;
324 
325 	if (prop) {
326 		if (!of_prop_cmp(prop->name, "#address-cells")) {
327 			if (!of_prop_val_eq(prop, overlay_prop)) {
328 				pr_err("ERROR: changing value of #address-cells is not allowed in %pOF\n",
329 				       target->np);
330 				ret = -EINVAL;
331 			}
332 			return ret;
333 
334 		} else if (!of_prop_cmp(prop->name, "#size-cells")) {
335 			if (!of_prop_val_eq(prop, overlay_prop)) {
336 				pr_err("ERROR: changing value of #size-cells is not allowed in %pOF\n",
337 				       target->np);
338 				ret = -EINVAL;
339 			}
340 			return ret;
341 		}
342 	}
343 
344 	if (is_symbols_prop) {
345 		if (prop)
346 			return -EINVAL;
347 		new_prop = dup_and_fixup_symbol_prop(ovcs, overlay_prop);
348 	} else {
349 		new_prop = __of_prop_dup(overlay_prop, GFP_KERNEL);
350 	}
351 
352 	if (!new_prop)
353 		return -ENOMEM;
354 
355 	if (!prop) {
356 		if (!target->in_livetree) {
357 			new_prop->next = target->np->deadprops;
358 			target->np->deadprops = new_prop;
359 		}
360 		ret = of_changeset_add_property(&ovcs->cset, target->np,
361 						new_prop);
362 	} else {
363 		ret = of_changeset_update_property(&ovcs->cset, target->np,
364 						   new_prop);
365 	}
366 
367 	if (!of_node_check_flag(target->np, OF_OVERLAY))
368 		pr_err("WARNING: memory leak will occur if overlay removed, property: %pOF/%s\n",
369 		       target->np, new_prop->name);
370 
371 	if (ret) {
372 		kfree(new_prop->name);
373 		kfree(new_prop->value);
374 		kfree(new_prop);
375 	}
376 	return ret;
377 }
378 
379 /**
380  * add_changeset_node() - add @node (and children) to overlay changeset
381  * @ovcs:	overlay changeset
382  * @target:	where @node will be placed in live tree or changeset
383  * @node:	node from within overlay device tree fragment
384  *
385  * If @node does not already exist in @target, add changeset entry
386  * to add @node in @target.
387  *
388  * If @node already exists in @target, and the existing node has
389  * a phandle, the overlay node is not allowed to have a phandle.
390  *
391  * If @node has child nodes, add the children recursively via
392  * build_changeset_next_level().
393  *
394  * NOTE_1: A live devicetree created from a flattened device tree (FDT) will
395  *       not contain the full path in node->full_name.  Thus an overlay
396  *       created from an FDT also will not contain the full path in
397  *       node->full_name.  However, a live devicetree created from Open
398  *       Firmware may have the full path in node->full_name.
399  *
400  *       add_changeset_node() follows the FDT convention and does not include
401  *       the full path in node->full_name.  Even though it expects the overlay
402  *       to not contain the full path, it uses kbasename() to remove the
403  *       full path should it exist.  It also uses kbasename() in comparisons
404  *       to nodes in the live devicetree so that it can apply an overlay to
405  *       a live devicetree created from Open Firmware.
406  *
407  * NOTE_2: Multiple mods of created nodes not supported.
408  *
409  * Return: 0 on success, -ENOMEM if memory allocation failure, or -EINVAL if
410  * invalid @overlay.
411  */
412 static int add_changeset_node(struct overlay_changeset *ovcs,
413 		struct target *target, struct device_node *node)
414 {
415 	const char *node_kbasename;
416 	const __be32 *phandle;
417 	struct device_node *tchild;
418 	struct target target_child;
419 	int ret = 0, size;
420 
421 	node_kbasename = kbasename(node->full_name);
422 
423 	for_each_child_of_node(target->np, tchild)
424 		if (!of_node_cmp(node_kbasename, kbasename(tchild->full_name)))
425 			break;
426 
427 	if (!tchild) {
428 		tchild = __of_node_dup(NULL, node_kbasename);
429 		if (!tchild)
430 			return -ENOMEM;
431 
432 		tchild->parent = target->np;
433 		tchild->name = __of_get_property(node, "name", NULL);
434 
435 		if (!tchild->name)
436 			tchild->name = "<NULL>";
437 
438 		/* ignore obsolete "linux,phandle" */
439 		phandle = __of_get_property(node, "phandle", &size);
440 		if (phandle && (size == 4))
441 			tchild->phandle = be32_to_cpup(phandle);
442 
443 		of_node_set_flag(tchild, OF_OVERLAY);
444 
445 		ret = of_changeset_attach_node(&ovcs->cset, tchild);
446 		if (ret)
447 			return ret;
448 
449 		target_child.np = tchild;
450 		target_child.in_livetree = false;
451 
452 		ret = build_changeset_next_level(ovcs, &target_child, node);
453 		of_node_put(tchild);
454 		return ret;
455 	}
456 
457 	if (node->phandle && tchild->phandle) {
458 		ret = -EINVAL;
459 	} else {
460 		target_child.np = tchild;
461 		target_child.in_livetree = target->in_livetree;
462 		ret = build_changeset_next_level(ovcs, &target_child, node);
463 	}
464 	of_node_put(tchild);
465 
466 	return ret;
467 }
468 
469 /**
470  * build_changeset_next_level() - add level of overlay changeset
471  * @ovcs:		overlay changeset
472  * @target:		where to place @overlay_node in live tree
473  * @overlay_node:	node from within an overlay device tree fragment
474  *
475  * Add the properties (if any) and nodes (if any) from @overlay_node to the
476  * @ovcs->cset changeset.  If an added node has child nodes, they will
477  * be added recursively.
478  *
479  * Do not allow symbols node to have any children.
480  *
481  * Return: 0 on success, -ENOMEM if memory allocation failure, or -EINVAL if
482  * invalid @overlay_node.
483  */
484 static int build_changeset_next_level(struct overlay_changeset *ovcs,
485 		struct target *target, const struct device_node *overlay_node)
486 {
487 	struct device_node *child;
488 	struct property *prop;
489 	int ret;
490 
491 	for_each_property_of_node(overlay_node, prop) {
492 		ret = add_changeset_property(ovcs, target, prop, 0);
493 		if (ret) {
494 			pr_debug("Failed to apply prop @%pOF/%s, err=%d\n",
495 				 target->np, prop->name, ret);
496 			return ret;
497 		}
498 	}
499 
500 	for_each_child_of_node(overlay_node, child) {
501 		ret = add_changeset_node(ovcs, target, child);
502 		if (ret) {
503 			pr_debug("Failed to apply node @%pOF/%pOFn, err=%d\n",
504 				 target->np, child, ret);
505 			of_node_put(child);
506 			return ret;
507 		}
508 	}
509 
510 	return 0;
511 }
512 
513 /*
514  * Add the properties from __overlay__ node to the @ovcs->cset changeset.
515  */
516 static int build_changeset_symbols_node(struct overlay_changeset *ovcs,
517 		struct target *target,
518 		const struct device_node *overlay_symbols_node)
519 {
520 	struct property *prop;
521 	int ret;
522 
523 	for_each_property_of_node(overlay_symbols_node, prop) {
524 		ret = add_changeset_property(ovcs, target, prop, 1);
525 		if (ret) {
526 			pr_debug("Failed to apply symbols prop @%pOF/%s, err=%d\n",
527 				 target->np, prop->name, ret);
528 			return ret;
529 		}
530 	}
531 
532 	return 0;
533 }
534 
535 static int find_dup_cset_node_entry(struct overlay_changeset *ovcs,
536 		struct of_changeset_entry *ce_1)
537 {
538 	struct of_changeset_entry *ce_2;
539 	char *fn_1, *fn_2;
540 	int node_path_match;
541 
542 	if (ce_1->action != OF_RECONFIG_ATTACH_NODE &&
543 	    ce_1->action != OF_RECONFIG_DETACH_NODE)
544 		return 0;
545 
546 	ce_2 = ce_1;
547 	list_for_each_entry_continue(ce_2, &ovcs->cset.entries, node) {
548 		if ((ce_2->action != OF_RECONFIG_ATTACH_NODE &&
549 		     ce_2->action != OF_RECONFIG_DETACH_NODE) ||
550 		    of_node_cmp(ce_1->np->full_name, ce_2->np->full_name))
551 			continue;
552 
553 		fn_1 = kasprintf(GFP_KERNEL, "%pOF", ce_1->np);
554 		fn_2 = kasprintf(GFP_KERNEL, "%pOF", ce_2->np);
555 		node_path_match = !strcmp(fn_1, fn_2);
556 		kfree(fn_1);
557 		kfree(fn_2);
558 		if (node_path_match) {
559 			pr_err("ERROR: multiple fragments add and/or delete node %pOF\n",
560 			       ce_1->np);
561 			return -EINVAL;
562 		}
563 	}
564 
565 	return 0;
566 }
567 
568 static int find_dup_cset_prop(struct overlay_changeset *ovcs,
569 		struct of_changeset_entry *ce_1)
570 {
571 	struct of_changeset_entry *ce_2;
572 	char *fn_1, *fn_2;
573 	int node_path_match;
574 
575 	if (ce_1->action != OF_RECONFIG_ADD_PROPERTY &&
576 	    ce_1->action != OF_RECONFIG_REMOVE_PROPERTY &&
577 	    ce_1->action != OF_RECONFIG_UPDATE_PROPERTY)
578 		return 0;
579 
580 	ce_2 = ce_1;
581 	list_for_each_entry_continue(ce_2, &ovcs->cset.entries, node) {
582 		if ((ce_2->action != OF_RECONFIG_ADD_PROPERTY &&
583 		     ce_2->action != OF_RECONFIG_REMOVE_PROPERTY &&
584 		     ce_2->action != OF_RECONFIG_UPDATE_PROPERTY) ||
585 		    of_node_cmp(ce_1->np->full_name, ce_2->np->full_name))
586 			continue;
587 
588 		fn_1 = kasprintf(GFP_KERNEL, "%pOF", ce_1->np);
589 		fn_2 = kasprintf(GFP_KERNEL, "%pOF", ce_2->np);
590 		node_path_match = !strcmp(fn_1, fn_2);
591 		kfree(fn_1);
592 		kfree(fn_2);
593 		if (node_path_match &&
594 		    !of_prop_cmp(ce_1->prop->name, ce_2->prop->name)) {
595 			pr_err("ERROR: multiple fragments add, update, and/or delete property %pOF/%s\n",
596 			       ce_1->np, ce_1->prop->name);
597 			return -EINVAL;
598 		}
599 	}
600 
601 	return 0;
602 }
603 
604 /**
605  * changeset_dup_entry_check() - check for duplicate entries
606  * @ovcs:	Overlay changeset
607  *
608  * Check changeset @ovcs->cset for multiple {add or delete} node entries for
609  * the same node or duplicate {add, delete, or update} properties entries
610  * for the same property.
611  *
612  * Return: 0 on success, or -EINVAL if duplicate changeset entry found.
613  */
614 static int changeset_dup_entry_check(struct overlay_changeset *ovcs)
615 {
616 	struct of_changeset_entry *ce_1;
617 	int dup_entry = 0;
618 
619 	list_for_each_entry(ce_1, &ovcs->cset.entries, node) {
620 		dup_entry |= find_dup_cset_node_entry(ovcs, ce_1);
621 		dup_entry |= find_dup_cset_prop(ovcs, ce_1);
622 	}
623 
624 	return dup_entry ? -EINVAL : 0;
625 }
626 
627 /**
628  * build_changeset() - populate overlay changeset in @ovcs from @ovcs->fragments
629  * @ovcs:	Overlay changeset
630  *
631  * Create changeset @ovcs->cset to contain the nodes and properties of the
632  * overlay device tree fragments in @ovcs->fragments[].  If an error occurs,
633  * any portions of the changeset that were successfully created will remain
634  * in @ovcs->cset.
635  *
636  * Return: 0 on success, -ENOMEM if memory allocation failure, or -EINVAL if
637  * invalid overlay in @ovcs->fragments[].
638  */
639 static int build_changeset(struct overlay_changeset *ovcs)
640 {
641 	struct fragment *fragment;
642 	struct target target;
643 	int fragments_count, i, ret;
644 
645 	/*
646 	 * if there is a symbols fragment in ovcs->fragments[i] it is
647 	 * the final element in the array
648 	 */
649 	if (ovcs->symbols_fragment)
650 		fragments_count = ovcs->count - 1;
651 	else
652 		fragments_count = ovcs->count;
653 
654 	for (i = 0; i < fragments_count; i++) {
655 		fragment = &ovcs->fragments[i];
656 
657 		target.np = fragment->target;
658 		target.in_livetree = true;
659 		ret = build_changeset_next_level(ovcs, &target,
660 						 fragment->overlay);
661 		if (ret) {
662 			pr_debug("fragment apply failed '%pOF'\n",
663 				 fragment->target);
664 			return ret;
665 		}
666 	}
667 
668 	if (ovcs->symbols_fragment) {
669 		fragment = &ovcs->fragments[ovcs->count - 1];
670 
671 		target.np = fragment->target;
672 		target.in_livetree = true;
673 		ret = build_changeset_symbols_node(ovcs, &target,
674 						   fragment->overlay);
675 		if (ret) {
676 			pr_debug("symbols fragment apply failed '%pOF'\n",
677 				 fragment->target);
678 			return ret;
679 		}
680 	}
681 
682 	return changeset_dup_entry_check(ovcs);
683 }
684 
685 /*
686  * Find the target node using a number of different strategies
687  * in order of preference:
688  *
689  * 1) "target" property containing the phandle of the target
690  * 2) "target-path" property containing the path of the target
691  */
692 static struct device_node *find_target(struct device_node *info_node)
693 {
694 	struct device_node *node;
695 	const char *path;
696 	u32 val;
697 	int ret;
698 
699 	ret = of_property_read_u32(info_node, "target", &val);
700 	if (!ret) {
701 		node = of_find_node_by_phandle(val);
702 		if (!node)
703 			pr_err("find target, node: %pOF, phandle 0x%x not found\n",
704 			       info_node, val);
705 		return node;
706 	}
707 
708 	ret = of_property_read_string(info_node, "target-path", &path);
709 	if (!ret) {
710 		node =  of_find_node_by_path(path);
711 		if (!node)
712 			pr_err("find target, node: %pOF, path '%s' not found\n",
713 			       info_node, path);
714 		return node;
715 	}
716 
717 	pr_err("find target, node: %pOF, no target property\n", info_node);
718 
719 	return NULL;
720 }
721 
722 /**
723  * init_overlay_changeset() - initialize overlay changeset from overlay tree
724  * @ovcs:		Overlay changeset to build
725  *
726  * Initialize @ovcs.  Populate @ovcs->fragments with node information from
727  * the top level of @overlay_root.  The relevant top level nodes are the
728  * fragment nodes and the __symbols__ node.  Any other top level node will
729  * be ignored.  Populate other @ovcs fields.
730  *
731  * Return: 0 on success, -ENOMEM if memory allocation failure, -EINVAL if error
732  * detected in @overlay_root.  On error return, the caller of
733  * init_overlay_changeset() must call free_overlay_changeset().
734  */
735 static int init_overlay_changeset(struct overlay_changeset *ovcs)
736 {
737 	struct device_node *node, *overlay_node;
738 	struct fragment *fragment;
739 	struct fragment *fragments;
740 	int cnt, ret;
741 
742 	/*
743 	 * None of the resources allocated by this function will be freed in
744 	 * the error paths.  Instead the caller of this function is required
745 	 * to call free_overlay_changeset() (which will free the resources)
746 	 * if error return.
747 	 */
748 
749 	/*
750 	 * Warn for some issues.  Can not return -EINVAL for these until
751 	 * of_unittest_apply_overlay() is fixed to pass these checks.
752 	 */
753 	if (!of_node_check_flag(ovcs->overlay_root, OF_DYNAMIC))
754 		pr_debug("%s() ovcs->overlay_root is not dynamic\n", __func__);
755 
756 	if (!of_node_check_flag(ovcs->overlay_root, OF_DETACHED))
757 		pr_debug("%s() ovcs->overlay_root is not detached\n", __func__);
758 
759 	if (!of_node_is_root(ovcs->overlay_root))
760 		pr_debug("%s() ovcs->overlay_root is not root\n", __func__);
761 
762 	of_changeset_init(&ovcs->cset);
763 
764 	cnt = 0;
765 
766 	/* fragment nodes */
767 	for_each_child_of_node(ovcs->overlay_root, node) {
768 		overlay_node = of_get_child_by_name(node, "__overlay__");
769 		if (overlay_node) {
770 			cnt++;
771 			of_node_put(overlay_node);
772 		}
773 	}
774 
775 	node = of_get_child_by_name(ovcs->overlay_root, "__symbols__");
776 	if (node) {
777 		cnt++;
778 		of_node_put(node);
779 	}
780 
781 	fragments = kcalloc(cnt, sizeof(*fragments), GFP_KERNEL);
782 	if (!fragments) {
783 		ret = -ENOMEM;
784 		goto err_out;
785 	}
786 	ovcs->fragments = fragments;
787 
788 	cnt = 0;
789 	for_each_child_of_node(ovcs->overlay_root, node) {
790 		overlay_node = of_get_child_by_name(node, "__overlay__");
791 		if (!overlay_node)
792 			continue;
793 
794 		fragment = &fragments[cnt];
795 		fragment->overlay = overlay_node;
796 		fragment->target = find_target(node);
797 		if (!fragment->target) {
798 			of_node_put(fragment->overlay);
799 			ret = -EINVAL;
800 			of_node_put(node);
801 			goto err_out;
802 		}
803 
804 		cnt++;
805 	}
806 
807 	/*
808 	 * if there is a symbols fragment in ovcs->fragments[i] it is
809 	 * the final element in the array
810 	 */
811 	node = of_get_child_by_name(ovcs->overlay_root, "__symbols__");
812 	if (node) {
813 		ovcs->symbols_fragment = 1;
814 		fragment = &fragments[cnt];
815 		fragment->overlay = node;
816 		fragment->target = of_find_node_by_path("/__symbols__");
817 
818 		if (!fragment->target) {
819 			pr_err("symbols in overlay, but not in live tree\n");
820 			ret = -EINVAL;
821 			goto err_out;
822 		}
823 
824 		cnt++;
825 	}
826 
827 	if (!cnt) {
828 		pr_err("no fragments or symbols in overlay\n");
829 		ret = -EINVAL;
830 		goto err_out;
831 	}
832 
833 	ovcs->count = cnt;
834 
835 	return 0;
836 
837 err_out:
838 	pr_err("%s() failed, ret = %d\n", __func__, ret);
839 
840 	return ret;
841 }
842 
843 static void free_overlay_changeset(struct overlay_changeset *ovcs)
844 {
845 	int i;
846 
847 	if (ovcs->cset.entries.next)
848 		of_changeset_destroy(&ovcs->cset);
849 
850 	if (ovcs->id) {
851 		idr_remove(&ovcs_idr, ovcs->id);
852 		list_del(&ovcs->ovcs_list);
853 		ovcs->id = 0;
854 	}
855 
856 
857 	for (i = 0; i < ovcs->count; i++) {
858 		of_node_put(ovcs->fragments[i].target);
859 		of_node_put(ovcs->fragments[i].overlay);
860 	}
861 	kfree(ovcs->fragments);
862 
863 	/*
864 	 * There should be no live pointers into ovcs->overlay_mem and
865 	 * ovcs->new_fdt due to the policy that overlay notifiers are not
866 	 * allowed to retain pointers into the overlay devicetree other
867 	 * than during the window from OF_OVERLAY_PRE_APPLY overlay
868 	 * notifiers until the OF_OVERLAY_POST_REMOVE overlay notifiers.
869 	 *
870 	 * A memory leak will occur here if within the window.
871 	 */
872 
873 	if (ovcs->notify_state == OF_OVERLAY_INIT ||
874 	    ovcs->notify_state == OF_OVERLAY_POST_REMOVE) {
875 		kfree(ovcs->overlay_mem);
876 		kfree(ovcs->new_fdt);
877 	}
878 	kfree(ovcs);
879 }
880 
881 /*
882  * internal documentation
883  *
884  * of_overlay_apply() - Create and apply an overlay changeset
885  * @ovcs:	overlay changeset
886  *
887  * Creates and applies an overlay changeset.
888  *
889  * If an error is returned by an overlay changeset pre-apply notifier
890  * then no further overlay changeset pre-apply notifier will be called.
891  *
892  * If an error is returned by an overlay changeset post-apply notifier
893  * then no further overlay changeset post-apply notifier will be called.
894  *
895  * If more than one notifier returns an error, then the last notifier
896  * error to occur is returned.
897  *
898  * If an error occurred while applying the overlay changeset, then an
899  * attempt is made to revert any changes that were made to the
900  * device tree.  If there were any errors during the revert attempt
901  * then the state of the device tree can not be determined, and any
902  * following attempt to apply or remove an overlay changeset will be
903  * refused.
904  *
905  * Returns 0 on success, or a negative error number.  On error return,
906  * the caller of of_overlay_apply() must call free_overlay_changeset().
907  */
908 
909 static int of_overlay_apply(struct overlay_changeset *ovcs)
910 {
911 	int ret = 0, ret_revert, ret_tmp;
912 
913 	if (devicetree_corrupt()) {
914 		pr_err("devicetree state suspect, refuse to apply overlay\n");
915 		ret = -EBUSY;
916 		goto out;
917 	}
918 
919 	ret = of_resolve_phandles(ovcs->overlay_root);
920 	if (ret)
921 		goto out;
922 
923 	ret = init_overlay_changeset(ovcs);
924 	if (ret)
925 		goto out;
926 
927 	ret = overlay_notify(ovcs, OF_OVERLAY_PRE_APPLY);
928 	if (ret) {
929 		pr_err("overlay changeset pre-apply notify error %d\n", ret);
930 		goto out;
931 	}
932 
933 	ret = build_changeset(ovcs);
934 	if (ret)
935 		goto out;
936 
937 	ret_revert = 0;
938 	ret = __of_changeset_apply_entries(&ovcs->cset, &ret_revert);
939 	if (ret) {
940 		if (ret_revert) {
941 			pr_debug("overlay changeset revert error %d\n",
942 				 ret_revert);
943 			devicetree_state_flags |= DTSF_APPLY_FAIL;
944 		}
945 		goto out;
946 	}
947 
948 	ret = __of_changeset_apply_notify(&ovcs->cset);
949 	if (ret)
950 		pr_err("overlay apply changeset entry notify error %d\n", ret);
951 	/* notify failure is not fatal, continue */
952 
953 	ret_tmp = overlay_notify(ovcs, OF_OVERLAY_POST_APPLY);
954 	if (ret_tmp) {
955 		pr_err("overlay changeset post-apply notify error %d\n",
956 		       ret_tmp);
957 		if (!ret)
958 			ret = ret_tmp;
959 	}
960 
961 out:
962 	pr_debug("%s() err=%d\n", __func__, ret);
963 
964 	return ret;
965 }
966 
967 int of_overlay_fdt_apply(const void *overlay_fdt, u32 overlay_fdt_size,
968 			 int *ret_ovcs_id)
969 {
970 	void *new_fdt;
971 	void *new_fdt_align;
972 	void *overlay_mem;
973 	int ret;
974 	u32 size;
975 	struct overlay_changeset *ovcs;
976 
977 	*ret_ovcs_id = 0;
978 
979 	if (overlay_fdt_size < sizeof(struct fdt_header) ||
980 	    fdt_check_header(overlay_fdt)) {
981 		pr_err("Invalid overlay_fdt header\n");
982 		return -EINVAL;
983 	}
984 
985 	size = fdt_totalsize(overlay_fdt);
986 	if (overlay_fdt_size < size)
987 		return -EINVAL;
988 
989 	ovcs = kzalloc(sizeof(*ovcs), GFP_KERNEL);
990 	if (!ovcs)
991 		return -ENOMEM;
992 
993 	of_overlay_mutex_lock();
994 	mutex_lock(&of_mutex);
995 
996 	/*
997 	 * ovcs->notify_state must be set to OF_OVERLAY_INIT before allocating
998 	 * ovcs resources, implicitly set by kzalloc() of ovcs
999 	 */
1000 
1001 	ovcs->id = idr_alloc(&ovcs_idr, ovcs, 1, 0, GFP_KERNEL);
1002 	if (ovcs->id <= 0) {
1003 		ret = ovcs->id;
1004 		goto err_free_ovcs;
1005 	}
1006 
1007 	INIT_LIST_HEAD(&ovcs->ovcs_list);
1008 	list_add_tail(&ovcs->ovcs_list, &ovcs_list);
1009 
1010 	/*
1011 	 * Must create permanent copy of FDT because of_fdt_unflatten_tree()
1012 	 * will create pointers to the passed in FDT in the unflattened tree.
1013 	 */
1014 	new_fdt = kmalloc(size + FDT_ALIGN_SIZE, GFP_KERNEL);
1015 	if (!new_fdt) {
1016 		ret = -ENOMEM;
1017 		goto err_free_ovcs;
1018 	}
1019 	ovcs->new_fdt = new_fdt;
1020 
1021 	new_fdt_align = PTR_ALIGN(new_fdt, FDT_ALIGN_SIZE);
1022 	memcpy(new_fdt_align, overlay_fdt, size);
1023 
1024 	overlay_mem = of_fdt_unflatten_tree(new_fdt_align, NULL,
1025 					    &ovcs->overlay_root);
1026 	if (!overlay_mem) {
1027 		pr_err("unable to unflatten overlay_fdt\n");
1028 		ret = -EINVAL;
1029 		goto err_free_ovcs;
1030 	}
1031 	ovcs->overlay_mem = overlay_mem;
1032 
1033 	ret = of_overlay_apply(ovcs);
1034 	if (ret < 0)
1035 		goto err_free_ovcs;
1036 
1037 	mutex_unlock(&of_mutex);
1038 	of_overlay_mutex_unlock();
1039 
1040 	*ret_ovcs_id = ovcs->id;
1041 
1042 	return 0;
1043 
1044 err_free_ovcs:
1045 	free_overlay_changeset(ovcs);
1046 
1047 	mutex_unlock(&of_mutex);
1048 	of_overlay_mutex_unlock();
1049 
1050 	return ret;
1051 }
1052 EXPORT_SYMBOL_GPL(of_overlay_fdt_apply);
1053 
1054 /*
1055  * Find @np in @tree.
1056  *
1057  * Returns 1 if @np is @tree or is contained in @tree, else 0
1058  */
1059 static int find_node(struct device_node *tree, struct device_node *np)
1060 {
1061 	struct device_node *child;
1062 
1063 	if (tree == np)
1064 		return 1;
1065 
1066 	for_each_child_of_node(tree, child) {
1067 		if (find_node(child, np)) {
1068 			of_node_put(child);
1069 			return 1;
1070 		}
1071 	}
1072 
1073 	return 0;
1074 }
1075 
1076 /*
1077  * Is @remove_ce_node a child of, a parent of, or the same as any
1078  * node in an overlay changeset more topmost than @remove_ovcs?
1079  *
1080  * Returns 1 if found, else 0
1081  */
1082 static int node_overlaps_later_cs(struct overlay_changeset *remove_ovcs,
1083 		struct device_node *remove_ce_node)
1084 {
1085 	struct overlay_changeset *ovcs;
1086 	struct of_changeset_entry *ce;
1087 
1088 	list_for_each_entry_reverse(ovcs, &ovcs_list, ovcs_list) {
1089 		if (ovcs == remove_ovcs)
1090 			break;
1091 
1092 		list_for_each_entry(ce, &ovcs->cset.entries, node) {
1093 			if (find_node(ce->np, remove_ce_node)) {
1094 				pr_err("%s: #%d overlaps with #%d @%pOF\n",
1095 					__func__, remove_ovcs->id, ovcs->id,
1096 					remove_ce_node);
1097 				return 1;
1098 			}
1099 			if (find_node(remove_ce_node, ce->np)) {
1100 				pr_err("%s: #%d overlaps with #%d @%pOF\n",
1101 					__func__, remove_ovcs->id, ovcs->id,
1102 					remove_ce_node);
1103 				return 1;
1104 			}
1105 		}
1106 	}
1107 
1108 	return 0;
1109 }
1110 
1111 /*
1112  * We can safely remove the overlay only if it's the top-most one.
1113  * Newly applied overlays are inserted at the tail of the overlay list,
1114  * so a top most overlay is the one that is closest to the tail.
1115  *
1116  * The topmost check is done by exploiting this property. For each
1117  * affected device node in the log list we check if this overlay is
1118  * the one closest to the tail. If another overlay has affected this
1119  * device node and is closest to the tail, then removal is not permited.
1120  */
1121 static int overlay_removal_is_ok(struct overlay_changeset *remove_ovcs)
1122 {
1123 	struct of_changeset_entry *remove_ce;
1124 
1125 	list_for_each_entry(remove_ce, &remove_ovcs->cset.entries, node) {
1126 		if (node_overlaps_later_cs(remove_ovcs, remove_ce->np)) {
1127 			pr_err("overlay #%d is not topmost\n", remove_ovcs->id);
1128 			return 0;
1129 		}
1130 	}
1131 
1132 	return 1;
1133 }
1134 
1135 /**
1136  * of_overlay_remove() - Revert and free an overlay changeset
1137  * @ovcs_id:	Pointer to overlay changeset id
1138  *
1139  * Removes an overlay if it is permissible.  @ovcs_id was previously returned
1140  * by of_overlay_fdt_apply().
1141  *
1142  * If an error occurred while attempting to revert the overlay changeset,
1143  * then an attempt is made to re-apply any changeset entry that was
1144  * reverted.  If an error occurs on re-apply then the state of the device
1145  * tree can not be determined, and any following attempt to apply or remove
1146  * an overlay changeset will be refused.
1147  *
1148  * A non-zero return value will not revert the changeset if error is from:
1149  *   - parameter checks
1150  *   - overlay changeset pre-remove notifier
1151  *   - overlay changeset entry revert
1152  *
1153  * If an error is returned by an overlay changeset pre-remove notifier
1154  * then no further overlay changeset pre-remove notifier will be called.
1155  *
1156  * If more than one notifier returns an error, then the last notifier
1157  * error to occur is returned.
1158  *
1159  * A non-zero return value will revert the changeset if error is from:
1160  *   - overlay changeset entry notifier
1161  *   - overlay changeset post-remove notifier
1162  *
1163  * If an error is returned by an overlay changeset post-remove notifier
1164  * then no further overlay changeset post-remove notifier will be called.
1165  *
1166  * Return: 0 on success, or a negative error number.  *@ovcs_id is set to
1167  * zero after reverting the changeset, even if a subsequent error occurs.
1168  */
1169 int of_overlay_remove(int *ovcs_id)
1170 {
1171 	struct overlay_changeset *ovcs;
1172 	int ret, ret_apply, ret_tmp;
1173 
1174 	if (devicetree_corrupt()) {
1175 		pr_err("suspect devicetree state, refuse to remove overlay\n");
1176 		ret = -EBUSY;
1177 		goto out;
1178 	}
1179 
1180 	mutex_lock(&of_mutex);
1181 
1182 	ovcs = idr_find(&ovcs_idr, *ovcs_id);
1183 	if (!ovcs) {
1184 		ret = -ENODEV;
1185 		pr_err("remove: Could not find overlay #%d\n", *ovcs_id);
1186 		goto err_unlock;
1187 	}
1188 
1189 	if (!overlay_removal_is_ok(ovcs)) {
1190 		ret = -EBUSY;
1191 		goto err_unlock;
1192 	}
1193 
1194 	ret = overlay_notify(ovcs, OF_OVERLAY_PRE_REMOVE);
1195 	if (ret) {
1196 		pr_err("overlay changeset pre-remove notify error %d\n", ret);
1197 		goto err_unlock;
1198 	}
1199 
1200 	ret_apply = 0;
1201 	ret = __of_changeset_revert_entries(&ovcs->cset, &ret_apply);
1202 	if (ret) {
1203 		if (ret_apply)
1204 			devicetree_state_flags |= DTSF_REVERT_FAIL;
1205 		goto err_unlock;
1206 	}
1207 
1208 	ret = __of_changeset_revert_notify(&ovcs->cset);
1209 	if (ret)
1210 		pr_err("overlay remove changeset entry notify error %d\n", ret);
1211 	/* notify failure is not fatal, continue */
1212 
1213 	*ovcs_id = 0;
1214 
1215 	/*
1216 	 * Note that the overlay memory will be kfree()ed by
1217 	 * free_overlay_changeset() even if the notifier for
1218 	 * OF_OVERLAY_POST_REMOVE returns an error.
1219 	 */
1220 	ret_tmp = overlay_notify(ovcs, OF_OVERLAY_POST_REMOVE);
1221 	if (ret_tmp) {
1222 		pr_err("overlay changeset post-remove notify error %d\n",
1223 		       ret_tmp);
1224 		if (!ret)
1225 			ret = ret_tmp;
1226 	}
1227 
1228 	free_overlay_changeset(ovcs);
1229 
1230 err_unlock:
1231 	/*
1232 	 * If jumped over free_overlay_changeset(), then did not kfree()
1233 	 * overlay related memory.  This is a memory leak unless a subsequent
1234 	 * of_overlay_remove() of this overlay is successful.
1235 	 */
1236 	mutex_unlock(&of_mutex);
1237 
1238 out:
1239 	pr_debug("%s() err=%d\n", __func__, ret);
1240 
1241 	return ret;
1242 }
1243 EXPORT_SYMBOL_GPL(of_overlay_remove);
1244 
1245 /**
1246  * of_overlay_remove_all() - Reverts and frees all overlay changesets
1247  *
1248  * Removes all overlays from the system in the correct order.
1249  *
1250  * Return: 0 on success, or a negative error number
1251  */
1252 int of_overlay_remove_all(void)
1253 {
1254 	struct overlay_changeset *ovcs, *ovcs_n;
1255 	int ret;
1256 
1257 	/* the tail of list is guaranteed to be safe to remove */
1258 	list_for_each_entry_safe_reverse(ovcs, ovcs_n, &ovcs_list, ovcs_list) {
1259 		ret = of_overlay_remove(&ovcs->id);
1260 		if (ret)
1261 			return ret;
1262 	}
1263 
1264 	return 0;
1265 }
1266 EXPORT_SYMBOL_GPL(of_overlay_remove_all);
1267