xref: /linux/drivers/of/base.c (revision f4cdf7ca9a1fdcca413157df19753f388a5a224e)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Procedures for creating, accessing and interpreting the device tree.
4  *
5  * Paul Mackerras	August 1996.
6  * Copyright (C) 1996-2005 Paul Mackerras.
7  *
8  *  Adapted for 64bit PowerPC by Dave Engebretsen and Peter Bergner.
9  *    {engebret|bergner}@us.ibm.com
10  *
11  *  Adapted for sparc and sparc64 by David S. Miller davem@davemloft.net
12  *
13  *  Reconsolidated from arch/x/kernel/prom.c by Stephen Rothwell and
14  *  Grant Likely.
15  */
16 
17 #define pr_fmt(fmt)	"OF: " fmt
18 
19 #include <linux/cleanup.h>
20 #include <linux/console.h>
21 #include <linux/ctype.h>
22 #include <linux/cpu.h>
23 #include <linux/module.h>
24 #include <linux/of.h>
25 #include <linux/of_device.h>
26 #include <linux/of_graph.h>
27 #include <linux/spinlock.h>
28 #include <linux/slab.h>
29 #include <linux/string.h>
30 #include <linux/proc_fs.h>
31 
32 #include "of_private.h"
33 
34 LIST_HEAD(aliases_lookup);
35 
36 struct device_node *of_root;
37 EXPORT_SYMBOL(of_root);
38 struct device_node *of_chosen;
39 EXPORT_SYMBOL(of_chosen);
40 struct device_node *of_aliases;
41 struct device_node *of_stdout;
42 EXPORT_SYMBOL_GPL(of_stdout);
43 static const char *of_stdout_options;
44 
45 struct kset *of_kset;
46 
47 /*
48  * Used to protect the of_aliases, to hold off addition of nodes to sysfs.
49  * This mutex must be held whenever modifications are being made to the
50  * device tree. The of_{attach,detach}_node() and
51  * of_{add,remove,update}_property() helpers make sure this happens.
52  */
53 DEFINE_MUTEX(of_mutex);
54 
55 /* use when traversing tree through the child, sibling,
56  * or parent members of struct device_node.
57  */
58 DEFINE_RAW_SPINLOCK(devtree_lock);
59 
60 bool of_node_name_eq(const struct device_node *np, const char *name)
61 {
62 	const char *node_name;
63 	size_t len;
64 
65 	if (!np)
66 		return false;
67 
68 	node_name = kbasename(np->full_name);
69 	len = strchrnul(node_name, '@') - node_name;
70 
71 	return (strlen(name) == len) && (strncmp(node_name, name, len) == 0);
72 }
73 EXPORT_SYMBOL(of_node_name_eq);
74 
75 bool of_node_name_prefix(const struct device_node *np, const char *prefix)
76 {
77 	if (!np)
78 		return false;
79 
80 	return strncmp(kbasename(np->full_name), prefix, strlen(prefix)) == 0;
81 }
82 EXPORT_SYMBOL(of_node_name_prefix);
83 
84 static bool __of_node_is_type(const struct device_node *np, const char *type)
85 {
86 	const char *match;
87 	int len;
88 
89 	if (!np || !type)
90 		return false;
91 
92 	match = __of_get_property(np, "device_type", &len);
93 	if (!match || len <= 0 || strnlen(match, len) >= len)
94 		return false;
95 
96 	return !strcmp(match, type);
97 }
98 
99 #define EXCLUDED_DEFAULT_CELLS_PLATFORMS ( \
100 	IS_ENABLED(CONFIG_SPARC) || \
101 	of_find_compatible_node(NULL, NULL, "coreboot") \
102 )
103 
104 int of_bus_n_addr_cells(struct device_node *np)
105 {
106 	u32 cells;
107 
108 	for (; np; np = np->parent) {
109 		if (!of_property_read_u32(np, "#address-cells", &cells))
110 			return cells;
111 		/*
112 		 * Default root value and walking parent nodes for "#address-cells"
113 		 * is deprecated. Any platforms which hit this warning should
114 		 * be added to the excluded list.
115 		 */
116 		WARN_ONCE(!EXCLUDED_DEFAULT_CELLS_PLATFORMS,
117 			  "Missing '#address-cells' in %pOF\n", np);
118 	}
119 	return OF_ROOT_NODE_ADDR_CELLS_DEFAULT;
120 }
121 
122 int of_n_addr_cells(struct device_node *np)
123 {
124 	if (np->parent)
125 		np = np->parent;
126 
127 	return of_bus_n_addr_cells(np);
128 }
129 EXPORT_SYMBOL(of_n_addr_cells);
130 
131 int of_bus_n_size_cells(struct device_node *np)
132 {
133 	u32 cells;
134 
135 	for (; np; np = np->parent) {
136 		if (!of_property_read_u32(np, "#size-cells", &cells))
137 			return cells;
138 		/*
139 		 * Default root value and walking parent nodes for "#size-cells"
140 		 * is deprecated. Any platforms which hit this warning should
141 		 * be added to the excluded list.
142 		 */
143 		WARN_ONCE(!EXCLUDED_DEFAULT_CELLS_PLATFORMS,
144 			  "Missing '#size-cells' in %pOF\n", np);
145 	}
146 	return OF_ROOT_NODE_SIZE_CELLS_DEFAULT;
147 }
148 
149 int of_n_size_cells(struct device_node *np)
150 {
151 	if (np->parent)
152 		np = np->parent;
153 
154 	return of_bus_n_size_cells(np);
155 }
156 EXPORT_SYMBOL(of_n_size_cells);
157 
158 #ifdef CONFIG_NUMA
159 int __weak of_node_to_nid(struct device_node *np)
160 {
161 	return NUMA_NO_NODE;
162 }
163 #endif
164 
165 #define OF_PHANDLE_CACHE_BITS	7
166 #define OF_PHANDLE_CACHE_SZ	BIT(OF_PHANDLE_CACHE_BITS)
167 
168 static struct device_node *phandle_cache[OF_PHANDLE_CACHE_SZ];
169 
170 static u32 of_phandle_cache_hash(phandle handle)
171 {
172 	return hash_32(handle, OF_PHANDLE_CACHE_BITS);
173 }
174 
175 /*
176  * Caller must hold devtree_lock.
177  */
178 void __of_phandle_cache_inv_entry(phandle handle)
179 {
180 	u32 handle_hash;
181 	struct device_node *np;
182 
183 	if (!handle)
184 		return;
185 
186 	handle_hash = of_phandle_cache_hash(handle);
187 
188 	np = phandle_cache[handle_hash];
189 	if (np && handle == np->phandle)
190 		phandle_cache[handle_hash] = NULL;
191 }
192 
193 void __init of_core_init(void)
194 {
195 	struct device_node *np;
196 
197 	of_platform_register_reconfig_notifier();
198 
199 	/* Create the kset, and register existing nodes */
200 	mutex_lock(&of_mutex);
201 	of_kset = kset_create_and_add("devicetree", NULL, firmware_kobj);
202 	if (!of_kset) {
203 		mutex_unlock(&of_mutex);
204 		pr_err("failed to register existing nodes\n");
205 		return;
206 	}
207 	for_each_of_allnodes(np) {
208 		__of_attach_node_sysfs(np);
209 		if (np->phandle && !phandle_cache[of_phandle_cache_hash(np->phandle)])
210 			phandle_cache[of_phandle_cache_hash(np->phandle)] = np;
211 	}
212 	mutex_unlock(&of_mutex);
213 
214 	/* Symlink in /proc as required by userspace ABI */
215 	if (of_root)
216 		proc_symlink("device-tree", NULL, "/sys/firmware/devicetree/base");
217 }
218 
219 static struct property *__of_find_property(const struct device_node *np,
220 					   const char *name, int *lenp)
221 {
222 	struct property *pp;
223 
224 	if (!np)
225 		return NULL;
226 
227 	for (pp = np->properties; pp; pp = pp->next) {
228 		if (of_prop_cmp(pp->name, name) == 0) {
229 			if (lenp)
230 				*lenp = pp->length;
231 			break;
232 		}
233 	}
234 
235 	return pp;
236 }
237 
238 struct property *of_find_property(const struct device_node *np,
239 				  const char *name,
240 				  int *lenp)
241 {
242 	struct property *pp;
243 	unsigned long flags;
244 
245 	raw_spin_lock_irqsave(&devtree_lock, flags);
246 	pp = __of_find_property(np, name, lenp);
247 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
248 
249 	return pp;
250 }
251 EXPORT_SYMBOL(of_find_property);
252 
253 struct device_node *__of_find_all_nodes(struct device_node *prev)
254 {
255 	struct device_node *np;
256 	if (!prev) {
257 		np = of_root;
258 	} else if (prev->child) {
259 		np = prev->child;
260 	} else {
261 		/* Walk back up looking for a sibling, or the end of the structure */
262 		np = prev;
263 		while (np->parent && !np->sibling)
264 			np = np->parent;
265 		np = np->sibling; /* Might be null at the end of the tree */
266 	}
267 	return np;
268 }
269 
270 /**
271  * of_find_all_nodes - Get next node in global list
272  * @prev:	Previous node or NULL to start iteration
273  *		of_node_put() will be called on it
274  *
275  * Return: A node pointer with refcount incremented, use
276  * of_node_put() on it when done.
277  */
278 struct device_node *of_find_all_nodes(struct device_node *prev)
279 {
280 	struct device_node *np;
281 	unsigned long flags;
282 
283 	raw_spin_lock_irqsave(&devtree_lock, flags);
284 	np = __of_find_all_nodes(prev);
285 	of_node_get(np);
286 	of_node_put(prev);
287 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
288 	return np;
289 }
290 EXPORT_SYMBOL(of_find_all_nodes);
291 
292 /*
293  * Find a property with a given name for a given node
294  * and return the value.
295  */
296 const void *__of_get_property(const struct device_node *np,
297 			      const char *name, int *lenp)
298 {
299 	const struct property *pp = __of_find_property(np, name, lenp);
300 
301 	return pp ? pp->value : NULL;
302 }
303 
304 /*
305  * Find a property with a given name for a given node
306  * and return the value.
307  */
308 const void *of_get_property(const struct device_node *np, const char *name,
309 			    int *lenp)
310 {
311 	const struct property *pp = of_find_property(np, name, lenp);
312 
313 	return pp ? pp->value : NULL;
314 }
315 EXPORT_SYMBOL(of_get_property);
316 
317 /**
318  * __of_device_is_compatible() - Check if the node matches given constraints
319  * @device: pointer to node
320  * @compat: required compatible string, NULL or "" for any match
321  * @type: required device_type value, NULL or "" for any match
322  * @name: required node name, NULL or "" for any match
323  *
324  * Checks if the given @compat, @type and @name strings match the
325  * properties of the given @device. A constraints can be skipped by
326  * passing NULL or an empty string as the constraint.
327  *
328  * Returns 0 for no match, and a positive integer on match. The return
329  * value is a relative score with larger values indicating better
330  * matches. The score is weighted for the most specific compatible value
331  * to get the highest score. Matching type is next, followed by matching
332  * name. Practically speaking, this results in the following priority
333  * order for matches:
334  *
335  * 1. specific compatible && type && name
336  * 2. specific compatible && type
337  * 3. specific compatible && name
338  * 4. specific compatible
339  * 5. general compatible && type && name
340  * 6. general compatible && type
341  * 7. general compatible && name
342  * 8. general compatible
343  * 9. type && name
344  * 10. type
345  * 11. name
346  */
347 static int __of_device_is_compatible(const struct device_node *device,
348 				     const char *compat, const char *type, const char *name)
349 {
350 	const struct property *prop;
351 	const char *cp;
352 	int index = 0, score = 0;
353 
354 	/* Compatible match has highest priority */
355 	if (compat && compat[0]) {
356 		prop = __of_find_property(device, "compatible", NULL);
357 		for (cp = of_prop_next_string(prop, NULL); cp;
358 		     cp = of_prop_next_string(prop, cp), index++) {
359 			if (of_compat_cmp(cp, compat, strlen(compat)) == 0) {
360 				score = INT_MAX/2 - (index << 2);
361 				break;
362 			}
363 		}
364 		if (!score)
365 			return 0;
366 	}
367 
368 	/* Matching type is better than matching name */
369 	if (type && type[0]) {
370 		if (!__of_node_is_type(device, type))
371 			return 0;
372 		score += 2;
373 	}
374 
375 	/* Matching name is a bit better than not */
376 	if (name && name[0]) {
377 		if (!of_node_name_eq(device, name))
378 			return 0;
379 		score++;
380 	}
381 
382 	return score;
383 }
384 
385 /** Checks if the given "compat" string matches one of the strings in
386  * the device's "compatible" property
387  */
388 int of_device_is_compatible(const struct device_node *device,
389 		const char *compat)
390 {
391 	unsigned long flags;
392 	int res;
393 
394 	raw_spin_lock_irqsave(&devtree_lock, flags);
395 	res = __of_device_is_compatible(device, compat, NULL, NULL);
396 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
397 	return res;
398 }
399 EXPORT_SYMBOL(of_device_is_compatible);
400 
401 /** Checks if the device is compatible with any of the entries in
402  *  a NULL terminated array of strings. Returns the best match
403  *  score or 0.
404  */
405 int of_device_compatible_match(const struct device_node *device,
406 			       const char *const *compat)
407 {
408 	unsigned int tmp, score = 0;
409 
410 	if (!compat)
411 		return 0;
412 
413 	while (*compat) {
414 		tmp = of_device_is_compatible(device, *compat);
415 		if (tmp > score)
416 			score = tmp;
417 		compat++;
418 	}
419 
420 	return score;
421 }
422 EXPORT_SYMBOL_GPL(of_device_compatible_match);
423 
424 /**
425  * of_machine_compatible_match - Test root of device tree against a compatible array
426  * @compats: NULL terminated array of compatible strings to look for in root node's compatible property.
427  *
428  * Returns true if the root node has any of the given compatible values in its
429  * compatible property.
430  */
431 bool of_machine_compatible_match(const char *const *compats)
432 {
433 	struct device_node *root;
434 	int rc = 0;
435 
436 	root = of_find_node_by_path("/");
437 	if (root) {
438 		rc = of_device_compatible_match(root, compats);
439 		of_node_put(root);
440 	}
441 
442 	return rc != 0;
443 }
444 EXPORT_SYMBOL(of_machine_compatible_match);
445 
446 /**
447  * of_machine_read_compatible - Get the compatible string of this machine
448  * @compatible: address at which the address of the compatible string will be
449  *              stored
450  * @index: index of the compatible entry in the list
451  *
452  * Returns:
453  * 0 on success, negative error number on failure.
454  */
455 int of_machine_read_compatible(const char **compatible, unsigned int index)
456 {
457 	return of_property_read_string_index(of_root, "compatible", index, compatible);
458 }
459 EXPORT_SYMBOL_GPL(of_machine_read_compatible);
460 
461 /**
462  * of_machine_read_model - Get the model string of this machine
463  * @model: address at which the address of the model string will be stored
464  *
465  * Returns:
466  * 0 on success, negative error number on failure.
467  */
468 int of_machine_read_model(const char **model)
469 {
470 	return of_property_read_string(of_root, "model", model);
471 }
472 EXPORT_SYMBOL_GPL(of_machine_read_model);
473 
474 /**
475  * of_machine_get_match - Test root of device tree against an of_device_id array
476  * @matches:	NULL terminated array of of_device_id match structures to search in
477  *
478  * Returns matched entry or NULL
479  */
480 const struct of_device_id *of_machine_get_match(const struct of_device_id *matches)
481 {
482 	struct device_node *root;
483 	const struct of_device_id *match = NULL;
484 
485 	root = of_find_node_by_path("/");
486 	if (root) {
487 		match = of_match_node(matches, root);
488 		of_node_put(root);
489 	}
490 
491 	return match;
492 }
493 EXPORT_SYMBOL(of_machine_get_match);
494 
495 /**
496  * of_machine_get_match_data - Tell if root of device tree has a matching of_match structure
497  * @matches:	NULL terminated array of of_device_id match structures to search in
498  *
499  * Returns data associated with matched entry or NULL
500  */
501 const void *of_machine_get_match_data(const struct of_device_id *matches)
502 {
503 	const struct of_device_id *match;
504 
505 	match = of_machine_get_match(matches);
506 	if (!match)
507 		return NULL;
508 
509 	return match->data;
510 }
511 EXPORT_SYMBOL(of_machine_get_match_data);
512 
513 static bool __of_device_is_status(const struct device_node *device,
514 				  const char * const*strings)
515 {
516 	const char *status;
517 	int statlen;
518 
519 	if (!device)
520 		return false;
521 
522 	status = __of_get_property(device, "status", &statlen);
523 	if (!status || statlen <= 0)
524 		return false;
525 	if (strnlen(status, statlen) >= statlen)
526 		return false;
527 
528 	while (*strings) {
529 		unsigned int len = strlen(*strings);
530 
531 		if ((*strings)[len - 1] == '-') {
532 			if (!strncmp(status, *strings, len))
533 				return true;
534 		} else {
535 			if (!strcmp(status, *strings))
536 				return true;
537 		}
538 		strings++;
539 	}
540 
541 	return false;
542 }
543 
544 /**
545  *  __of_device_is_available - check if a device is available for use
546  *
547  *  @device: Node to check for availability, with locks already held
548  *
549  *  Return: True if the status property is absent or set to "okay" or "ok",
550  *  false otherwise
551  */
552 static bool __of_device_is_available(const struct device_node *device)
553 {
554 	static const char * const ok[] = {"okay", "ok", NULL};
555 
556 	if (!device)
557 		return false;
558 
559 	return !__of_get_property(device, "status", NULL) ||
560 		__of_device_is_status(device, ok);
561 }
562 
563 /**
564  *  __of_device_is_reserved - check if a device is reserved
565  *
566  *  @device: Node to check for availability, with locks already held
567  *
568  *  Return: True if the status property is set to "reserved", false otherwise
569  */
570 static bool __of_device_is_reserved(const struct device_node *device)
571 {
572 	static const char * const reserved[] = {"reserved", NULL};
573 
574 	return __of_device_is_status(device, reserved);
575 }
576 
577 /**
578  *  of_device_is_available - check if a device is available for use
579  *
580  *  @device: Node to check for availability
581  *
582  *  Return: True if the status property is absent or set to "okay" or "ok",
583  *  false otherwise
584  */
585 bool of_device_is_available(const struct device_node *device)
586 {
587 	unsigned long flags;
588 	bool res;
589 
590 	raw_spin_lock_irqsave(&devtree_lock, flags);
591 	res = __of_device_is_available(device);
592 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
593 	return res;
594 
595 }
596 EXPORT_SYMBOL(of_device_is_available);
597 
598 /**
599  *  __of_device_is_fail - check if a device has status "fail" or "fail-..."
600  *
601  *  @device: Node to check status for, with locks already held
602  *
603  *  Return: True if the status property is set to "fail" or "fail-..." (for any
604  *  error code suffix), false otherwise
605  */
606 static bool __of_device_is_fail(const struct device_node *device)
607 {
608 	static const char * const fail[] = {"fail", "fail-", NULL};
609 
610 	return __of_device_is_status(device, fail);
611 }
612 
613 /**
614  *  of_device_is_big_endian - check if a device has BE registers
615  *
616  *  @device: Node to check for endianness
617  *
618  *  Return: True if the device has a "big-endian" property, or if the kernel
619  *  was compiled for BE *and* the device has a "native-endian" property.
620  *  Returns false otherwise.
621  *
622  *  Callers would nominally use ioread32be/iowrite32be if
623  *  of_device_is_big_endian() == true, or readl/writel otherwise.
624  */
625 bool of_device_is_big_endian(const struct device_node *device)
626 {
627 	if (of_property_read_bool(device, "big-endian"))
628 		return true;
629 	if (IS_ENABLED(CONFIG_CPU_BIG_ENDIAN) &&
630 	    of_property_read_bool(device, "native-endian"))
631 		return true;
632 	return false;
633 }
634 EXPORT_SYMBOL(of_device_is_big_endian);
635 
636 /**
637  * of_get_parent - Get a node's parent if any
638  * @node:	Node to get parent
639  *
640  * Return: A node pointer with refcount incremented, use
641  * of_node_put() on it when done.
642  */
643 struct device_node *of_get_parent(const struct device_node *node)
644 {
645 	struct device_node *np;
646 	unsigned long flags;
647 
648 	if (!node)
649 		return NULL;
650 
651 	raw_spin_lock_irqsave(&devtree_lock, flags);
652 	np = of_node_get(node->parent);
653 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
654 	return np;
655 }
656 EXPORT_SYMBOL(of_get_parent);
657 
658 /**
659  * of_get_next_parent - Iterate to a node's parent
660  * @node:	Node to get parent of
661  *
662  * This is like of_get_parent() except that it drops the
663  * refcount on the passed node, making it suitable for iterating
664  * through a node's parents.
665  *
666  * Return: A node pointer with refcount incremented, use
667  * of_node_put() on it when done.
668  */
669 struct device_node *of_get_next_parent(struct device_node *node)
670 {
671 	struct device_node *parent;
672 	unsigned long flags;
673 
674 	if (!node)
675 		return NULL;
676 
677 	raw_spin_lock_irqsave(&devtree_lock, flags);
678 	parent = of_node_get(node->parent);
679 	of_node_put(node);
680 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
681 	return parent;
682 }
683 EXPORT_SYMBOL(of_get_next_parent);
684 
685 static struct device_node *__of_get_next_child(const struct device_node *node,
686 						struct device_node *prev)
687 {
688 	struct device_node *next;
689 
690 	if (!node)
691 		return NULL;
692 
693 	next = prev ? prev->sibling : node->child;
694 	of_node_get(next);
695 	of_node_put(prev);
696 	return next;
697 }
698 #define __for_each_child_of_node(parent, child) \
699 	for (child = __of_get_next_child(parent, NULL); child != NULL; \
700 	     child = __of_get_next_child(parent, child))
701 
702 /**
703  * of_get_next_child - Iterate a node childs
704  * @node:	parent node
705  * @prev:	previous child of the parent node, or NULL to get first
706  *
707  * Return: A node pointer with refcount incremented, use of_node_put() on
708  * it when done. Returns NULL when prev is the last child. Decrements the
709  * refcount of prev.
710  */
711 struct device_node *of_get_next_child(const struct device_node *node,
712 	struct device_node *prev)
713 {
714 	struct device_node *next;
715 	unsigned long flags;
716 
717 	raw_spin_lock_irqsave(&devtree_lock, flags);
718 	next = __of_get_next_child(node, prev);
719 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
720 	return next;
721 }
722 EXPORT_SYMBOL(of_get_next_child);
723 
724 /**
725  * of_get_next_child_with_prefix - Find the next child node with prefix
726  * @node:	parent node
727  * @prev:	previous child of the parent node, or NULL to get first
728  * @prefix:	prefix that the node name should have
729  *
730  * This function is like of_get_next_child(), except that it automatically
731  * skips any nodes whose name doesn't have the given prefix.
732  *
733  * Return: A node pointer with refcount incremented, use
734  * of_node_put() on it when done.
735  */
736 struct device_node *of_get_next_child_with_prefix(const struct device_node *node,
737 						  struct device_node *prev,
738 						  const char *prefix)
739 {
740 	struct device_node *next;
741 	unsigned long flags;
742 
743 	if (!node)
744 		return NULL;
745 
746 	raw_spin_lock_irqsave(&devtree_lock, flags);
747 	next = prev ? prev->sibling : node->child;
748 	for (; next; next = next->sibling) {
749 		if (!of_node_name_prefix(next, prefix))
750 			continue;
751 		if (of_node_get(next))
752 			break;
753 	}
754 	of_node_put(prev);
755 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
756 	return next;
757 }
758 EXPORT_SYMBOL(of_get_next_child_with_prefix);
759 
760 static struct device_node *of_get_next_status_child(const struct device_node *node,
761 						    struct device_node *prev,
762 						    bool (*checker)(const struct device_node *))
763 {
764 	struct device_node *next;
765 	unsigned long flags;
766 
767 	if (!node)
768 		return NULL;
769 
770 	raw_spin_lock_irqsave(&devtree_lock, flags);
771 	next = prev ? prev->sibling : node->child;
772 	for (; next; next = next->sibling) {
773 		if (!checker(next))
774 			continue;
775 		if (of_node_get(next))
776 			break;
777 	}
778 	of_node_put(prev);
779 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
780 	return next;
781 }
782 
783 /**
784  * of_get_next_available_child - Find the next available child node
785  * @node:	parent node
786  * @prev:	previous child of the parent node, or NULL to get first
787  *
788  * This function is like of_get_next_child(), except that it
789  * automatically skips any disabled nodes (i.e. status = "disabled").
790  */
791 struct device_node *of_get_next_available_child(const struct device_node *node,
792 	struct device_node *prev)
793 {
794 	return of_get_next_status_child(node, prev, __of_device_is_available);
795 }
796 EXPORT_SYMBOL(of_get_next_available_child);
797 
798 /**
799  * of_get_next_reserved_child - Find the next reserved child node
800  * @node:	parent node
801  * @prev:	previous child of the parent node, or NULL to get first
802  *
803  * This function is like of_get_next_child(), except that it
804  * automatically skips any disabled nodes (i.e. status = "disabled").
805  */
806 struct device_node *of_get_next_reserved_child(const struct device_node *node,
807 						struct device_node *prev)
808 {
809 	return of_get_next_status_child(node, prev, __of_device_is_reserved);
810 }
811 EXPORT_SYMBOL(of_get_next_reserved_child);
812 
813 /**
814  * of_get_next_cpu_node - Iterate on cpu nodes
815  * @prev:	previous child of the /cpus node, or NULL to get first
816  *
817  * Unusable CPUs (those with the status property set to "fail" or "fail-...")
818  * will be skipped.
819  *
820  * Return: A cpu node pointer with refcount incremented, use of_node_put()
821  * on it when done. Returns NULL when prev is the last child. Decrements
822  * the refcount of prev.
823  */
824 struct device_node *of_get_next_cpu_node(struct device_node *prev)
825 {
826 	struct device_node *next = NULL;
827 	unsigned long flags;
828 	struct device_node *node;
829 
830 	if (!prev)
831 		node = of_find_node_by_path("/cpus");
832 
833 	raw_spin_lock_irqsave(&devtree_lock, flags);
834 	if (prev)
835 		next = prev->sibling;
836 	else if (node) {
837 		next = node->child;
838 		of_node_put(node);
839 	}
840 	for (; next; next = next->sibling) {
841 		if (__of_device_is_fail(next))
842 			continue;
843 		if (!(of_node_name_eq(next, "cpu") ||
844 		      __of_node_is_type(next, "cpu")))
845 			continue;
846 		if (of_node_get(next))
847 			break;
848 	}
849 	of_node_put(prev);
850 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
851 	return next;
852 }
853 EXPORT_SYMBOL(of_get_next_cpu_node);
854 
855 /**
856  * of_get_compatible_child - Find compatible child node
857  * @parent:	parent node
858  * @compatible:	compatible string
859  *
860  * Lookup child node whose compatible property contains the given compatible
861  * string.
862  *
863  * Return: a node pointer with refcount incremented, use of_node_put() on it
864  * when done; or NULL if not found.
865  */
866 struct device_node *of_get_compatible_child(const struct device_node *parent,
867 				const char *compatible)
868 {
869 	struct device_node *child;
870 
871 	for_each_child_of_node(parent, child) {
872 		if (of_device_is_compatible(child, compatible))
873 			break;
874 	}
875 
876 	return child;
877 }
878 EXPORT_SYMBOL(of_get_compatible_child);
879 
880 /**
881  * of_get_child_by_name - Find the child node by name for a given parent
882  * @node:	parent node
883  * @name:	child name to look for.
884  *
885  * This function looks for child node for given matching name
886  *
887  * Return: A node pointer if found, with refcount incremented, use
888  * of_node_put() on it when done.
889  * Returns NULL if node is not found.
890  */
891 struct device_node *of_get_child_by_name(const struct device_node *node,
892 				const char *name)
893 {
894 	struct device_node *child;
895 
896 	for_each_child_of_node(node, child)
897 		if (of_node_name_eq(child, name))
898 			break;
899 	return child;
900 }
901 EXPORT_SYMBOL(of_get_child_by_name);
902 
903 /**
904  * of_get_available_child_by_name - Find the available child node by name for a given parent
905  * @node:	parent node
906  * @name:	child name to look for.
907  *
908  * This function looks for child node for given matching name and checks the
909  * device's availability for use.
910  *
911  * Return: A node pointer if found, with refcount incremented, use
912  * of_node_put() on it when done.
913  * Returns NULL if node is not found.
914  */
915 struct device_node *of_get_available_child_by_name(const struct device_node *node,
916 						   const char *name)
917 {
918 	struct device_node *child;
919 
920 	child = of_get_child_by_name(node, name);
921 	if (child && !of_device_is_available(child)) {
922 		of_node_put(child);
923 		return NULL;
924 	}
925 
926 	return child;
927 }
928 EXPORT_SYMBOL(of_get_available_child_by_name);
929 
930 struct device_node *__of_find_node_by_path(const struct device_node *parent,
931 						const char *path)
932 {
933 	struct device_node *child;
934 	int len;
935 
936 	len = strcspn(path, "/:");
937 	if (!len)
938 		return NULL;
939 
940 	__for_each_child_of_node(parent, child) {
941 		const char *name = kbasename(child->full_name);
942 		if (strncmp(path, name, len) == 0 && (strlen(name) == len))
943 			return child;
944 	}
945 	return NULL;
946 }
947 
948 struct device_node *__of_find_node_by_full_path(struct device_node *node,
949 						const char *path)
950 {
951 	const char *separator = strchr(path, ':');
952 
953 	while (node && *path == '/') {
954 		struct device_node *tmp = node;
955 
956 		path++; /* Increment past '/' delimiter */
957 		node = __of_find_node_by_path(node, path);
958 		of_node_put(tmp);
959 		path = strchrnul(path, '/');
960 		if (separator && separator < path)
961 			break;
962 	}
963 	return node;
964 }
965 
966 /**
967  * of_find_node_opts_by_path - Find a node matching a full OF path
968  * @path: Either the full path to match, or if the path does not
969  *       start with '/', the name of a property of the /aliases
970  *       node (an alias).  In the case of an alias, the node
971  *       matching the alias' value will be returned.
972  * @opts: Address of a pointer into which to store the start of
973  *       an options string appended to the end of the path with
974  *       a ':' separator.
975  *
976  * Valid paths:
977  *  * /foo/bar	Full path
978  *  * foo	Valid alias
979  *  * foo/bar	Valid alias + relative path
980  *
981  * Return: A node pointer with refcount incremented, use
982  * of_node_put() on it when done.
983  */
984 struct device_node *of_find_node_opts_by_path(const char *path, const char **opts)
985 {
986 	struct device_node *np = NULL;
987 	const struct property *pp;
988 	unsigned long flags;
989 	const char *separator = strchr(path, ':');
990 
991 	if (opts)
992 		*opts = separator ? separator + 1 : NULL;
993 
994 	if (strcmp(path, "/") == 0)
995 		return of_node_get(of_root);
996 
997 	/* The path could begin with an alias */
998 	if (*path != '/') {
999 		int len;
1000 		const char *p = strchrnul(path, '/');
1001 
1002 		if (separator && separator < p)
1003 			p = separator;
1004 		len = p - path;
1005 
1006 		/* of_aliases must not be NULL */
1007 		if (!of_aliases)
1008 			return NULL;
1009 
1010 		for_each_property_of_node(of_aliases, pp) {
1011 			if (strlen(pp->name) == len && !strncmp(pp->name, path, len)) {
1012 				np = of_find_node_by_path(pp->value);
1013 				break;
1014 			}
1015 		}
1016 		if (!np)
1017 			return NULL;
1018 		path = p;
1019 	}
1020 
1021 	/* Step down the tree matching path components */
1022 	raw_spin_lock_irqsave(&devtree_lock, flags);
1023 	if (!np)
1024 		np = of_node_get(of_root);
1025 	np = __of_find_node_by_full_path(np, path);
1026 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
1027 	return np;
1028 }
1029 EXPORT_SYMBOL(of_find_node_opts_by_path);
1030 
1031 /**
1032  * of_find_node_by_name - Find a node by its "name" property
1033  * @from:	The node to start searching from or NULL; the node
1034  *		you pass will not be searched, only the next one
1035  *		will. Typically, you pass what the previous call
1036  *		returned. of_node_put() will be called on @from.
1037  * @name:	The name string to match against
1038  *
1039  * Return: A node pointer with refcount incremented, use
1040  * of_node_put() on it when done.
1041  */
1042 struct device_node *of_find_node_by_name(struct device_node *from,
1043 	const char *name)
1044 {
1045 	struct device_node *np;
1046 	unsigned long flags;
1047 
1048 	raw_spin_lock_irqsave(&devtree_lock, flags);
1049 	for_each_of_allnodes_from(from, np)
1050 		if (of_node_name_eq(np, name) && of_node_get(np))
1051 			break;
1052 	of_node_put(from);
1053 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
1054 	return np;
1055 }
1056 EXPORT_SYMBOL(of_find_node_by_name);
1057 
1058 /**
1059  * of_find_node_by_type - Find a node by its "device_type" property
1060  * @from:	The node to start searching from, or NULL to start searching
1061  *		the entire device tree. The node you pass will not be
1062  *		searched, only the next one will; typically, you pass
1063  *		what the previous call returned. of_node_put() will be
1064  *		called on from for you.
1065  * @type:	The type string to match against
1066  *
1067  * Return: A node pointer with refcount incremented, use
1068  * of_node_put() on it when done.
1069  */
1070 struct device_node *of_find_node_by_type(struct device_node *from,
1071 	const char *type)
1072 {
1073 	struct device_node *np;
1074 	unsigned long flags;
1075 
1076 	raw_spin_lock_irqsave(&devtree_lock, flags);
1077 	for_each_of_allnodes_from(from, np)
1078 		if (__of_node_is_type(np, type) && of_node_get(np))
1079 			break;
1080 	of_node_put(from);
1081 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
1082 	return np;
1083 }
1084 EXPORT_SYMBOL(of_find_node_by_type);
1085 
1086 /**
1087  * of_find_compatible_node - Find a node based on type and one of the
1088  *                                tokens in its "compatible" property
1089  * @from:	The node to start searching from or NULL, the node
1090  *		you pass will not be searched, only the next one
1091  *		will; typically, you pass what the previous call
1092  *		returned. of_node_put() will be called on it
1093  * @type:	The type string to match "device_type" or NULL to ignore
1094  * @compatible:	The string to match to one of the tokens in the device
1095  *		"compatible" list.
1096  *
1097  * Return: A node pointer with refcount incremented, use
1098  * of_node_put() on it when done.
1099  */
1100 struct device_node *of_find_compatible_node(struct device_node *from,
1101 	const char *type, const char *compatible)
1102 {
1103 	struct device_node *np;
1104 	unsigned long flags;
1105 
1106 	raw_spin_lock_irqsave(&devtree_lock, flags);
1107 	for_each_of_allnodes_from(from, np)
1108 		if (__of_device_is_compatible(np, compatible, type, NULL) &&
1109 		    of_node_get(np))
1110 			break;
1111 	of_node_put(from);
1112 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
1113 	return np;
1114 }
1115 EXPORT_SYMBOL(of_find_compatible_node);
1116 
1117 /**
1118  * of_find_node_with_property - Find a node which has a property with
1119  *                              the given name.
1120  * @from:	The node to start searching from or NULL, the node
1121  *		you pass will not be searched, only the next one
1122  *		will; typically, you pass what the previous call
1123  *		returned. of_node_put() will be called on it
1124  * @prop_name:	The name of the property to look for.
1125  *
1126  * Return: A node pointer with refcount incremented, use
1127  * of_node_put() on it when done.
1128  */
1129 struct device_node *of_find_node_with_property(struct device_node *from,
1130 	const char *prop_name)
1131 {
1132 	struct device_node *np;
1133 	unsigned long flags;
1134 
1135 	raw_spin_lock_irqsave(&devtree_lock, flags);
1136 	for_each_of_allnodes_from(from, np) {
1137 		if (__of_find_property(np, prop_name, NULL)) {
1138 			of_node_get(np);
1139 			break;
1140 		}
1141 	}
1142 	of_node_put(from);
1143 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
1144 	return np;
1145 }
1146 EXPORT_SYMBOL(of_find_node_with_property);
1147 
1148 static
1149 const struct of_device_id *__of_match_node(const struct of_device_id *matches,
1150 					   const struct device_node *node)
1151 {
1152 	const struct of_device_id *best_match = NULL;
1153 	int score, best_score = 0;
1154 
1155 	if (!matches)
1156 		return NULL;
1157 
1158 	for (; matches->name[0] || matches->type[0] || matches->compatible[0]; matches++) {
1159 		score = __of_device_is_compatible(node, matches->compatible,
1160 						  matches->type, matches->name);
1161 		if (score > best_score) {
1162 			best_match = matches;
1163 			best_score = score;
1164 		}
1165 	}
1166 
1167 	return best_match;
1168 }
1169 
1170 /**
1171  * of_match_node - Tell if a device_node has a matching of_match structure
1172  * @matches:	array of of device match structures to search in
1173  * @node:	the of device structure to match against
1174  *
1175  * Low level utility function used by device matching.
1176  */
1177 const struct of_device_id *of_match_node(const struct of_device_id *matches,
1178 					 const struct device_node *node)
1179 {
1180 	const struct of_device_id *match;
1181 	unsigned long flags;
1182 
1183 	raw_spin_lock_irqsave(&devtree_lock, flags);
1184 	match = __of_match_node(matches, node);
1185 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
1186 	return match;
1187 }
1188 EXPORT_SYMBOL(of_match_node);
1189 
1190 /**
1191  * of_find_matching_node_and_match - Find a node based on an of_device_id
1192  *				     match table.
1193  * @from:	The node to start searching from or NULL, the node
1194  *		you pass will not be searched, only the next one
1195  *		will; typically, you pass what the previous call
1196  *		returned. of_node_put() will be called on it
1197  * @matches:	array of of device match structures to search in
1198  * @match:	Updated to point at the matches entry which matched
1199  *
1200  * Return: A node pointer with refcount incremented, use
1201  * of_node_put() on it when done.
1202  */
1203 struct device_node *of_find_matching_node_and_match(struct device_node *from,
1204 					const struct of_device_id *matches,
1205 					const struct of_device_id **match)
1206 {
1207 	struct device_node *np;
1208 	const struct of_device_id *m;
1209 	unsigned long flags;
1210 
1211 	if (match)
1212 		*match = NULL;
1213 
1214 	raw_spin_lock_irqsave(&devtree_lock, flags);
1215 	for_each_of_allnodes_from(from, np) {
1216 		m = __of_match_node(matches, np);
1217 		if (m && of_node_get(np)) {
1218 			if (match)
1219 				*match = m;
1220 			break;
1221 		}
1222 	}
1223 	of_node_put(from);
1224 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
1225 	return np;
1226 }
1227 EXPORT_SYMBOL(of_find_matching_node_and_match);
1228 
1229 /**
1230  * of_alias_from_compatible - Lookup appropriate alias for a device node
1231  *			      depending on compatible
1232  * @node:	pointer to a device tree node
1233  * @alias:	Pointer to buffer that alias value will be copied into
1234  * @len:	Length of alias value
1235  *
1236  * Based on the value of the compatible property, this routine will attempt
1237  * to choose an appropriate alias value for a particular device tree node.
1238  * It does this by stripping the manufacturer prefix (as delimited by a ',')
1239  * from the first entry in the compatible list property.
1240  *
1241  * Note: The matching on just the "product" side of the compatible is a relic
1242  * from I2C and SPI. Please do not add any new user.
1243  *
1244  * Return: This routine returns 0 on success, <0 on failure.
1245  */
1246 int of_alias_from_compatible(const struct device_node *node, char *alias, int len)
1247 {
1248 	const char *compatible, *p;
1249 	int ret;
1250 
1251 	ret = of_property_read_string_index(node, "compatible", 0,
1252 					    &compatible);
1253 	if (ret)
1254 		return -ENODEV;
1255 	p = strchr(compatible, ',');
1256 	strscpy(alias, p ? p + 1 : compatible, len);
1257 	return 0;
1258 }
1259 EXPORT_SYMBOL_GPL(of_alias_from_compatible);
1260 
1261 /**
1262  * of_find_node_by_phandle - Find a node given a phandle
1263  * @handle:	phandle of the node to find
1264  *
1265  * Return: A node pointer with refcount incremented, use
1266  * of_node_put() on it when done.
1267  */
1268 struct device_node *of_find_node_by_phandle(phandle handle)
1269 {
1270 	struct device_node *np = NULL;
1271 	unsigned long flags;
1272 	u32 handle_hash;
1273 
1274 	if (!handle)
1275 		return NULL;
1276 
1277 	handle_hash = of_phandle_cache_hash(handle);
1278 
1279 	raw_spin_lock_irqsave(&devtree_lock, flags);
1280 
1281 	if (phandle_cache[handle_hash] &&
1282 	    handle == phandle_cache[handle_hash]->phandle)
1283 		np = phandle_cache[handle_hash];
1284 
1285 	if (!np) {
1286 		for_each_of_allnodes(np)
1287 			if (np->phandle == handle &&
1288 			    !of_node_check_flag(np, OF_DETACHED)) {
1289 				phandle_cache[handle_hash] = np;
1290 				break;
1291 			}
1292 	}
1293 
1294 	of_node_get(np);
1295 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
1296 	return np;
1297 }
1298 EXPORT_SYMBOL(of_find_node_by_phandle);
1299 
1300 void of_print_phandle_args(const char *msg, const struct of_phandle_args *args)
1301 {
1302 	int i;
1303 	printk("%s %pOF", msg, args->np);
1304 	for (i = 0; i < args->args_count; i++) {
1305 		const char delim = i ? ',' : ':';
1306 
1307 		pr_cont("%c%08x", delim, args->args[i]);
1308 	}
1309 	pr_cont("\n");
1310 }
1311 
1312 int of_phandle_iterator_init(struct of_phandle_iterator *it,
1313 		const struct device_node *np,
1314 		const char *list_name,
1315 		const char *cells_name,
1316 		int cell_count)
1317 {
1318 	const __be32 *list;
1319 	int size;
1320 
1321 	memset(it, 0, sizeof(*it));
1322 
1323 	/*
1324 	 * one of cell_count or cells_name must be provided to determine the
1325 	 * argument length.
1326 	 */
1327 	if (cell_count < 0 && !cells_name)
1328 		return -EINVAL;
1329 
1330 	list = of_get_property(np, list_name, &size);
1331 	if (!list)
1332 		return -ENOENT;
1333 
1334 	it->cells_name = cells_name;
1335 	it->cell_count = cell_count;
1336 	it->parent = np;
1337 	it->list_end = list + size / sizeof(*list);
1338 	it->phandle_end = list;
1339 	it->cur = list;
1340 
1341 	return 0;
1342 }
1343 EXPORT_SYMBOL_GPL(of_phandle_iterator_init);
1344 
1345 int of_phandle_iterator_next(struct of_phandle_iterator *it)
1346 {
1347 	uint32_t count = 0;
1348 
1349 	if (it->node) {
1350 		of_node_put(it->node);
1351 		it->node = NULL;
1352 	}
1353 
1354 	if (!it->cur || it->phandle_end >= it->list_end)
1355 		return -ENOENT;
1356 
1357 	it->cur = it->phandle_end;
1358 
1359 	/* If phandle is 0, then it is an empty entry with no arguments. */
1360 	it->phandle = be32_to_cpup(it->cur++);
1361 
1362 	if (it->phandle) {
1363 
1364 		/*
1365 		 * Find the provider node and parse the #*-cells property to
1366 		 * determine the argument length.
1367 		 */
1368 		it->node = of_find_node_by_phandle(it->phandle);
1369 
1370 		if (it->cells_name) {
1371 			if (!it->node) {
1372 				pr_err("%pOF: could not find phandle %d\n",
1373 				       it->parent, it->phandle);
1374 				goto err;
1375 			}
1376 
1377 			if (of_property_read_u32(it->node, it->cells_name,
1378 						 &count)) {
1379 				/*
1380 				 * If both cell_count and cells_name is given,
1381 				 * fall back to cell_count in absence
1382 				 * of the cells_name property
1383 				 */
1384 				if (it->cell_count >= 0) {
1385 					count = it->cell_count;
1386 				} else {
1387 					pr_err("%pOF: could not get %s for %pOF\n",
1388 					       it->parent,
1389 					       it->cells_name,
1390 					       it->node);
1391 					goto err;
1392 				}
1393 			}
1394 		} else {
1395 			count = it->cell_count;
1396 		}
1397 
1398 		/*
1399 		 * Make sure that the arguments actually fit in the remaining
1400 		 * property data length
1401 		 */
1402 		if (it->cur + count > it->list_end) {
1403 			if (it->cells_name)
1404 				pr_err("%pOF: %s = %d found %td\n",
1405 					it->parent, it->cells_name,
1406 					count, it->list_end - it->cur);
1407 			else
1408 				pr_err("%pOF: phandle %s needs %d, found %td\n",
1409 					it->parent, of_node_full_name(it->node),
1410 					count, it->list_end - it->cur);
1411 			goto err;
1412 		}
1413 	}
1414 
1415 	it->phandle_end = it->cur + count;
1416 	it->cur_count = count;
1417 
1418 	return 0;
1419 
1420 err:
1421 	if (it->node) {
1422 		of_node_put(it->node);
1423 		it->node = NULL;
1424 	}
1425 
1426 	return -EINVAL;
1427 }
1428 EXPORT_SYMBOL_GPL(of_phandle_iterator_next);
1429 
1430 int of_phandle_iterator_args(struct of_phandle_iterator *it,
1431 			     uint32_t *args,
1432 			     int size)
1433 {
1434 	int i, count;
1435 
1436 	count = it->cur_count;
1437 
1438 	if (WARN_ON(size < count))
1439 		count = size;
1440 
1441 	for (i = 0; i < count; i++)
1442 		args[i] = be32_to_cpup(it->cur++);
1443 
1444 	return count;
1445 }
1446 
1447 int __of_parse_phandle_with_args(const struct device_node *np,
1448 				 const char *list_name,
1449 				 const char *cells_name,
1450 				 int cell_count, int index,
1451 				 struct of_phandle_args *out_args)
1452 {
1453 	struct of_phandle_iterator it;
1454 	int rc, cur_index = 0;
1455 
1456 	if (index < 0)
1457 		return -EINVAL;
1458 
1459 	/* Loop over the phandles until all the requested entry is found */
1460 	of_for_each_phandle(&it, rc, np, list_name, cells_name, cell_count) {
1461 		/*
1462 		 * All of the error cases bail out of the loop, so at
1463 		 * this point, the parsing is successful. If the requested
1464 		 * index matches, then fill the out_args structure and return,
1465 		 * or return -ENOENT for an empty entry.
1466 		 */
1467 		rc = -ENOENT;
1468 		if (cur_index == index) {
1469 			if (!it.phandle)
1470 				goto err;
1471 
1472 			if (out_args) {
1473 				int c;
1474 
1475 				c = of_phandle_iterator_args(&it,
1476 							     out_args->args,
1477 							     MAX_PHANDLE_ARGS);
1478 				out_args->np = it.node;
1479 				out_args->args_count = c;
1480 			} else {
1481 				of_node_put(it.node);
1482 			}
1483 
1484 			/* Found it! return success */
1485 			return 0;
1486 		}
1487 
1488 		cur_index++;
1489 	}
1490 
1491 	/*
1492 	 * Unlock node before returning result; will be one of:
1493 	 * -ENOENT : index is for empty phandle
1494 	 * -EINVAL : parsing error on data
1495 	 */
1496 
1497  err:
1498 	of_node_put(it.node);
1499 	return rc;
1500 }
1501 EXPORT_SYMBOL(__of_parse_phandle_with_args);
1502 
1503 /**
1504  * of_parse_phandle_with_args_map() - Find a node pointed by phandle in a list and remap it
1505  * @np:		pointer to a device tree node containing a list
1506  * @list_name:	property name that contains a list
1507  * @stem_name:	stem of property names that specify phandles' arguments count
1508  * @index:	index of a phandle to parse out
1509  * @out_args:	optional pointer to output arguments structure (will be filled)
1510  *
1511  * This function is useful to parse lists of phandles and their arguments.
1512  * Returns 0 on success and fills out_args, on error returns appropriate errno
1513  * value. The difference between this function and of_parse_phandle_with_args()
1514  * is that this API remaps a phandle if the node the phandle points to has
1515  * a <@stem_name>-map property.
1516  *
1517  * Caller is responsible to call of_node_put() on the returned out_args->np
1518  * pointer.
1519  *
1520  * Example::
1521  *
1522  *  phandle1: node1 {
1523  *  	#list-cells = <2>;
1524  *  };
1525  *
1526  *  phandle2: node2 {
1527  *  	#list-cells = <1>;
1528  *  };
1529  *
1530  *  phandle3: node3 {
1531  *  	#list-cells = <1>;
1532  *  	list-map = <0 &phandle2 3>,
1533  *  		   <1 &phandle2 2>,
1534  *  		   <2 &phandle1 5 1>;
1535  *  	list-map-mask = <0x3>;
1536  *  };
1537  *
1538  *  node4 {
1539  *  	list = <&phandle1 1 2 &phandle3 0>;
1540  *  };
1541  *
1542  * To get a device_node of the ``node2`` node you may call this:
1543  * of_parse_phandle_with_args(node4, "list", "list", 1, &args);
1544  */
1545 int of_parse_phandle_with_args_map(const struct device_node *np,
1546 				   const char *list_name,
1547 				   const char *stem_name,
1548 				   int index, struct of_phandle_args *out_args)
1549 {
1550 	char *cells_name __free(kfree) = kasprintf(GFP_KERNEL, "#%s-cells", stem_name);
1551 	char *map_name __free(kfree) = kasprintf(GFP_KERNEL, "%s-map", stem_name);
1552 	char *mask_name __free(kfree) = kasprintf(GFP_KERNEL, "%s-map-mask", stem_name);
1553 	char *pass_name __free(kfree) = kasprintf(GFP_KERNEL, "%s-map-pass-thru", stem_name);
1554 	struct device_node *cur, *new = NULL;
1555 	const __be32 *map, *mask, *pass;
1556 	static const __be32 dummy_mask[] = { [0 ... (MAX_PHANDLE_ARGS - 1)] = cpu_to_be32(~0) };
1557 	static const __be32 dummy_pass[] = { [0 ... (MAX_PHANDLE_ARGS - 1)] = cpu_to_be32(0) };
1558 	__be32 initial_match_array[MAX_PHANDLE_ARGS];
1559 	const __be32 *match_array = initial_match_array;
1560 	int i, ret, map_len, match;
1561 	u32 list_size, new_size;
1562 
1563 	if (index < 0)
1564 		return -EINVAL;
1565 
1566 	if (!cells_name || !map_name || !mask_name || !pass_name)
1567 		return -ENOMEM;
1568 
1569 	ret = __of_parse_phandle_with_args(np, list_name, cells_name, -1, index,
1570 					   out_args);
1571 	if (ret)
1572 		return ret;
1573 
1574 	/* Get the #<list>-cells property */
1575 	cur = out_args->np;
1576 	ret = of_property_read_u32(cur, cells_name, &list_size);
1577 	if (ret < 0)
1578 		goto put;
1579 
1580 	/* Precalculate the match array - this simplifies match loop */
1581 	for (i = 0; i < list_size; i++)
1582 		initial_match_array[i] = cpu_to_be32(out_args->args[i]);
1583 
1584 	ret = -EINVAL;
1585 	while (cur) {
1586 		/* Get the <list>-map property */
1587 		map = of_get_property(cur, map_name, &map_len);
1588 		if (!map) {
1589 			return 0;
1590 		}
1591 		map_len /= sizeof(u32);
1592 
1593 		/* Get the <list>-map-mask property (optional) */
1594 		mask = of_get_property(cur, mask_name, NULL);
1595 		if (!mask)
1596 			mask = dummy_mask;
1597 		/* Iterate through <list>-map property */
1598 		match = 0;
1599 		while (map_len > (list_size + 1) && !match) {
1600 			/* Compare specifiers */
1601 			match = 1;
1602 			for (i = 0; i < list_size; i++, map_len--)
1603 				match &= !((match_array[i] ^ *map++) & mask[i]);
1604 
1605 			of_node_put(new);
1606 			new = of_find_node_by_phandle(be32_to_cpup(map));
1607 			map++;
1608 			map_len--;
1609 
1610 			/* Check if not found */
1611 			if (!new) {
1612 				ret = -EINVAL;
1613 				goto put;
1614 			}
1615 
1616 			if (!of_device_is_available(new))
1617 				match = 0;
1618 
1619 			ret = of_property_read_u32(new, cells_name, &new_size);
1620 			if (ret)
1621 				goto put;
1622 
1623 			/* Check for malformed properties */
1624 			if (WARN_ON(new_size > MAX_PHANDLE_ARGS) ||
1625 			    map_len < new_size) {
1626 				ret = -EINVAL;
1627 				goto put;
1628 			}
1629 
1630 			/* Move forward by new node's #<list>-cells amount */
1631 			map += new_size;
1632 			map_len -= new_size;
1633 		}
1634 		if (!match) {
1635 			ret = -ENOENT;
1636 			goto put;
1637 		}
1638 
1639 		/* Get the <list>-map-pass-thru property (optional) */
1640 		pass = of_get_property(cur, pass_name, NULL);
1641 		if (!pass)
1642 			pass = dummy_pass;
1643 
1644 		/*
1645 		 * Successfully parsed a <list>-map translation; copy new
1646 		 * specifier into the out_args structure, keeping the
1647 		 * bits specified in <list>-map-pass-thru.
1648 		 */
1649 		for (i = 0; i < new_size; i++) {
1650 			__be32 val = *(map - new_size + i);
1651 
1652 			if (i < list_size) {
1653 				val &= ~pass[i];
1654 				val |= cpu_to_be32(out_args->args[i]) & pass[i];
1655 			}
1656 
1657 			initial_match_array[i] = val;
1658 			out_args->args[i] = be32_to_cpu(val);
1659 		}
1660 		out_args->args_count = list_size = new_size;
1661 		/* Iterate again with new provider */
1662 		out_args->np = new;
1663 		of_node_put(cur);
1664 		cur = new;
1665 		new = NULL;
1666 	}
1667 put:
1668 	of_node_put(cur);
1669 	of_node_put(new);
1670 	return ret;
1671 }
1672 EXPORT_SYMBOL(of_parse_phandle_with_args_map);
1673 
1674 /**
1675  * of_count_phandle_with_args() - Find the number of phandles references in a property
1676  * @np:		pointer to a device tree node containing a list
1677  * @list_name:	property name that contains a list
1678  * @cells_name:	property name that specifies phandles' arguments count
1679  *
1680  * Return: The number of phandle + argument tuples within a property. It
1681  * is a typical pattern to encode a list of phandle and variable
1682  * arguments into a single property. The number of arguments is encoded
1683  * by a property in the phandle-target node. For example, a gpios
1684  * property would contain a list of GPIO specifies consisting of a
1685  * phandle and 1 or more arguments. The number of arguments are
1686  * determined by the #gpio-cells property in the node pointed to by the
1687  * phandle.
1688  */
1689 int of_count_phandle_with_args(const struct device_node *np, const char *list_name,
1690 				const char *cells_name)
1691 {
1692 	struct of_phandle_iterator it;
1693 	int rc, cur_index = 0;
1694 
1695 	/*
1696 	 * If cells_name is NULL we assume a cell count of 0. This makes
1697 	 * counting the phandles trivial as each 32bit word in the list is a
1698 	 * phandle and no arguments are to consider. So we don't iterate through
1699 	 * the list but just use the length to determine the phandle count.
1700 	 */
1701 	if (!cells_name) {
1702 		const __be32 *list;
1703 		int size;
1704 
1705 		list = of_get_property(np, list_name, &size);
1706 		if (!list)
1707 			return -ENOENT;
1708 
1709 		return size / sizeof(*list);
1710 	}
1711 
1712 	rc = of_phandle_iterator_init(&it, np, list_name, cells_name, -1);
1713 	if (rc)
1714 		return rc;
1715 
1716 	while ((rc = of_phandle_iterator_next(&it)) == 0)
1717 		cur_index += 1;
1718 
1719 	if (rc != -ENOENT)
1720 		return rc;
1721 
1722 	return cur_index;
1723 }
1724 EXPORT_SYMBOL(of_count_phandle_with_args);
1725 
1726 static struct property *__of_remove_property_from_list(struct property **list, struct property *prop)
1727 {
1728 	struct property **next;
1729 
1730 	for (next = list; *next; next = &(*next)->next) {
1731 		if (*next == prop) {
1732 			*next = prop->next;
1733 			prop->next = NULL;
1734 			return prop;
1735 		}
1736 	}
1737 	return NULL;
1738 }
1739 
1740 /**
1741  * __of_add_property - Add a property to a node without lock operations
1742  * @np:		Caller's Device Node
1743  * @prop:	Property to add
1744  */
1745 int __of_add_property(struct device_node *np, struct property *prop)
1746 {
1747 	int rc = 0;
1748 	unsigned long flags;
1749 	struct property **next;
1750 
1751 	raw_spin_lock_irqsave(&devtree_lock, flags);
1752 
1753 	__of_remove_property_from_list(&np->deadprops, prop);
1754 
1755 	prop->next = NULL;
1756 	next = &np->properties;
1757 	while (*next) {
1758 		if (of_prop_cmp(prop->name, (*next)->name) == 0) {
1759 			/* duplicate ! don't insert it */
1760 			rc = -EEXIST;
1761 			goto out_unlock;
1762 		}
1763 		next = &(*next)->next;
1764 	}
1765 	*next = prop;
1766 
1767 out_unlock:
1768 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
1769 	if (rc)
1770 		return rc;
1771 
1772 	__of_add_property_sysfs(np, prop);
1773 	return 0;
1774 }
1775 
1776 /**
1777  * of_add_property - Add a property to a node
1778  * @np:		Caller's Device Node
1779  * @prop:	Property to add
1780  */
1781 int of_add_property(struct device_node *np, struct property *prop)
1782 {
1783 	int rc;
1784 
1785 	mutex_lock(&of_mutex);
1786 	rc = __of_add_property(np, prop);
1787 	mutex_unlock(&of_mutex);
1788 
1789 	if (!rc)
1790 		of_property_notify(OF_RECONFIG_ADD_PROPERTY, np, prop, NULL);
1791 
1792 	return rc;
1793 }
1794 EXPORT_SYMBOL_GPL(of_add_property);
1795 
1796 int __of_remove_property(struct device_node *np, struct property *prop)
1797 {
1798 	unsigned long flags;
1799 	int rc = -ENODEV;
1800 
1801 	raw_spin_lock_irqsave(&devtree_lock, flags);
1802 
1803 	if (__of_remove_property_from_list(&np->properties, prop)) {
1804 		/* Found the property, add it to deadprops list */
1805 		prop->next = np->deadprops;
1806 		np->deadprops = prop;
1807 		rc = 0;
1808 	}
1809 
1810 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
1811 	if (rc)
1812 		return rc;
1813 
1814 	__of_remove_property_sysfs(np, prop);
1815 	return 0;
1816 }
1817 
1818 /**
1819  * of_remove_property - Remove a property from a node.
1820  * @np:		Caller's Device Node
1821  * @prop:	Property to remove
1822  *
1823  * Note that we don't actually remove it, since we have given out
1824  * who-knows-how-many pointers to the data using get-property.
1825  * Instead we just move the property to the "dead properties"
1826  * list, so it won't be found any more.
1827  */
1828 int of_remove_property(struct device_node *np, struct property *prop)
1829 {
1830 	int rc;
1831 
1832 	if (!prop)
1833 		return -ENODEV;
1834 
1835 	mutex_lock(&of_mutex);
1836 	rc = __of_remove_property(np, prop);
1837 	mutex_unlock(&of_mutex);
1838 
1839 	if (!rc)
1840 		of_property_notify(OF_RECONFIG_REMOVE_PROPERTY, np, prop, NULL);
1841 
1842 	return rc;
1843 }
1844 EXPORT_SYMBOL_GPL(of_remove_property);
1845 
1846 int __of_update_property(struct device_node *np, struct property *newprop,
1847 		struct property **oldpropp)
1848 {
1849 	struct property **next, *oldprop;
1850 	unsigned long flags;
1851 
1852 	raw_spin_lock_irqsave(&devtree_lock, flags);
1853 
1854 	__of_remove_property_from_list(&np->deadprops, newprop);
1855 
1856 	for (next = &np->properties; *next; next = &(*next)->next) {
1857 		if (of_prop_cmp((*next)->name, newprop->name) == 0)
1858 			break;
1859 	}
1860 	*oldpropp = oldprop = *next;
1861 
1862 	if (oldprop) {
1863 		/* replace the node */
1864 		newprop->next = oldprop->next;
1865 		*next = newprop;
1866 		oldprop->next = np->deadprops;
1867 		np->deadprops = oldprop;
1868 	} else {
1869 		/* new node */
1870 		newprop->next = NULL;
1871 		*next = newprop;
1872 	}
1873 
1874 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
1875 
1876 	__of_update_property_sysfs(np, newprop, oldprop);
1877 
1878 	return 0;
1879 }
1880 
1881 /*
1882  * of_update_property - Update a property in a node, if the property does
1883  * not exist, add it.
1884  *
1885  * Note that we don't actually remove it, since we have given out
1886  * who-knows-how-many pointers to the data using get-property.
1887  * Instead we just move the property to the "dead properties" list,
1888  * and add the new property to the property list
1889  */
1890 int of_update_property(struct device_node *np, struct property *newprop)
1891 {
1892 	struct property *oldprop;
1893 	int rc;
1894 
1895 	if (!newprop->name)
1896 		return -EINVAL;
1897 
1898 	mutex_lock(&of_mutex);
1899 	rc = __of_update_property(np, newprop, &oldprop);
1900 	mutex_unlock(&of_mutex);
1901 
1902 	if (!rc)
1903 		of_property_notify(OF_RECONFIG_UPDATE_PROPERTY, np, newprop, oldprop);
1904 
1905 	return rc;
1906 }
1907 
1908 static void of_alias_add(struct alias_prop *ap, struct device_node *np,
1909 			 int id, const char *stem, int stem_len)
1910 {
1911 	ap->np = np;
1912 	ap->id = id;
1913 	strscpy(ap->stem, stem, stem_len + 1);
1914 	list_add_tail(&ap->link, &aliases_lookup);
1915 	pr_debug("adding DT alias:%s: stem=%s id=%i node=%pOF\n",
1916 		 ap->alias, ap->stem, ap->id, np);
1917 }
1918 
1919 /**
1920  * of_alias_scan - Scan all properties of the 'aliases' node
1921  * @dt_alloc:	An allocator that provides a virtual address to memory
1922  *		for storing the resulting tree
1923  *
1924  * The function scans all the properties of the 'aliases' node and populates
1925  * the global lookup table with the properties.
1926  */
1927 void of_alias_scan(void * (*dt_alloc)(u64 size, u64 align))
1928 {
1929 	const struct property *pp;
1930 
1931 	of_aliases = of_find_node_by_path("/aliases");
1932 	of_chosen = of_find_node_by_path("/chosen");
1933 	if (of_chosen == NULL)
1934 		of_chosen = of_find_node_by_path("/chosen@0");
1935 
1936 	if (of_chosen) {
1937 		/* linux,stdout-path and /aliases/stdout are for legacy compatibility */
1938 		const char *name = NULL;
1939 
1940 		if (of_property_read_string(of_chosen, "stdout-path", &name))
1941 			of_property_read_string(of_chosen, "linux,stdout-path",
1942 						&name);
1943 		if (IS_ENABLED(CONFIG_PPC) && !name)
1944 			of_property_read_string(of_aliases, "stdout", &name);
1945 		if (name)
1946 			of_stdout = of_find_node_opts_by_path(name, &of_stdout_options);
1947 		if (of_stdout)
1948 			fwnode_set_flag(&of_stdout->fwnode, FWNODE_FLAG_BEST_EFFORT);
1949 	}
1950 
1951 	if (!of_aliases)
1952 		return;
1953 
1954 	for_each_property_of_node(of_aliases, pp) {
1955 		const char *start = pp->name;
1956 		const char *end = start + strlen(start);
1957 		struct device_node *np;
1958 		struct alias_prop *ap;
1959 		int id, len;
1960 
1961 		/* Skip those we do not want to proceed */
1962 		if (is_pseudo_property(pp->name))
1963 			continue;
1964 
1965 		np = of_find_node_by_path(pp->value);
1966 		if (!np)
1967 			continue;
1968 
1969 		/* walk the alias backwards to extract the id and work out
1970 		 * the 'stem' string */
1971 		while (isdigit(*(end-1)) && end > start)
1972 			end--;
1973 		len = end - start;
1974 
1975 		if (kstrtoint(end, 10, &id) < 0) {
1976 			of_node_put(np);
1977 			continue;
1978 		}
1979 
1980 		/* Allocate an alias_prop with enough space for the stem */
1981 		ap = dt_alloc(sizeof(*ap) + len + 1, __alignof__(*ap));
1982 		if (!ap) {
1983 			of_node_put(np);
1984 			continue;
1985 		}
1986 		memset(ap, 0, sizeof(*ap) + len + 1);
1987 		ap->alias = start;
1988 		of_alias_add(ap, np, id, start, len);
1989 	}
1990 }
1991 
1992 /**
1993  * of_alias_get_id - Get alias id for the given device_node
1994  * @np:		Pointer to the given device_node
1995  * @stem:	Alias stem of the given device_node
1996  *
1997  * The function travels the lookup table to get the alias id for the given
1998  * device_node and alias stem.
1999  *
2000  * Return: The alias id if found.
2001  */
2002 int of_alias_get_id(const struct device_node *np, const char *stem)
2003 {
2004 	struct alias_prop *app;
2005 	int id = -ENODEV;
2006 
2007 	mutex_lock(&of_mutex);
2008 	list_for_each_entry(app, &aliases_lookup, link) {
2009 		if (strcmp(app->stem, stem) != 0)
2010 			continue;
2011 
2012 		if (np == app->np) {
2013 			id = app->id;
2014 			break;
2015 		}
2016 	}
2017 	mutex_unlock(&of_mutex);
2018 
2019 	return id;
2020 }
2021 EXPORT_SYMBOL_GPL(of_alias_get_id);
2022 
2023 /**
2024  * of_alias_get_highest_id - Get highest alias id for the given stem
2025  * @stem:	Alias stem to be examined
2026  *
2027  * The function travels the lookup table to get the highest alias id for the
2028  * given alias stem.  It returns the alias id if found.
2029  */
2030 int of_alias_get_highest_id(const char *stem)
2031 {
2032 	struct alias_prop *app;
2033 	int id = -ENODEV;
2034 
2035 	mutex_lock(&of_mutex);
2036 	list_for_each_entry(app, &aliases_lookup, link) {
2037 		if (strcmp(app->stem, stem) != 0)
2038 			continue;
2039 
2040 		if (app->id > id)
2041 			id = app->id;
2042 	}
2043 	mutex_unlock(&of_mutex);
2044 
2045 	return id;
2046 }
2047 EXPORT_SYMBOL_GPL(of_alias_get_highest_id);
2048 
2049 /**
2050  * of_console_check() - Test and setup console for DT setup
2051  * @dn: Pointer to device node
2052  * @name: Name to use for preferred console without index. ex. "ttyS"
2053  * @index: Index to use for preferred console.
2054  *
2055  * Check if the given device node matches the stdout-path property in the
2056  * /chosen node. If it does then register it as the preferred console.
2057  *
2058  * Return: TRUE if console successfully setup. Otherwise return FALSE.
2059  */
2060 bool of_console_check(const struct device_node *dn, char *name, int index)
2061 {
2062 	if (!dn || dn != of_stdout || console_set_on_cmdline)
2063 		return false;
2064 
2065 	/*
2066 	 * XXX: cast `options' to char pointer to suppress complication
2067 	 * warnings: printk, UART and console drivers expect char pointer.
2068 	 */
2069 	return !add_preferred_console(name, index, (char *)of_stdout_options);
2070 }
2071 EXPORT_SYMBOL_GPL(of_console_check);
2072 
2073 /**
2074  * of_find_next_cache_node - Find a node's subsidiary cache
2075  * @np:	node of type "cpu" or "cache"
2076  *
2077  * Return: A node pointer with refcount incremented, use
2078  * of_node_put() on it when done.  Caller should hold a reference
2079  * to np.
2080  */
2081 struct device_node *of_find_next_cache_node(const struct device_node *np)
2082 {
2083 	struct device_node *child, *cache_node;
2084 
2085 	cache_node = of_parse_phandle(np, "l2-cache", 0);
2086 	if (!cache_node)
2087 		cache_node = of_parse_phandle(np, "next-level-cache", 0);
2088 
2089 	if (cache_node)
2090 		return cache_node;
2091 
2092 	/* OF on pmac has nodes instead of properties named "l2-cache"
2093 	 * beneath CPU nodes.
2094 	 */
2095 	if (IS_ENABLED(CONFIG_PPC_PMAC) && of_node_is_type(np, "cpu"))
2096 		for_each_child_of_node(np, child)
2097 			if (of_node_is_type(child, "cache"))
2098 				return child;
2099 
2100 	return NULL;
2101 }
2102 
2103 /**
2104  * of_find_last_cache_level - Find the level at which the last cache is
2105  * 		present for the given logical cpu
2106  *
2107  * @cpu: cpu number(logical index) for which the last cache level is needed
2108  *
2109  * Return: The level at which the last cache is present. It is exactly
2110  * same as  the total number of cache levels for the given logical cpu.
2111  */
2112 int of_find_last_cache_level(unsigned int cpu)
2113 {
2114 	u32 cache_level = 0;
2115 	struct device_node *prev = NULL, *np = of_cpu_device_node_get(cpu);
2116 
2117 	while (np) {
2118 		of_node_put(prev);
2119 		prev = np;
2120 		np = of_find_next_cache_node(np);
2121 	}
2122 
2123 	of_property_read_u32(prev, "cache-level", &cache_level);
2124 	of_node_put(prev);
2125 
2126 	return cache_level;
2127 }
2128 
2129 /*
2130  * Some DTs have an iommu-map targeting a 2-cell IOMMU node while
2131  * specifying only 1 cell. Fortunately they all consist of value '1'
2132  * as the 2nd cell entry with the same target, so check for that pattern.
2133  *
2134  * Example:
2135  *	IOMMU node:
2136  *		#iommu-cells = <2>;
2137  *
2138  *	Device node:
2139  *		iommu-map = <0x0000 &smmu 0x0000 0x1>,
2140  *			    <0x0100 &smmu 0x0100 0x1>;
2141  */
2142 static bool of_check_bad_map(const __be32 *map, int len)
2143 {
2144 	__be32 phandle = map[1];
2145 
2146 	if (len % 4)
2147 		return false;
2148 	for (int i = 0; i < len; i += 4) {
2149 		if (map[i + 1] != phandle || map[i + 3] != cpu_to_be32(1))
2150 			return false;
2151 	}
2152 	return true;
2153 }
2154 
2155 /**
2156  * of_map_id - Translate an ID through a downstream mapping.
2157  * @np: root complex device node.
2158  * @id: device ID to map.
2159  * @map_name: property name of the map to use.
2160  * @cells_name: property name of target specifier cells.
2161  * @map_mask_name: optional property name of the mask to use.
2162  * @filter_np: pointer to an optional filter node, or NULL to allow bypass.
2163  *	If non-NULL, the map property must exist (-ENODEV if absent). If
2164  *	``*filter_np`` is also non-NULL, only entries targeting that node match.
2165  * @arg: pointer to a &struct of_phandle_args for the result. On success,
2166  *	@arg->args_count will be set to the number of output specifier cells
2167  *	as defined by @cells_name in the target node, and
2168  *	@arg->args[0..args_count-1] will contain the translated output
2169  *	specifier values. If a map entry was matched, @arg->np will be set
2170  *	to the target node with a reference held that the caller must release
2171  *	with of_node_put().
2172  *
2173  * Given a device ID, look up the appropriate implementation-defined
2174  * platform ID and/or the target device which receives transactions on that
2175  * ID, as per the "iommu-map" and "msi-map" bindings.
2176  *
2177  * Return: 0 on success or a standard error code on failure.
2178  */
2179 int of_map_id(const struct device_node *np, u32 id,
2180 	       const char *map_name, const char *cells_name,
2181 	       const char *map_mask_name,
2182 	       struct device_node * const *filter_np, struct of_phandle_args *arg)
2183 {
2184 	u32 map_mask, masked_id;
2185 	int map_bytes, map_len, offset = 0;
2186 	bool bad_map = false;
2187 	const __be32 *map = NULL;
2188 
2189 	if (!np || !map_name || !cells_name || !arg)
2190 		return -EINVAL;
2191 	/* Ensure bypass/no-match success never returns a stale target node. */
2192 	arg->np = NULL;
2193 
2194 	map = of_get_property(np, map_name, &map_bytes);
2195 	if (!map) {
2196 		if (filter_np)
2197 			return -ENODEV;
2198 		/* Otherwise, no map implies no translation */
2199 		arg->args[0] = id;
2200 		arg->args_count = 1;
2201 		return 0;
2202 	}
2203 
2204 	if (map_bytes % sizeof(*map))
2205 		goto err_map_len;
2206 	map_len = map_bytes / sizeof(*map);
2207 
2208 	/* The default is to select all bits. */
2209 	map_mask = 0xffffffff;
2210 
2211 	/*
2212 	 * Can be overridden by "{iommu,msi}-map-mask" property.
2213 	 * If of_property_read_u32() fails, the default is used.
2214 	 */
2215 	if (map_mask_name)
2216 		of_property_read_u32(np, map_mask_name, &map_mask);
2217 
2218 	masked_id = map_mask & id;
2219 
2220 	while (offset < map_len) {
2221 		struct device_node *phandle_node;
2222 		u32 id_base, phandle, id_len, id_off, cells = 0;
2223 		const __be32 *out_base;
2224 
2225 		if (map_len - offset < 2)
2226 			goto err_map_len;
2227 
2228 		id_base = be32_to_cpup(map + offset);
2229 
2230 		if (id_base & ~map_mask) {
2231 			pr_err("%pOF: Invalid %s translation - %s (0x%x) ignores id-base (0x%x)\n",
2232 			       np, map_name, map_mask_name, map_mask, id_base);
2233 			return -EFAULT;
2234 		}
2235 
2236 		phandle = be32_to_cpup(map + offset + 1);
2237 		phandle_node = of_find_node_by_phandle(phandle);
2238 		if (!phandle_node)
2239 			return -ENODEV;
2240 
2241 		/*
2242 		 * Assume 1-cell output specifier if the target node lacks the
2243 		 * #cells property, for backward compatibility with controllers
2244 		 * that predate the property (e.g. arm,gic-v2m-frame).
2245 		 */
2246 		if (bad_map || of_property_read_u32(phandle_node, cells_name, &cells))
2247 			cells = 1;
2248 
2249 		if (cells > MAX_PHANDLE_ARGS) {
2250 			pr_err("%pOF: %s cell count %d exceeds maximum\n",
2251 			       phandle_node, cells_name, cells);
2252 			of_node_put(phandle_node);
2253 			return -EINVAL;
2254 		}
2255 
2256 		if (offset == 0 && cells == 2) {
2257 			bad_map = of_check_bad_map(map, map_len);
2258 			if (bad_map) {
2259 				pr_warn_once("%pOF: %s has 1-cell entries targeting 2-cell %s, treating as 1-cell output\n",
2260 					     np, map_name, cells_name);
2261 				cells = 1;
2262 			}
2263 		}
2264 
2265 		if (map_len - offset < 3 + cells) {
2266 			of_node_put(phandle_node);
2267 			goto err_map_len;
2268 		}
2269 
2270 		out_base = map + offset + 2;
2271 		offset += 3 + cells;
2272 
2273 		id_len = be32_to_cpup(map + offset - 1);
2274 		id_off = masked_id - id_base;
2275 		if (masked_id < id_base || id_off >= id_len) {
2276 			of_node_put(phandle_node);
2277 			continue;
2278 		}
2279 		if (id_len > 1 && cells > 1) {
2280 			/*
2281 			 * With 1 output cell we reasonably assume its value
2282 			 * has a linear relationship to the input; with more,
2283 			 * we'd need help from the provider to know what to do.
2284 			 */
2285 			pr_err("%pOF: Unsupported %s - cannot handle %d-ID range with %d-cell output specifier\n",
2286 			       np, map_name, id_len, cells);
2287 			of_node_put(phandle_node);
2288 			return -EINVAL;
2289 		}
2290 
2291 		if (filter_np && *filter_np && *filter_np != phandle_node) {
2292 			of_node_put(phandle_node);
2293 			continue;
2294 		}
2295 
2296 		arg->np = phandle_node;
2297 		for (int i = 0; i < cells; i++)
2298 			arg->args[i] = id_off + be32_to_cpu(out_base[i]);
2299 		arg->args_count = cells;
2300 
2301 		pr_debug("%pOF: %s, using mask %08x, id-base: %08x, out-base: %08x, length: %08x, id: %08x -> %08x\n",
2302 			np, map_name, map_mask, id_base,
2303 			cells ? be32_to_cpup(out_base) : 0,
2304 			id_len, id,
2305 			cells ? id_off + be32_to_cpup(out_base) : id_off);
2306 		return 0;
2307 	}
2308 
2309 	pr_info("%pOF: no %s translation for id 0x%x on %pOF\n", np, map_name,
2310 		id, filter_np && *filter_np ? *filter_np : NULL);
2311 
2312 	/* Bypasses translation */
2313 	arg->args[0] = id;
2314 	arg->args_count = 1;
2315 	return 0;
2316 
2317 err_map_len:
2318 	pr_err("%pOF: Error: Bad %s length: %d\n", np, map_name, map_bytes);
2319 	return -EINVAL;
2320 }
2321 EXPORT_SYMBOL_GPL(of_map_id);
2322 
2323 /**
2324  * of_map_iommu_id - Translate an ID using "iommu-map" bindings.
2325  * @np: root complex device node.
2326  * @id: Requester ID of the device (e.g. PCI RID/BDF or a platform
2327  *      stream/device ID) used as the lookup key in the iommu-map table.
2328  * @arg: pointer to a &struct of_phandle_args for the result. On success,
2329  *	@arg->args_count will be set to the number of output specifier cells
2330  *	and @arg->args[0..args_count-1] will contain the translated output
2331  *	specifier values. If a map entry was matched, @arg->np holds a
2332  *	reference to the target node that the caller must release with
2333  *	of_node_put().
2334  *
2335  * Convenience wrapper around of_map_id() using "iommu-map", "#iommu-cells",
2336  * and "iommu-map-mask".
2337  *
2338  * Return: 0 on success or a standard error code on failure.
2339  */
2340 int of_map_iommu_id(const struct device_node *np, u32 id,
2341 		    struct of_phandle_args *arg)
2342 {
2343 	return of_map_id(np, id, "iommu-map", "#iommu-cells", "iommu-map-mask", NULL, arg);
2344 }
2345 EXPORT_SYMBOL_GPL(of_map_iommu_id);
2346 
2347 /**
2348  * of_map_msi_id - Translate an ID using "msi-map" bindings.
2349  * @np: root complex device node.
2350  * @id: Requester ID of the device (e.g. PCI RID/BDF or a platform
2351  *      stream/device ID) used as the lookup key in the msi-map table.
2352  * @filter_np: pointer to an optional filter node, or NULL to allow bypass.
2353  *	If non-NULL, the map property must exist (-ENODEV if absent). If
2354  *	``*filter_np`` is also non-NULL, only entries targeting that node match.
2355  * @arg: pointer to a &struct of_phandle_args for the result. On success,
2356  *	@arg->args_count will be set to the number of output specifier cells
2357  *	and @arg->args[0..args_count-1] will contain the translated output
2358  *	specifier values. If a map entry was matched, @arg->np holds a
2359  *	reference to the target node that the caller must release with
2360  *	of_node_put().
2361  *
2362  * Convenience wrapper around of_map_id() using "msi-map", "#msi-cells",
2363  * and "msi-map-mask".
2364  *
2365  * Return: 0 on success or a standard error code on failure.
2366  */
2367 int of_map_msi_id(const struct device_node *np, u32 id,
2368 		  struct device_node * const *filter_np, struct of_phandle_args *arg)
2369 {
2370 	return of_map_id(np, id, "msi-map", "#msi-cells", "msi-map-mask", filter_np, arg);
2371 }
2372 EXPORT_SYMBOL_GPL(of_map_msi_id);
2373