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