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