xref: /linux/drivers/of/overlay.c (revision 4b99990cdf9560e8a071640baf19f312e6ae02f4)
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 
260 	new_prop = kzalloc_obj(*new_prop);
261 	if (!new_prop)
262 		goto err_free_target_path;
263 
264 	new_prop->name = kstrdup(prop->name, GFP_KERNEL);
265 	new_prop->length = target_path_len + path_tail_len + 1;
266 	new_prop->value = kzalloc(new_prop->length, GFP_KERNEL);
267 	if (!new_prop->name || !new_prop->value)
268 		goto err_free_new_prop;
269 
270 	strcpy(new_prop->value, target_path);
271 	strcpy(new_prop->value + target_path_len, path_tail);
272 
273 	of_property_set_flag(new_prop, OF_DYNAMIC);
274 
275 	kfree(target_path);
276 
277 	return new_prop;
278 
279 err_free_new_prop:
280 	__of_prop_free(new_prop);
281 err_free_target_path:
282 	kfree(target_path);
283 
284 	return NULL;
285 }
286 
287 /**
288  * add_changeset_property() - add @overlay_prop to overlay changeset
289  * @ovcs:		overlay changeset
290  * @target:		where @overlay_prop will be placed
291  * @overlay_prop:	property to add or update, from overlay tree
292  * @is_symbols_prop:	1 if @overlay_prop is from node "/__symbols__"
293  *
294  * If @overlay_prop does not already exist in live devicetree, add changeset
295  * entry to add @overlay_prop in @target, else add changeset entry to update
296  * value of @overlay_prop.
297  *
298  * @target may be either in the live devicetree or in a new subtree that
299  * is contained in the changeset.
300  *
301  * Some special properties are not added or updated (no error returned):
302  * "name", "phandle", "linux,phandle".
303  *
304  * Properties "#address-cells" and "#size-cells" are not updated if they
305  * are already in the live tree, but if present in the live tree, the values
306  * in the overlay must match the values in the live tree.
307  *
308  * Update of property in symbols node is not allowed.
309  *
310  * Return: 0 on success, -ENOMEM if memory allocation failure, or -EINVAL if
311  * invalid @overlay.
312  */
313 static int add_changeset_property(struct overlay_changeset *ovcs,
314 		struct target *target, const struct property *overlay_prop,
315 		bool is_symbols_prop)
316 {
317 	struct property *new_prop = NULL;
318 	const struct property *prop;
319 	int ret = 0;
320 
321 	if (target->in_livetree)
322 		if (is_pseudo_property(overlay_prop->name))
323 			return 0;
324 
325 	if (target->in_livetree)
326 		prop = of_find_property(target->np, overlay_prop->name, NULL);
327 	else
328 		prop = NULL;
329 
330 	if (prop) {
331 		if (!of_prop_cmp(prop->name, "#address-cells")) {
332 			if (!of_prop_val_eq(prop, overlay_prop)) {
333 				pr_err("ERROR: changing value of #address-cells is not allowed in %pOF\n",
334 				       target->np);
335 				ret = -EINVAL;
336 			}
337 			return ret;
338 
339 		} else if (!of_prop_cmp(prop->name, "#size-cells")) {
340 			if (!of_prop_val_eq(prop, overlay_prop)) {
341 				pr_err("ERROR: changing value of #size-cells is not allowed in %pOF\n",
342 				       target->np);
343 				ret = -EINVAL;
344 			}
345 			return ret;
346 		}
347 	}
348 
349 	if (is_symbols_prop) {
350 		if (prop)
351 			return -EINVAL;
352 		new_prop = dup_and_fixup_symbol_prop(ovcs, overlay_prop);
353 	} else {
354 		new_prop = __of_prop_dup(overlay_prop, GFP_KERNEL);
355 	}
356 
357 	if (!new_prop)
358 		return -ENOMEM;
359 
360 	if (!prop) {
361 		if (!target->in_livetree) {
362 			new_prop->next = target->np->deadprops;
363 			target->np->deadprops = new_prop;
364 		}
365 		ret = of_changeset_add_property(&ovcs->cset, target->np,
366 						new_prop);
367 	} else {
368 		ret = of_changeset_update_property(&ovcs->cset, target->np,
369 						   new_prop);
370 	}
371 
372 	if (!of_node_check_flag(target->np, OF_OVERLAY))
373 		pr_err("WARNING: memory leak will occur if overlay removed, property: %pOF/%s\n",
374 		       target->np, new_prop->name);
375 
376 	if (ret)
377 		__of_prop_free(new_prop);
378 	return ret;
379 }
380 
381 /**
382  * add_changeset_node() - add @node (and children) to overlay changeset
383  * @ovcs:	overlay changeset
384  * @target:	where @node will be placed in live tree or changeset
385  * @node:	node from within overlay device tree fragment
386  *
387  * If @node does not already exist in @target, add changeset entry
388  * to add @node in @target.
389  *
390  * If @node already exists in @target, and the existing node has
391  * a phandle, the overlay node is not allowed to have a phandle.
392  *
393  * If @node has child nodes, add the children recursively via
394  * build_changeset_next_level().
395  *
396  * NOTE_1: A live devicetree created from a flattened device tree (FDT) will
397  *       not contain the full path in node->full_name.  Thus an overlay
398  *       created from an FDT also will not contain the full path in
399  *       node->full_name.  However, a live devicetree created from Open
400  *       Firmware may have the full path in node->full_name.
401  *
402  *       add_changeset_node() follows the FDT convention and does not include
403  *       the full path in node->full_name.  Even though it expects the overlay
404  *       to not contain the full path, it uses kbasename() to remove the
405  *       full path should it exist.  It also uses kbasename() in comparisons
406  *       to nodes in the live devicetree so that it can apply an overlay to
407  *       a live devicetree created from Open Firmware.
408  *
409  * NOTE_2: Multiple mods of created nodes not supported.
410  *
411  * Return: 0 on success, -ENOMEM if memory allocation failure, or -EINVAL if
412  * invalid @overlay.
413  */
414 static int add_changeset_node(struct overlay_changeset *ovcs,
415 		struct target *target, const struct device_node *node)
416 {
417 	const char *node_kbasename;
418 	const __be32 *phandle;
419 	struct device_node *tchild;
420 	struct target target_child;
421 	int ret = 0, size;
422 
423 	node_kbasename = kbasename(node->full_name);
424 
425 	for_each_child_of_node(target->np, tchild)
426 		if (!of_node_cmp(node_kbasename, kbasename(tchild->full_name)))
427 			break;
428 
429 	if (!tchild) {
430 		tchild = __of_node_dup(NULL, node_kbasename);
431 		if (!tchild)
432 			return -ENOMEM;
433 
434 		tchild->parent = target->np;
435 		tchild->name = __of_get_property(node, "name", NULL);
436 
437 		if (!tchild->name)
438 			tchild->name = "<NULL>";
439 
440 		/* ignore obsolete "linux,phandle" */
441 		phandle = __of_get_property(node, "phandle", &size);
442 		if (phandle && (size == 4))
443 			tchild->phandle = be32_to_cpup(phandle);
444 
445 		of_node_set_flag(tchild, OF_OVERLAY);
446 
447 		ret = of_changeset_attach_node(&ovcs->cset, tchild);
448 		if (ret)
449 			return ret;
450 
451 		target_child.np = tchild;
452 		target_child.in_livetree = false;
453 
454 		ret = build_changeset_next_level(ovcs, &target_child, node);
455 		of_node_put(tchild);
456 		return ret;
457 	}
458 
459 	if (node->phandle && tchild->phandle) {
460 		ret = -EINVAL;
461 	} else {
462 		target_child.np = tchild;
463 		target_child.in_livetree = target->in_livetree;
464 		ret = build_changeset_next_level(ovcs, &target_child, node);
465 	}
466 	of_node_put(tchild);
467 
468 	return ret;
469 }
470 
471 /**
472  * build_changeset_next_level() - add level of overlay changeset
473  * @ovcs:		overlay changeset
474  * @target:		where to place @overlay_node in live tree
475  * @overlay_node:	node from within an overlay device tree fragment
476  *
477  * Add the properties (if any) and nodes (if any) from @overlay_node to the
478  * @ovcs->cset changeset.  If an added node has child nodes, they will
479  * be added recursively.
480  *
481  * Do not allow symbols node to have any children.
482  *
483  * Return: 0 on success, -ENOMEM if memory allocation failure, or -EINVAL if
484  * invalid @overlay_node.
485  */
486 static int build_changeset_next_level(struct overlay_changeset *ovcs,
487 		struct target *target, const struct device_node *overlay_node)
488 {
489 	struct property *prop;
490 	int ret;
491 
492 	for_each_property_of_node(overlay_node, prop) {
493 		ret = add_changeset_property(ovcs, target, prop, 0);
494 		if (ret) {
495 			pr_debug("Failed to apply prop @%pOF/%s, err=%d\n",
496 				 target->np, prop->name, ret);
497 			return ret;
498 		}
499 	}
500 
501 	for_each_child_of_node_scoped(overlay_node, child) {
502 		ret = add_changeset_node(ovcs, target, child);
503 		if (ret) {
504 			pr_debug("Failed to apply node @%pOF/%pOFn, err=%d\n",
505 				 target->np, child, ret);
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 = !fn_1 || !fn_2 || !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 = !fn_1 || !fn_2 || !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(const struct device_node *info_node,
693 				       const struct device_node *target_base)
694 {
695 	struct device_node *node;
696 	char *target_path;
697 	const char *path;
698 	u32 val;
699 	int ret;
700 
701 	ret = of_property_read_u32(info_node, "target", &val);
702 	if (!ret) {
703 		node = of_find_node_by_phandle(val);
704 		if (!node)
705 			pr_err("find target, node: %pOF, phandle 0x%x not found\n",
706 			       info_node, val);
707 		return node;
708 	}
709 
710 	ret = of_property_read_string(info_node, "target-path", &path);
711 	if (!ret) {
712 		if (target_base) {
713 			target_path = kasprintf(GFP_KERNEL, "%pOF%s", target_base, path);
714 			if (!target_path)
715 				return NULL;
716 			node = of_find_node_by_path(target_path);
717 			if (!node) {
718 				pr_err("find target, node: %pOF, path '%s' not found\n",
719 				       info_node, target_path);
720 			}
721 			kfree(target_path);
722 		} else {
723 			node =  of_find_node_by_path(path);
724 			if (!node) {
725 				pr_err("find target, node: %pOF, path '%s' not found\n",
726 				       info_node, path);
727 			}
728 		}
729 		return node;
730 	}
731 
732 	pr_err("find target, node: %pOF, no target property\n", info_node);
733 
734 	return NULL;
735 }
736 
737 /**
738  * init_overlay_changeset() - initialize overlay changeset from overlay tree
739  * @ovcs:		Overlay changeset to build
740  * @target_base:	Point to the target node to apply overlay
741  *
742  * Initialize @ovcs.  Populate @ovcs->fragments with node information from
743  * the top level of @overlay_root.  The relevant top level nodes are the
744  * fragment nodes and the __symbols__ node.  Any other top level node will
745  * be ignored.  Populate other @ovcs fields.
746  *
747  * Return: 0 on success, -ENOMEM if memory allocation failure, -EINVAL if error
748  * detected in @overlay_root.  On error return, the caller of
749  * init_overlay_changeset() must call free_overlay_changeset().
750  */
751 static int init_overlay_changeset(struct overlay_changeset *ovcs,
752 				  const struct device_node *target_base)
753 {
754 	struct device_node *node, *overlay_node;
755 	struct fragment *fragment;
756 	struct fragment *fragments;
757 	int cnt, ret;
758 
759 	/*
760 	 * None of the resources allocated by this function will be freed in
761 	 * the error paths.  Instead the caller of this function is required
762 	 * to call free_overlay_changeset() (which will free the resources)
763 	 * if error return.
764 	 */
765 
766 	/*
767 	 * Warn for some issues.  Can not return -EINVAL for these until
768 	 * of_unittest_apply_overlay() is fixed to pass these checks.
769 	 */
770 	if (!of_node_check_flag(ovcs->overlay_root, OF_DYNAMIC))
771 		pr_debug("%s() ovcs->overlay_root is not dynamic\n", __func__);
772 
773 	if (!of_node_check_flag(ovcs->overlay_root, OF_DETACHED))
774 		pr_debug("%s() ovcs->overlay_root is not detached\n", __func__);
775 
776 	if (!of_node_is_root(ovcs->overlay_root))
777 		pr_debug("%s() ovcs->overlay_root is not root\n", __func__);
778 
779 	cnt = 0;
780 
781 	/* fragment nodes */
782 	for_each_child_of_node(ovcs->overlay_root, node) {
783 		overlay_node = of_get_child_by_name(node, "__overlay__");
784 		if (overlay_node) {
785 			cnt++;
786 			of_node_put(overlay_node);
787 		}
788 	}
789 
790 	node = of_get_child_by_name(ovcs->overlay_root, "__symbols__");
791 	if (node) {
792 		cnt++;
793 		of_node_put(node);
794 	}
795 
796 	fragments = kzalloc_objs(*fragments, cnt);
797 	if (!fragments) {
798 		ret = -ENOMEM;
799 		goto err_out;
800 	}
801 	ovcs->fragments = fragments;
802 
803 	cnt = 0;
804 	for_each_child_of_node(ovcs->overlay_root, node) {
805 		overlay_node = of_get_child_by_name(node, "__overlay__");
806 		if (!overlay_node)
807 			continue;
808 
809 		fragment = &fragments[cnt];
810 		fragment->overlay = overlay_node;
811 		fragment->target = find_target(node, target_base);
812 		if (!fragment->target) {
813 			of_node_put(fragment->overlay);
814 			ret = -EINVAL;
815 			of_node_put(node);
816 			goto err_out;
817 		}
818 
819 		cnt++;
820 	}
821 
822 	/*
823 	 * if there is a symbols fragment in ovcs->fragments[i] it is
824 	 * the final element in the array
825 	 */
826 	node = of_get_child_by_name(ovcs->overlay_root, "__symbols__");
827 	if (node) {
828 		ovcs->symbols_fragment = 1;
829 		fragment = &fragments[cnt];
830 		fragment->overlay = node;
831 		fragment->target = of_find_node_by_path("/__symbols__");
832 
833 		if (!fragment->target) {
834 			pr_err("symbols in overlay, but not in live tree\n");
835 			ret = -EINVAL;
836 			of_node_put(node);
837 			goto err_out;
838 		}
839 
840 		cnt++;
841 	}
842 
843 	if (!cnt) {
844 		pr_err("no fragments or symbols in overlay\n");
845 		ret = -EINVAL;
846 		goto err_out;
847 	}
848 
849 	ovcs->count = cnt;
850 
851 	return 0;
852 
853 err_out:
854 	pr_err("%s() failed, ret = %d\n", __func__, ret);
855 
856 	return ret;
857 }
858 
859 static void free_overlay_changeset(struct overlay_changeset *ovcs)
860 {
861 	int i;
862 
863 	if (ovcs->cset.entries.next)
864 		of_changeset_destroy(&ovcs->cset);
865 
866 	if (ovcs->id) {
867 		idr_remove(&ovcs_idr, ovcs->id);
868 		list_del(&ovcs->ovcs_list);
869 		ovcs->id = 0;
870 	}
871 
872 
873 	for (i = 0; i < ovcs->count; i++) {
874 		of_node_put(ovcs->fragments[i].target);
875 		of_node_put(ovcs->fragments[i].overlay);
876 	}
877 	kfree(ovcs->fragments);
878 
879 	/*
880 	 * There should be no live pointers into ovcs->overlay_mem and
881 	 * ovcs->new_fdt due to the policy that overlay notifiers are not
882 	 * allowed to retain pointers into the overlay devicetree other
883 	 * than during the window from OF_OVERLAY_PRE_APPLY overlay
884 	 * notifiers until the OF_OVERLAY_POST_REMOVE overlay notifiers.
885 	 *
886 	 * A memory leak will occur here if within the window.
887 	 */
888 
889 	if (ovcs->notify_state == OF_OVERLAY_INIT ||
890 	    ovcs->notify_state == OF_OVERLAY_POST_REMOVE) {
891 		kfree(ovcs->overlay_mem);
892 		kfree(ovcs->new_fdt);
893 	}
894 	kfree(ovcs);
895 }
896 
897 /*
898  * internal documentation
899  *
900  * of_overlay_apply() - Create and apply an overlay changeset
901  * @ovcs:	overlay changeset
902  * @base:	point to the target node to apply overlay
903  *
904  * Creates and applies an overlay changeset.
905  *
906  * If an error is returned by an overlay changeset pre-apply notifier
907  * then no further overlay changeset pre-apply notifier will be called.
908  *
909  * If an error is returned by an overlay changeset post-apply notifier
910  * then no further overlay changeset post-apply notifier will be called.
911  *
912  * If more than one notifier returns an error, then the last notifier
913  * error to occur is returned.
914  *
915  * If an error occurred while applying the overlay changeset, then an
916  * attempt is made to revert any changes that were made to the
917  * device tree.  If there were any errors during the revert attempt
918  * then the state of the device tree can not be determined, and any
919  * following attempt to apply or remove an overlay changeset will be
920  * refused.
921  *
922  * Returns 0 on success, or a negative error number.  On error return,
923  * the caller of of_overlay_apply() must call free_overlay_changeset().
924  */
925 
926 static int of_overlay_apply(struct overlay_changeset *ovcs,
927 			    const struct device_node *base)
928 {
929 	int ret = 0, ret_revert, ret_tmp;
930 
931 	ret = of_resolve_phandles(ovcs->overlay_root);
932 	if (ret)
933 		goto out;
934 
935 	ret = init_overlay_changeset(ovcs, base);
936 	if (ret)
937 		goto out;
938 
939 	ret = overlay_notify(ovcs, OF_OVERLAY_PRE_APPLY);
940 	if (ret)
941 		goto out;
942 
943 	ret = build_changeset(ovcs);
944 	if (ret)
945 		goto out;
946 
947 	ret_revert = 0;
948 	ret = __of_changeset_apply_entries(&ovcs->cset, &ret_revert);
949 	if (ret) {
950 		if (ret_revert) {
951 			pr_debug("overlay changeset revert error %d\n",
952 				 ret_revert);
953 			devicetree_state_flags |= DTSF_APPLY_FAIL;
954 		}
955 		goto out;
956 	}
957 
958 	ret = __of_changeset_apply_notify(&ovcs->cset);
959 	if (ret)
960 		pr_err("overlay apply changeset entry notify error %d\n", ret);
961 	/* notify failure is not fatal, continue */
962 
963 	/*
964 	 * Needs to happen after changeset notify to give the listeners a chance
965 	 * to finish creating all the devices they need to create.
966 	 */
967 	overlay_fw_devlink_refresh(ovcs);
968 
969 	ret_tmp = overlay_notify(ovcs, OF_OVERLAY_POST_APPLY);
970 	if (ret_tmp)
971 		if (!ret)
972 			ret = ret_tmp;
973 
974 out:
975 	pr_debug("%s() err=%d\n", __func__, ret);
976 
977 	return ret;
978 }
979 
980 /**
981  * of_overlay_fdt_apply() - Create and apply an overlay changeset
982  * @overlay_fdt:	pointer to overlay FDT
983  * @overlay_fdt_size:	number of bytes in @overlay_fdt
984  * @ret_ovcs_id:	pointer for returning created changeset id
985  * @base:		pointer for the target node to apply overlay
986  *
987  * Creates and applies an overlay changeset.
988  *
989  * See of_overlay_apply() for important behavior information.
990  *
991  * Return: 0 on success, or a negative error number.  *@ret_ovcs_id is set to
992  * the value of overlay changeset id, which can be passed to of_overlay_remove()
993  * to remove the overlay.
994  *
995  * On error return, the changeset may be partially applied.  This is especially
996  * likely if an OF_OVERLAY_POST_APPLY notifier returns an error.  In this case
997  * the caller should call of_overlay_remove() with the value in *@ret_ovcs_id.
998  */
999 
1000 int of_overlay_fdt_apply(const void *overlay_fdt, u32 overlay_fdt_size,
1001 			 int *ret_ovcs_id, const struct device_node *base)
1002 {
1003 	void *new_fdt;
1004 	void *new_fdt_align;
1005 	void *overlay_mem;
1006 	int ret;
1007 	u32 size;
1008 	struct overlay_changeset *ovcs;
1009 
1010 	*ret_ovcs_id = 0;
1011 
1012 	if (devicetree_corrupt()) {
1013 		pr_err("devicetree state suspect, refuse to apply overlay\n");
1014 		return -EBUSY;
1015 	}
1016 
1017 	if (overlay_fdt_size < sizeof(struct fdt_header) ||
1018 	    fdt_check_header(overlay_fdt)) {
1019 		pr_err("Invalid overlay_fdt header\n");
1020 		return -EINVAL;
1021 	}
1022 
1023 	size = fdt_totalsize(overlay_fdt);
1024 	if (overlay_fdt_size < size)
1025 		return -EINVAL;
1026 
1027 	ovcs = kzalloc_obj(*ovcs);
1028 	if (!ovcs)
1029 		return -ENOMEM;
1030 
1031 	of_overlay_mutex_lock();
1032 	mutex_lock(&of_mutex);
1033 
1034 	/*
1035 	 * ovcs->notify_state must be set to OF_OVERLAY_INIT before allocating
1036 	 * ovcs resources, implicitly set by kzalloc() of ovcs
1037 	 */
1038 
1039 	ovcs->id = idr_alloc(&ovcs_idr, ovcs, 1, 0, GFP_KERNEL);
1040 	if (ovcs->id <= 0) {
1041 		ret = ovcs->id;
1042 		goto err_free_ovcs;
1043 	}
1044 
1045 	INIT_LIST_HEAD(&ovcs->ovcs_list);
1046 	list_add_tail(&ovcs->ovcs_list, &ovcs_list);
1047 	of_changeset_init(&ovcs->cset);
1048 
1049 	/*
1050 	 * Must create permanent copy of FDT because of_fdt_unflatten_tree()
1051 	 * will create pointers to the passed in FDT in the unflattened tree.
1052 	 */
1053 	new_fdt = kmalloc(size + FDT_ALIGN_SIZE, GFP_KERNEL);
1054 	if (!new_fdt) {
1055 		ret = -ENOMEM;
1056 		goto err_free_ovcs;
1057 	}
1058 	ovcs->new_fdt = new_fdt;
1059 
1060 	new_fdt_align = PTR_ALIGN(new_fdt, FDT_ALIGN_SIZE);
1061 	memcpy(new_fdt_align, overlay_fdt, size);
1062 
1063 	overlay_mem = of_fdt_unflatten_tree(new_fdt_align, NULL,
1064 					    &ovcs->overlay_root);
1065 	if (!overlay_mem) {
1066 		pr_err("unable to unflatten overlay_fdt\n");
1067 		ret = -EINVAL;
1068 		goto err_free_ovcs;
1069 	}
1070 	ovcs->overlay_mem = overlay_mem;
1071 
1072 	ret = of_overlay_apply(ovcs, base);
1073 	/*
1074 	 * If of_overlay_apply() error, calling free_overlay_changeset() may
1075 	 * result in a memory leak if the apply partly succeeded, so do NOT
1076 	 * goto err_free_ovcs.  Instead, the caller of of_overlay_fdt_apply()
1077 	 * can call of_overlay_remove();
1078 	 */
1079 	*ret_ovcs_id = ovcs->id;
1080 	goto out_unlock;
1081 
1082 err_free_ovcs:
1083 	free_overlay_changeset(ovcs);
1084 
1085 out_unlock:
1086 	mutex_unlock(&of_mutex);
1087 	of_overlay_mutex_unlock();
1088 	return ret;
1089 }
1090 EXPORT_SYMBOL_GPL(of_overlay_fdt_apply);
1091 
1092 /*
1093  * Find @np in @tree.
1094  *
1095  * Returns 1 if @np is @tree or is contained in @tree, else 0
1096  */
1097 static int find_node(const struct device_node *tree, struct device_node *np)
1098 {
1099 	if (tree == np)
1100 		return 1;
1101 
1102 	for_each_child_of_node_scoped(tree, child) {
1103 		if (find_node(child, np))
1104 			return 1;
1105 	}
1106 
1107 	return 0;
1108 }
1109 
1110 /*
1111  * Is @remove_ce_node a child of, a parent of, or the same as any
1112  * node in an overlay changeset more topmost than @remove_ovcs?
1113  *
1114  * Returns 1 if found, else 0
1115  */
1116 static int node_overlaps_later_cs(struct overlay_changeset *remove_ovcs,
1117 		struct device_node *remove_ce_node)
1118 {
1119 	struct overlay_changeset *ovcs;
1120 	struct of_changeset_entry *ce;
1121 
1122 	list_for_each_entry_reverse(ovcs, &ovcs_list, ovcs_list) {
1123 		if (ovcs == remove_ovcs)
1124 			break;
1125 
1126 		list_for_each_entry(ce, &ovcs->cset.entries, node) {
1127 			if (find_node(ce->np, remove_ce_node)) {
1128 				pr_err("%s: #%d overlaps with #%d @%pOF\n",
1129 					__func__, remove_ovcs->id, ovcs->id,
1130 					remove_ce_node);
1131 				return 1;
1132 			}
1133 			if (find_node(remove_ce_node, ce->np)) {
1134 				pr_err("%s: #%d overlaps with #%d @%pOF\n",
1135 					__func__, remove_ovcs->id, ovcs->id,
1136 					remove_ce_node);
1137 				return 1;
1138 			}
1139 		}
1140 	}
1141 
1142 	return 0;
1143 }
1144 
1145 /*
1146  * We can safely remove the overlay only if it's the top-most one.
1147  * Newly applied overlays are inserted at the tail of the overlay list,
1148  * so a top most overlay is the one that is closest to the tail.
1149  *
1150  * The topmost check is done by exploiting this property. For each
1151  * affected device node in the log list we check if this overlay is
1152  * the one closest to the tail. If another overlay has affected this
1153  * device node and is closest to the tail, then removal is not permitted.
1154  */
1155 static int overlay_removal_is_ok(struct overlay_changeset *remove_ovcs)
1156 {
1157 	struct of_changeset_entry *remove_ce;
1158 
1159 	list_for_each_entry(remove_ce, &remove_ovcs->cset.entries, node) {
1160 		if (node_overlaps_later_cs(remove_ovcs, remove_ce->np)) {
1161 			pr_err("overlay #%d is not topmost\n", remove_ovcs->id);
1162 			return 0;
1163 		}
1164 	}
1165 
1166 	return 1;
1167 }
1168 
1169 /**
1170  * of_overlay_remove() - Revert and free an overlay changeset
1171  * @ovcs_id:	Pointer to overlay changeset id
1172  *
1173  * Removes an overlay if it is permissible.  @ovcs_id was previously returned
1174  * by of_overlay_fdt_apply().
1175  *
1176  * If an error occurred while attempting to revert the overlay changeset,
1177  * then an attempt is made to re-apply any changeset entry that was
1178  * reverted.  If an error occurs on re-apply then the state of the device
1179  * tree can not be determined, and any following attempt to apply or remove
1180  * an overlay changeset will be refused.
1181  *
1182  * A non-zero return value will not revert the changeset if error is from:
1183  *   - parameter checks
1184  *   - overlay changeset pre-remove notifier
1185  *   - overlay changeset entry revert
1186  *
1187  * If an error is returned by an overlay changeset pre-remove notifier
1188  * then no further overlay changeset pre-remove notifier will be called.
1189  *
1190  * If more than one notifier returns an error, then the last notifier
1191  * error to occur is returned.
1192  *
1193  * A non-zero return value will revert the changeset if error is from:
1194  *   - overlay changeset entry notifier
1195  *   - overlay changeset post-remove notifier
1196  *
1197  * If an error is returned by an overlay changeset post-remove notifier
1198  * then no further overlay changeset post-remove notifier will be called.
1199  *
1200  * Return: 0 on success, or a negative error number.  *@ovcs_id is set to
1201  * zero after reverting the changeset, even if a subsequent error occurs.
1202  */
1203 int of_overlay_remove(int *ovcs_id)
1204 {
1205 	struct overlay_changeset *ovcs;
1206 	int ret, ret_apply, ret_tmp;
1207 
1208 	if (*ovcs_id == 0)
1209 		return 0;
1210 
1211 	if (devicetree_corrupt()) {
1212 		pr_err("suspect devicetree state, refuse to remove overlay\n");
1213 		ret = -EBUSY;
1214 		goto out;
1215 	}
1216 
1217 	mutex_lock(&of_mutex);
1218 
1219 	ovcs = idr_find(&ovcs_idr, *ovcs_id);
1220 	if (!ovcs) {
1221 		ret = -ENODEV;
1222 		pr_err("remove: Could not find overlay #%d\n", *ovcs_id);
1223 		goto err_unlock;
1224 	}
1225 
1226 	if (!overlay_removal_is_ok(ovcs)) {
1227 		ret = -EBUSY;
1228 		goto err_unlock;
1229 	}
1230 
1231 	ret = overlay_notify(ovcs, OF_OVERLAY_PRE_REMOVE);
1232 	if (ret)
1233 		goto err_unlock;
1234 
1235 	ret_apply = 0;
1236 	ret = __of_changeset_revert_entries(&ovcs->cset, &ret_apply);
1237 	if (ret) {
1238 		if (ret_apply)
1239 			devicetree_state_flags |= DTSF_REVERT_FAIL;
1240 		goto err_unlock;
1241 	}
1242 
1243 	ret = __of_changeset_revert_notify(&ovcs->cset);
1244 	if (ret)
1245 		pr_err("overlay remove changeset entry notify error %d\n", ret);
1246 	/* notify failure is not fatal, continue */
1247 
1248 	*ovcs_id = 0;
1249 
1250 	/*
1251 	 * Note that the overlay memory will be kfree()ed by
1252 	 * free_overlay_changeset() even if the notifier for
1253 	 * OF_OVERLAY_POST_REMOVE returns an error.
1254 	 */
1255 	ret_tmp = overlay_notify(ovcs, OF_OVERLAY_POST_REMOVE);
1256 	if (ret_tmp)
1257 		if (!ret)
1258 			ret = ret_tmp;
1259 
1260 	free_overlay_changeset(ovcs);
1261 
1262 err_unlock:
1263 	/*
1264 	 * If jumped over free_overlay_changeset(), then did not kfree()
1265 	 * overlay related memory.  This is a memory leak unless a subsequent
1266 	 * of_overlay_remove() of this overlay is successful.
1267 	 */
1268 	mutex_unlock(&of_mutex);
1269 
1270 out:
1271 	pr_debug("%s() err=%d\n", __func__, ret);
1272 
1273 	return ret;
1274 }
1275 EXPORT_SYMBOL_GPL(of_overlay_remove);
1276 
1277 /**
1278  * of_overlay_remove_all() - Reverts and frees all overlay changesets
1279  *
1280  * Removes all overlays from the system in the correct order.
1281  *
1282  * Return: 0 on success, or a negative error number
1283  */
1284 int of_overlay_remove_all(void)
1285 {
1286 	struct overlay_changeset *ovcs, *ovcs_n;
1287 	int ret;
1288 
1289 	/* the tail of list is guaranteed to be safe to remove */
1290 	list_for_each_entry_safe_reverse(ovcs, ovcs_n, &ovcs_list, ovcs_list) {
1291 		ret = of_overlay_remove(&ovcs->id);
1292 		if (ret)
1293 			return ret;
1294 	}
1295 
1296 	return 0;
1297 }
1298 EXPORT_SYMBOL_GPL(of_overlay_remove_all);
1299