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