xref: /linux/drivers/of/base.c (revision fab183d632628381b466a41479489541ac0e29a0)
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 
of_node_name_eq(const struct device_node * np,const char * name)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 
of_node_name_prefix(const struct device_node * np,const char * prefix)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 
__of_node_is_type(const struct device_node * np,const char * type)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 
of_bus_n_addr_cells(struct device_node * np)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 
of_n_addr_cells(struct device_node * np)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 
of_bus_n_size_cells(struct device_node * np)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 
of_n_size_cells(struct device_node * np)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
of_node_to_nid(struct device_node * np)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 
of_phandle_cache_hash(phandle handle)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  */
__of_phandle_cache_inv_entry(phandle handle)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 
of_core_init(void)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 
__of_find_property(const struct device_node * np,const char * name,int * lenp)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 
of_find_property(const struct device_node * np,const char * name,int * lenp)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 
__of_find_all_nodes(struct device_node * prev)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  */
of_find_all_nodes(struct device_node * prev)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  */
__of_get_property(const struct device_node * np,const char * name,int * lenp)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  */
of_get_property(const struct device_node * np,const char * name,int * lenp)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  */
__of_device_is_compatible(const struct device_node * device,const char * compat,const char * type,const char * name)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  */
of_device_is_compatible(const struct device_node * device,const char * compat)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  */
of_device_compatible_match(const struct device_node * device,const char * const * compat)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  */
of_machine_compatible_match(const char * const * compats)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  */
of_machine_read_compatible(const char ** compatible,unsigned int index)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  */
of_machine_read_model(const char ** model)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  */
of_machine_get_match(const struct of_device_id * matches)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  */
of_machine_get_match_data(const struct of_device_id * matches)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 
__of_device_is_status(const struct device_node * device,const char * const * strings)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  */
__of_device_is_available(const struct device_node * device)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  */
__of_device_is_reserved(const struct device_node * device)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  */
of_device_is_available(const struct device_node * device)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  */
__of_device_is_fail(const struct device_node * device)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  */
of_device_is_big_endian(const struct device_node * device)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  */
of_get_parent(const struct device_node * node)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  */
of_get_next_parent(struct device_node * node)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 
__of_get_next_child(const struct device_node * node,struct device_node * prev)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  */
of_get_next_child(const struct device_node * node,struct device_node * prev)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  */
of_get_next_child_with_prefix(const struct device_node * node,struct device_node * prev,const char * prefix)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 
of_get_next_status_child(const struct device_node * node,struct device_node * prev,bool (* checker)(const struct device_node *))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  */
of_get_next_available_child(const struct device_node * node,struct device_node * prev)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  */
of_get_next_reserved_child(const struct device_node * node,struct device_node * prev)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  */
of_get_next_cpu_node(struct device_node * prev)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  */
of_get_compatible_child(const struct device_node * parent,const char * compatible)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  */
of_get_child_by_name(const struct device_node * node,const char * name)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  */
of_get_available_child_by_name(const struct device_node * node,const char * name)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 
__of_find_node_by_path(const struct device_node * parent,const char * path)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 
__of_find_node_by_full_path(struct device_node * node,const char * path)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  */
of_find_node_opts_by_path(const char * path,const char ** opts)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  */
of_find_node_by_name(struct device_node * from,const char * name)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  */
of_find_node_by_type(struct device_node * from,const char * type)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  */
of_find_compatible_node(struct device_node * from,const char * type,const char * compatible)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  */
of_find_node_with_property(struct device_node * from,const char * prop_name)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
__of_match_node(const struct of_device_id * matches,const struct device_node * node)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  */
of_match_node(const struct of_device_id * matches,const struct device_node * node)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  */
of_find_matching_node_and_match(struct device_node * from,const struct of_device_id * matches,const struct of_device_id ** match)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  */
of_alias_from_compatible(const struct device_node * node,char * alias,int len)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  */
of_find_node_by_phandle(phandle handle)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 
of_print_phandle_args(const char * msg,const struct of_phandle_args * args)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 
of_phandle_iterator_init(struct of_phandle_iterator * it,const struct device_node * np,const char * list_name,const char * cells_name,int cell_count)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 
of_phandle_iterator_next(struct of_phandle_iterator * it)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 
of_phandle_iterator_args(struct of_phandle_iterator * it,uint32_t * args,int size)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 
__of_parse_phandle_with_args(const struct device_node * np,const char * list_name,const char * cells_name,int cell_count,int index,struct of_phandle_args * out_args)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  */
of_parse_phandle_with_args_map(const struct device_node * np,const char * list_name,const char * stem_name,int index,struct of_phandle_args * _out_args)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 	struct of_phandle_args _oa = {};
1559 	struct of_phandle_args *out_args = _out_args ? _out_args : &_oa;
1560 	__be32 initial_match_array[MAX_PHANDLE_ARGS];
1561 	const __be32 *match_array = initial_match_array;
1562 	int i, ret, map_len, match;
1563 	u32 list_size, new_size;
1564 
1565 	if (index < 0)
1566 		return -EINVAL;
1567 
1568 	if (!cells_name || !map_name || !mask_name || !pass_name)
1569 		return -ENOMEM;
1570 
1571 	ret = __of_parse_phandle_with_args(np, list_name, cells_name, -1, index,
1572 					   out_args);
1573 	if (ret)
1574 		return ret;
1575 
1576 	/* Get the #<list>-cells property */
1577 	cur = out_args->np;
1578 	ret = of_property_read_u32(cur, cells_name, &list_size);
1579 	if (ret < 0)
1580 		goto put;
1581 
1582 	/* Precalculate the match array - this simplifies match loop */
1583 	for (i = 0; i < list_size; i++)
1584 		initial_match_array[i] = cpu_to_be32(out_args->args[i]);
1585 
1586 	ret = -EINVAL;
1587 	while (cur) {
1588 		/* Get the <list>-map property */
1589 		map = of_get_property(cur, map_name, &map_len);
1590 		if (!map) {
1591 			if (!_out_args)
1592 				of_node_put(out_args->np);
1593 			return 0;
1594 		}
1595 		map_len /= sizeof(u32);
1596 
1597 		/* Get the <list>-map-mask property (optional) */
1598 		mask = of_get_property(cur, mask_name, NULL);
1599 		if (!mask)
1600 			mask = dummy_mask;
1601 		/* Iterate through <list>-map property */
1602 		match = 0;
1603 		while (map_len > (list_size + 1) && !match) {
1604 			/* Compare specifiers */
1605 			match = 1;
1606 			for (i = 0; i < list_size; i++, map_len--)
1607 				match &= !((match_array[i] ^ *map++) & mask[i]);
1608 
1609 			of_node_put(new);
1610 			new = of_find_node_by_phandle(be32_to_cpup(map));
1611 			map++;
1612 			map_len--;
1613 
1614 			/* Check if not found */
1615 			if (!new) {
1616 				ret = -EINVAL;
1617 				goto put;
1618 			}
1619 
1620 			if (!of_device_is_available(new))
1621 				match = 0;
1622 
1623 			ret = of_property_read_u32(new, cells_name, &new_size);
1624 			if (ret)
1625 				goto put;
1626 
1627 			/* Check for malformed properties */
1628 			if (WARN_ON(new_size > MAX_PHANDLE_ARGS) ||
1629 			    map_len < new_size) {
1630 				ret = -EINVAL;
1631 				goto put;
1632 			}
1633 
1634 			/* Move forward by new node's #<list>-cells amount */
1635 			map += new_size;
1636 			map_len -= new_size;
1637 		}
1638 		if (!match) {
1639 			ret = -ENOENT;
1640 			goto put;
1641 		}
1642 
1643 		/* Get the <list>-map-pass-thru property (optional) */
1644 		pass = of_get_property(cur, pass_name, NULL);
1645 		if (!pass)
1646 			pass = dummy_pass;
1647 
1648 		/*
1649 		 * Successfully parsed a <list>-map translation; copy new
1650 		 * specifier into the out_args structure, keeping the
1651 		 * bits specified in <list>-map-pass-thru.
1652 		 */
1653 		for (i = 0; i < new_size; i++) {
1654 			__be32 val = *(map - new_size + i);
1655 
1656 			if (i < list_size) {
1657 				val &= ~pass[i];
1658 				val |= cpu_to_be32(out_args->args[i]) & pass[i];
1659 			}
1660 
1661 			initial_match_array[i] = val;
1662 			out_args->args[i] = be32_to_cpu(val);
1663 		}
1664 		out_args->args_count = list_size = new_size;
1665 		/* Iterate again with new provider */
1666 		out_args->np = new;
1667 		of_node_put(cur);
1668 		cur = new;
1669 		new = NULL;
1670 	}
1671 put:
1672 	of_node_put(cur);
1673 	of_node_put(new);
1674 	return ret;
1675 }
1676 EXPORT_SYMBOL(of_parse_phandle_with_args_map);
1677 
1678 /**
1679  * of_count_phandle_with_args() - Find the number of phandles references in a property
1680  * @np:		pointer to a device tree node containing a list
1681  * @list_name:	property name that contains a list
1682  * @cells_name:	property name that specifies phandles' arguments count
1683  *
1684  * Return: The number of phandle + argument tuples within a property. It
1685  * is a typical pattern to encode a list of phandle and variable
1686  * arguments into a single property. The number of arguments is encoded
1687  * by a property in the phandle-target node. For example, a gpios
1688  * property would contain a list of GPIO specifies consisting of a
1689  * phandle and 1 or more arguments. The number of arguments are
1690  * determined by the #gpio-cells property in the node pointed to by the
1691  * phandle.
1692  */
of_count_phandle_with_args(const struct device_node * np,const char * list_name,const char * cells_name)1693 int of_count_phandle_with_args(const struct device_node *np, const char *list_name,
1694 				const char *cells_name)
1695 {
1696 	struct of_phandle_iterator it;
1697 	int rc, cur_index = 0;
1698 
1699 	/*
1700 	 * If cells_name is NULL we assume a cell count of 0. This makes
1701 	 * counting the phandles trivial as each 32bit word in the list is a
1702 	 * phandle and no arguments are to consider. So we don't iterate through
1703 	 * the list but just use the length to determine the phandle count.
1704 	 */
1705 	if (!cells_name) {
1706 		const __be32 *list;
1707 		int size;
1708 
1709 		list = of_get_property(np, list_name, &size);
1710 		if (!list)
1711 			return -ENOENT;
1712 
1713 		return size / sizeof(*list);
1714 	}
1715 
1716 	rc = of_phandle_iterator_init(&it, np, list_name, cells_name, -1);
1717 	if (rc)
1718 		return rc;
1719 
1720 	while ((rc = of_phandle_iterator_next(&it)) == 0)
1721 		cur_index += 1;
1722 
1723 	if (rc != -ENOENT)
1724 		return rc;
1725 
1726 	return cur_index;
1727 }
1728 EXPORT_SYMBOL(of_count_phandle_with_args);
1729 
__of_remove_property_from_list(struct property ** list,struct property * prop)1730 static struct property *__of_remove_property_from_list(struct property **list, struct property *prop)
1731 {
1732 	struct property **next;
1733 
1734 	for (next = list; *next; next = &(*next)->next) {
1735 		if (*next == prop) {
1736 			*next = prop->next;
1737 			prop->next = NULL;
1738 			return prop;
1739 		}
1740 	}
1741 	return NULL;
1742 }
1743 
1744 /**
1745  * __of_add_property - Add a property to a node without lock operations
1746  * @np:		Caller's Device Node
1747  * @prop:	Property to add
1748  */
__of_add_property(struct device_node * np,struct property * prop)1749 int __of_add_property(struct device_node *np, struct property *prop)
1750 {
1751 	int rc = 0;
1752 	unsigned long flags;
1753 	struct property **next;
1754 
1755 	raw_spin_lock_irqsave(&devtree_lock, flags);
1756 
1757 	__of_remove_property_from_list(&np->deadprops, prop);
1758 
1759 	prop->next = NULL;
1760 	next = &np->properties;
1761 	while (*next) {
1762 		if (of_prop_cmp(prop->name, (*next)->name) == 0) {
1763 			/* duplicate ! don't insert it */
1764 			rc = -EEXIST;
1765 			goto out_unlock;
1766 		}
1767 		next = &(*next)->next;
1768 	}
1769 	*next = prop;
1770 
1771 out_unlock:
1772 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
1773 	if (rc)
1774 		return rc;
1775 
1776 	__of_add_property_sysfs(np, prop);
1777 	return 0;
1778 }
1779 
1780 /**
1781  * of_add_property - Add a property to a node
1782  * @np:		Caller's Device Node
1783  * @prop:	Property to add
1784  */
of_add_property(struct device_node * np,struct property * prop)1785 int of_add_property(struct device_node *np, struct property *prop)
1786 {
1787 	int rc;
1788 
1789 	mutex_lock(&of_mutex);
1790 	rc = __of_add_property(np, prop);
1791 	mutex_unlock(&of_mutex);
1792 
1793 	if (!rc)
1794 		of_property_notify(OF_RECONFIG_ADD_PROPERTY, np, prop, NULL);
1795 
1796 	return rc;
1797 }
1798 EXPORT_SYMBOL_GPL(of_add_property);
1799 
__of_remove_property(struct device_node * np,struct property * prop)1800 int __of_remove_property(struct device_node *np, struct property *prop)
1801 {
1802 	unsigned long flags;
1803 	int rc = -ENODEV;
1804 
1805 	raw_spin_lock_irqsave(&devtree_lock, flags);
1806 
1807 	if (__of_remove_property_from_list(&np->properties, prop)) {
1808 		/* Found the property, add it to deadprops list */
1809 		prop->next = np->deadprops;
1810 		np->deadprops = prop;
1811 		rc = 0;
1812 	}
1813 
1814 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
1815 	if (rc)
1816 		return rc;
1817 
1818 	__of_remove_property_sysfs(np, prop);
1819 	return 0;
1820 }
1821 
1822 /**
1823  * of_remove_property - Remove a property from a node.
1824  * @np:		Caller's Device Node
1825  * @prop:	Property to remove
1826  *
1827  * Note that we don't actually remove it, since we have given out
1828  * who-knows-how-many pointers to the data using get-property.
1829  * Instead we just move the property to the "dead properties"
1830  * list, so it won't be found any more.
1831  */
of_remove_property(struct device_node * np,struct property * prop)1832 int of_remove_property(struct device_node *np, struct property *prop)
1833 {
1834 	int rc;
1835 
1836 	if (!prop)
1837 		return -ENODEV;
1838 
1839 	mutex_lock(&of_mutex);
1840 	rc = __of_remove_property(np, prop);
1841 	mutex_unlock(&of_mutex);
1842 
1843 	if (!rc)
1844 		of_property_notify(OF_RECONFIG_REMOVE_PROPERTY, np, prop, NULL);
1845 
1846 	return rc;
1847 }
1848 EXPORT_SYMBOL_GPL(of_remove_property);
1849 
__of_update_property(struct device_node * np,struct property * newprop,struct property ** oldpropp)1850 int __of_update_property(struct device_node *np, struct property *newprop,
1851 		struct property **oldpropp)
1852 {
1853 	struct property **next, *oldprop;
1854 	unsigned long flags;
1855 
1856 	raw_spin_lock_irqsave(&devtree_lock, flags);
1857 
1858 	__of_remove_property_from_list(&np->deadprops, newprop);
1859 
1860 	for (next = &np->properties; *next; next = &(*next)->next) {
1861 		if (of_prop_cmp((*next)->name, newprop->name) == 0)
1862 			break;
1863 	}
1864 	*oldpropp = oldprop = *next;
1865 
1866 	if (oldprop) {
1867 		/* replace the node */
1868 		newprop->next = oldprop->next;
1869 		*next = newprop;
1870 		oldprop->next = np->deadprops;
1871 		np->deadprops = oldprop;
1872 	} else {
1873 		/* new node */
1874 		newprop->next = NULL;
1875 		*next = newprop;
1876 	}
1877 
1878 	raw_spin_unlock_irqrestore(&devtree_lock, flags);
1879 
1880 	__of_update_property_sysfs(np, newprop, oldprop);
1881 
1882 	return 0;
1883 }
1884 
1885 /*
1886  * of_update_property - Update a property in a node, if the property does
1887  * not exist, add it.
1888  *
1889  * Note that we don't actually remove it, since we have given out
1890  * who-knows-how-many pointers to the data using get-property.
1891  * Instead we just move the property to the "dead properties" list,
1892  * and add the new property to the property list
1893  */
of_update_property(struct device_node * np,struct property * newprop)1894 int of_update_property(struct device_node *np, struct property *newprop)
1895 {
1896 	struct property *oldprop;
1897 	int rc;
1898 
1899 	if (!newprop->name)
1900 		return -EINVAL;
1901 
1902 	mutex_lock(&of_mutex);
1903 	rc = __of_update_property(np, newprop, &oldprop);
1904 	mutex_unlock(&of_mutex);
1905 
1906 	if (!rc)
1907 		of_property_notify(OF_RECONFIG_UPDATE_PROPERTY, np, newprop, oldprop);
1908 
1909 	return rc;
1910 }
1911 
of_alias_add(struct alias_prop * ap,struct device_node * np,int id,const char * stem,int stem_len)1912 static void of_alias_add(struct alias_prop *ap, struct device_node *np,
1913 			 int id, const char *stem, int stem_len)
1914 {
1915 	ap->np = np;
1916 	ap->id = id;
1917 	strscpy(ap->stem, stem, stem_len + 1);
1918 	list_add_tail(&ap->link, &aliases_lookup);
1919 	pr_debug("adding DT alias:%s: stem=%s id=%i node=%pOF\n",
1920 		 ap->alias, ap->stem, ap->id, np);
1921 }
1922 
1923 /**
1924  * of_alias_scan - Scan all properties of the 'aliases' node
1925  * @dt_alloc:	An allocator that provides a virtual address to memory
1926  *		for storing the resulting tree
1927  *
1928  * The function scans all the properties of the 'aliases' node and populates
1929  * the global lookup table with the properties.
1930  */
of_alias_scan(void * (* dt_alloc)(u64 size,u64 align))1931 void of_alias_scan(void * (*dt_alloc)(u64 size, u64 align))
1932 {
1933 	const struct property *pp;
1934 
1935 	of_aliases = of_find_node_by_path("/aliases");
1936 	of_chosen = of_find_node_by_path("/chosen");
1937 	if (of_chosen == NULL)
1938 		of_chosen = of_find_node_by_path("/chosen@0");
1939 
1940 	if (of_chosen) {
1941 		/* linux,stdout-path and /aliases/stdout are for legacy compatibility */
1942 		const char *name = NULL;
1943 
1944 		if (of_property_read_string(of_chosen, "stdout-path", &name))
1945 			of_property_read_string(of_chosen, "linux,stdout-path",
1946 						&name);
1947 		if (IS_ENABLED(CONFIG_PPC) && !name)
1948 			of_property_read_string(of_aliases, "stdout", &name);
1949 		if (name)
1950 			of_stdout = of_find_node_opts_by_path(name, &of_stdout_options);
1951 		if (of_stdout)
1952 			fwnode_set_flag(&of_stdout->fwnode, FWNODE_FLAG_BEST_EFFORT);
1953 	}
1954 
1955 	if (!of_aliases)
1956 		return;
1957 
1958 	for_each_property_of_node(of_aliases, pp) {
1959 		const char *start = pp->name;
1960 		const char *end = start + strlen(start);
1961 		struct device_node *np;
1962 		struct alias_prop *ap;
1963 		int id, len;
1964 
1965 		/* Skip those we do not want to proceed */
1966 		if (is_pseudo_property(pp->name))
1967 			continue;
1968 
1969 		np = of_find_node_by_path(pp->value);
1970 		if (!np)
1971 			continue;
1972 
1973 		/* walk the alias backwards to extract the id and work out
1974 		 * the 'stem' string */
1975 		while (isdigit(*(end-1)) && end > start)
1976 			end--;
1977 		len = end - start;
1978 
1979 		if (kstrtoint(end, 10, &id) < 0) {
1980 			of_node_put(np);
1981 			continue;
1982 		}
1983 
1984 		/* Allocate an alias_prop with enough space for the stem */
1985 		ap = dt_alloc(sizeof(*ap) + len + 1, __alignof__(*ap));
1986 		if (!ap) {
1987 			of_node_put(np);
1988 			continue;
1989 		}
1990 		memset(ap, 0, sizeof(*ap) + len + 1);
1991 		ap->alias = start;
1992 		of_alias_add(ap, np, id, start, len);
1993 	}
1994 }
1995 
1996 /**
1997  * of_alias_get_id - Get alias id for the given device_node
1998  * @np:		Pointer to the given device_node
1999  * @stem:	Alias stem of the given device_node
2000  *
2001  * The function travels the lookup table to get the alias id for the given
2002  * device_node and alias stem.
2003  *
2004  * Return: The alias id if found.
2005  */
of_alias_get_id(const struct device_node * np,const char * stem)2006 int of_alias_get_id(const struct device_node *np, const char *stem)
2007 {
2008 	struct alias_prop *app;
2009 	int id = -ENODEV;
2010 
2011 	mutex_lock(&of_mutex);
2012 	list_for_each_entry(app, &aliases_lookup, link) {
2013 		if (strcmp(app->stem, stem) != 0)
2014 			continue;
2015 
2016 		if (np == app->np) {
2017 			id = app->id;
2018 			break;
2019 		}
2020 	}
2021 	mutex_unlock(&of_mutex);
2022 
2023 	return id;
2024 }
2025 EXPORT_SYMBOL_GPL(of_alias_get_id);
2026 
2027 /**
2028  * of_alias_get_highest_id - Get highest alias id for the given stem
2029  * @stem:	Alias stem to be examined
2030  *
2031  * The function travels the lookup table to get the highest alias id for the
2032  * given alias stem.  It returns the alias id if found.
2033  */
of_alias_get_highest_id(const char * stem)2034 int of_alias_get_highest_id(const char *stem)
2035 {
2036 	struct alias_prop *app;
2037 	int id = -ENODEV;
2038 
2039 	mutex_lock(&of_mutex);
2040 	list_for_each_entry(app, &aliases_lookup, link) {
2041 		if (strcmp(app->stem, stem) != 0)
2042 			continue;
2043 
2044 		if (app->id > id)
2045 			id = app->id;
2046 	}
2047 	mutex_unlock(&of_mutex);
2048 
2049 	return id;
2050 }
2051 EXPORT_SYMBOL_GPL(of_alias_get_highest_id);
2052 
2053 /**
2054  * of_console_check() - Test and setup console for DT setup
2055  * @dn: Pointer to device node
2056  * @name: Name to use for preferred console without index. ex. "ttyS"
2057  * @index: Index to use for preferred console.
2058  *
2059  * Check if the given device node matches the stdout-path property in the
2060  * /chosen node. If it does then register it as the preferred console.
2061  *
2062  * Return: TRUE if console successfully setup. Otherwise return FALSE.
2063  */
of_console_check(const struct device_node * dn,char * name,int index)2064 bool of_console_check(const struct device_node *dn, char *name, int index)
2065 {
2066 	if (!dn || dn != of_stdout || console_set_on_cmdline)
2067 		return false;
2068 
2069 	/*
2070 	 * XXX: cast `options' to char pointer to suppress complication
2071 	 * warnings: printk, UART and console drivers expect char pointer.
2072 	 */
2073 	return !add_preferred_console(name, index, (char *)of_stdout_options);
2074 }
2075 EXPORT_SYMBOL_GPL(of_console_check);
2076 
2077 /**
2078  * of_find_next_cache_node - Find a node's subsidiary cache
2079  * @np:	node of type "cpu" or "cache"
2080  *
2081  * Return: A node pointer with refcount incremented, use
2082  * of_node_put() on it when done.  Caller should hold a reference
2083  * to np.
2084  */
of_find_next_cache_node(const struct device_node * np)2085 struct device_node *of_find_next_cache_node(const struct device_node *np)
2086 {
2087 	struct device_node *child, *cache_node;
2088 
2089 	cache_node = of_parse_phandle(np, "l2-cache", 0);
2090 	if (!cache_node)
2091 		cache_node = of_parse_phandle(np, "next-level-cache", 0);
2092 
2093 	if (cache_node)
2094 		return cache_node;
2095 
2096 	/* OF on pmac has nodes instead of properties named "l2-cache"
2097 	 * beneath CPU nodes.
2098 	 */
2099 	if (IS_ENABLED(CONFIG_PPC_PMAC) && of_node_is_type(np, "cpu"))
2100 		for_each_child_of_node(np, child)
2101 			if (of_node_is_type(child, "cache"))
2102 				return child;
2103 
2104 	return NULL;
2105 }
2106 
2107 /**
2108  * of_find_last_cache_level - Find the level at which the last cache is
2109  * 		present for the given logical cpu
2110  *
2111  * @cpu: cpu number(logical index) for which the last cache level is needed
2112  *
2113  * Return: The level at which the last cache is present. It is exactly
2114  * same as  the total number of cache levels for the given logical cpu.
2115  */
of_find_last_cache_level(unsigned int cpu)2116 int of_find_last_cache_level(unsigned int cpu)
2117 {
2118 	u32 cache_level = 0;
2119 	struct device_node *prev = NULL, *np = of_cpu_device_node_get(cpu);
2120 
2121 	while (np) {
2122 		of_node_put(prev);
2123 		prev = np;
2124 		np = of_find_next_cache_node(np);
2125 	}
2126 
2127 	of_property_read_u32(prev, "cache-level", &cache_level);
2128 	of_node_put(prev);
2129 
2130 	return cache_level;
2131 }
2132 
2133 /*
2134  * Some DTs have an iommu-map targeting a 2-cell IOMMU node while
2135  * specifying only 1 cell. Fortunately they all consist of value '1'
2136  * as the 2nd cell entry with the same target, so check for that pattern.
2137  *
2138  * Example:
2139  *	IOMMU node:
2140  *		#iommu-cells = <2>;
2141  *
2142  *	Device node:
2143  *		iommu-map = <0x0000 &smmu 0x0000 0x1>,
2144  *			    <0x0100 &smmu 0x0100 0x1>;
2145  */
of_check_bad_map(const __be32 * map,int len)2146 static bool of_check_bad_map(const __be32 *map, int len)
2147 {
2148 	__be32 phandle = map[1];
2149 
2150 	if (len % 4)
2151 		return false;
2152 	for (int i = 0; i < len; i += 4) {
2153 		if (map[i + 1] != phandle || map[i + 3] != cpu_to_be32(1))
2154 			return false;
2155 	}
2156 	return true;
2157 }
2158 
2159 /**
2160  * of_map_id - Translate an ID through a downstream mapping.
2161  * @np: root complex device node.
2162  * @id: device ID to map.
2163  * @map_name: property name of the map to use.
2164  * @cells_name: property name of target specifier cells.
2165  * @map_mask_name: optional property name of the mask to use.
2166  * @filter_np: pointer to an optional filter node, or NULL to allow bypass.
2167  *	If non-NULL, the map property must exist (-ENODEV if absent). If
2168  *	``*filter_np`` is also non-NULL, only entries targeting that node match.
2169  * @arg: pointer to a &struct of_phandle_args for the result. On success,
2170  *	@arg->args_count will be set to the number of output specifier cells
2171  *	as defined by @cells_name in the target node, and
2172  *	@arg->args[0..args_count-1] will contain the translated output
2173  *	specifier values. If a map entry was matched, @arg->np will be set
2174  *	to the target node with a reference held that the caller must release
2175  *	with of_node_put().
2176  *
2177  * Given a device ID, look up the appropriate implementation-defined
2178  * platform ID and/or the target device which receives transactions on that
2179  * ID, as per the "iommu-map" and "msi-map" bindings.
2180  *
2181  * Return: 0 on success or a standard error code on failure.
2182  */
of_map_id(const struct device_node * np,u32 id,const char * map_name,const char * cells_name,const char * map_mask_name,struct device_node * const * filter_np,struct of_phandle_args * arg)2183 int of_map_id(const struct device_node *np, u32 id,
2184 	       const char *map_name, const char *cells_name,
2185 	       const char *map_mask_name,
2186 	       struct device_node * const *filter_np, struct of_phandle_args *arg)
2187 {
2188 	u32 map_mask, masked_id;
2189 	int map_bytes, map_len, offset = 0;
2190 	bool bad_map = false;
2191 	const __be32 *map = NULL;
2192 
2193 	if (!np || !map_name || !cells_name || !arg)
2194 		return -EINVAL;
2195 	/* Ensure bypass/no-match success never returns a stale target node. */
2196 	arg->np = NULL;
2197 
2198 	map = of_get_property(np, map_name, &map_bytes);
2199 	if (!map) {
2200 		if (filter_np)
2201 			return -ENODEV;
2202 		/* Otherwise, no map implies no translation */
2203 		arg->args[0] = id;
2204 		arg->args_count = 1;
2205 		return 0;
2206 	}
2207 
2208 	if (map_bytes % sizeof(*map))
2209 		goto err_map_len;
2210 	map_len = map_bytes / sizeof(*map);
2211 
2212 	/* The default is to select all bits. */
2213 	map_mask = 0xffffffff;
2214 
2215 	/*
2216 	 * Can be overridden by "{iommu,msi}-map-mask" property.
2217 	 * If of_property_read_u32() fails, the default is used.
2218 	 */
2219 	if (map_mask_name)
2220 		of_property_read_u32(np, map_mask_name, &map_mask);
2221 
2222 	masked_id = map_mask & id;
2223 
2224 	while (offset < map_len) {
2225 		struct device_node *phandle_node;
2226 		u32 id_base, phandle, id_len, id_off, cells = 0;
2227 		const __be32 *out_base;
2228 
2229 		if (map_len - offset < 2)
2230 			goto err_map_len;
2231 
2232 		id_base = be32_to_cpup(map + offset);
2233 
2234 		if (id_base & ~map_mask) {
2235 			pr_err("%pOF: Invalid %s translation - %s (0x%x) ignores id-base (0x%x)\n",
2236 			       np, map_name, map_mask_name, map_mask, id_base);
2237 			return -EFAULT;
2238 		}
2239 
2240 		phandle = be32_to_cpup(map + offset + 1);
2241 		phandle_node = of_find_node_by_phandle(phandle);
2242 		if (!phandle_node)
2243 			return -ENODEV;
2244 
2245 		/*
2246 		 * Assume 1-cell output specifier if the target node lacks the
2247 		 * #cells property, for backward compatibility with controllers
2248 		 * that predate the property (e.g. arm,gic-v2m-frame).
2249 		 */
2250 		if (bad_map || of_property_read_u32(phandle_node, cells_name, &cells))
2251 			cells = 1;
2252 
2253 		if (cells > MAX_PHANDLE_ARGS) {
2254 			pr_err("%pOF: %s cell count %d exceeds maximum\n",
2255 			       phandle_node, cells_name, cells);
2256 			of_node_put(phandle_node);
2257 			return -EINVAL;
2258 		}
2259 
2260 		if (offset == 0 && cells == 2) {
2261 			bad_map = of_check_bad_map(map, map_len);
2262 			if (bad_map) {
2263 				pr_warn_once("%pOF: %s has 1-cell entries targeting 2-cell %s, treating as 1-cell output\n",
2264 					     np, map_name, cells_name);
2265 				cells = 1;
2266 			}
2267 		}
2268 
2269 		if (map_len - offset < 3 + cells) {
2270 			of_node_put(phandle_node);
2271 			goto err_map_len;
2272 		}
2273 
2274 		out_base = map + offset + 2;
2275 		offset += 3 + cells;
2276 
2277 		id_len = be32_to_cpup(map + offset - 1);
2278 		id_off = masked_id - id_base;
2279 		if (masked_id < id_base || id_off >= id_len) {
2280 			of_node_put(phandle_node);
2281 			continue;
2282 		}
2283 		if (id_len > 1 && cells > 1) {
2284 			/*
2285 			 * With 1 output cell we reasonably assume its value
2286 			 * has a linear relationship to the input; with more,
2287 			 * we'd need help from the provider to know what to do.
2288 			 */
2289 			pr_err("%pOF: Unsupported %s - cannot handle %d-ID range with %d-cell output specifier\n",
2290 			       np, map_name, id_len, cells);
2291 			of_node_put(phandle_node);
2292 			return -EINVAL;
2293 		}
2294 
2295 		if (filter_np && *filter_np && *filter_np != phandle_node) {
2296 			of_node_put(phandle_node);
2297 			continue;
2298 		}
2299 
2300 		arg->np = phandle_node;
2301 		for (int i = 0; i < cells; i++)
2302 			arg->args[i] = id_off + be32_to_cpu(out_base[i]);
2303 		arg->args_count = cells;
2304 
2305 		pr_debug("%pOF: %s, using mask %08x, id-base: %08x, out-base: %08x, length: %08x, id: %08x -> %08x\n",
2306 			np, map_name, map_mask, id_base,
2307 			cells ? be32_to_cpup(out_base) : 0,
2308 			id_len, id,
2309 			cells ? id_off + be32_to_cpup(out_base) : id_off);
2310 		return 0;
2311 	}
2312 
2313 	pr_info("%pOF: no %s translation for id 0x%x on %pOF\n", np, map_name,
2314 		id, filter_np && *filter_np ? *filter_np : NULL);
2315 
2316 	/* Bypasses translation */
2317 	arg->args[0] = id;
2318 	arg->args_count = 1;
2319 	return 0;
2320 
2321 err_map_len:
2322 	pr_err("%pOF: Error: Bad %s length: %d\n", np, map_name, map_bytes);
2323 	return -EINVAL;
2324 }
2325 EXPORT_SYMBOL_GPL(of_map_id);
2326 
2327 /**
2328  * of_map_iommu_id - Translate an ID using "iommu-map" bindings.
2329  * @np: root complex device node.
2330  * @id: Requester ID of the device (e.g. PCI RID/BDF or a platform
2331  *      stream/device ID) used as the lookup key in the iommu-map table.
2332  * @arg: pointer to a &struct of_phandle_args for the result. On success,
2333  *	@arg->args_count will be set to the number of output specifier cells
2334  *	and @arg->args[0..args_count-1] will contain the translated output
2335  *	specifier values. If a map entry was matched, @arg->np holds a
2336  *	reference to the target node that the caller must release with
2337  *	of_node_put().
2338  *
2339  * Convenience wrapper around of_map_id() using "iommu-map", "#iommu-cells",
2340  * and "iommu-map-mask".
2341  *
2342  * Return: 0 on success or a standard error code on failure.
2343  */
of_map_iommu_id(const struct device_node * np,u32 id,struct of_phandle_args * arg)2344 int of_map_iommu_id(const struct device_node *np, u32 id,
2345 		    struct of_phandle_args *arg)
2346 {
2347 	return of_map_id(np, id, "iommu-map", "#iommu-cells", "iommu-map-mask", NULL, arg);
2348 }
2349 EXPORT_SYMBOL_GPL(of_map_iommu_id);
2350 
2351 /**
2352  * of_map_msi_id - Translate an ID using "msi-map" bindings.
2353  * @np: root complex device node.
2354  * @id: Requester ID of the device (e.g. PCI RID/BDF or a platform
2355  *      stream/device ID) used as the lookup key in the msi-map table.
2356  * @filter_np: pointer to an optional filter node, or NULL to allow bypass.
2357  *	If non-NULL, the map property must exist (-ENODEV if absent). If
2358  *	``*filter_np`` is also non-NULL, only entries targeting that node match.
2359  * @arg: pointer to a &struct of_phandle_args for the result. On success,
2360  *	@arg->args_count will be set to the number of output specifier cells
2361  *	and @arg->args[0..args_count-1] will contain the translated output
2362  *	specifier values. If a map entry was matched, @arg->np holds a
2363  *	reference to the target node that the caller must release with
2364  *	of_node_put().
2365  *
2366  * Convenience wrapper around of_map_id() using "msi-map", "#msi-cells",
2367  * and "msi-map-mask".
2368  *
2369  * Return: 0 on success or a standard error code on failure.
2370  */
of_map_msi_id(const struct device_node * np,u32 id,struct device_node * const * filter_np,struct of_phandle_args * arg)2371 int of_map_msi_id(const struct device_node *np, u32 id,
2372 		  struct device_node * const *filter_np, struct of_phandle_args *arg)
2373 {
2374 	return of_map_id(np, id, "msi-map", "#msi-cells", "msi-map-mask", filter_np, arg);
2375 }
2376 EXPORT_SYMBOL_GPL(of_map_msi_id);
2377