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