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