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