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