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