common: Drop log.h from common header
[oweals/u-boot.git] / drivers / core / of_access.c
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * Originally from Linux v4.9
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  * Modified for U-Boot
16  * Copyright (c) 2017 Google, Inc
17  *
18  * This file follows drivers/of/base.c with functions in the same order as the
19  * Linux version.
20  */
21
22 #include <common.h>
23 #include <log.h>
24 #include <malloc.h>
25 #include <linux/libfdt.h>
26 #include <dm/of_access.h>
27 #include <linux/ctype.h>
28 #include <linux/err.h>
29 #include <linux/ioport.h>
30
31 DECLARE_GLOBAL_DATA_PTR;
32
33 /* list of struct alias_prop aliases */
34 LIST_HEAD(aliases_lookup);
35
36 /* "/aliaes" node */
37 static struct device_node *of_aliases;
38
39 /* "/chosen" node */
40 static struct device_node *of_chosen;
41
42 /* node pointed to by the stdout-path alias */
43 static struct device_node *of_stdout;
44
45 /* pointer to options given after the alias (separated by :) or NULL if none */
46 static const char *of_stdout_options;
47
48 /**
49  * struct alias_prop - Alias property in 'aliases' node
50  *
51  * The structure represents one alias property of 'aliases' node as
52  * an entry in aliases_lookup list.
53  *
54  * @link:       List node to link the structure in aliases_lookup list
55  * @alias:      Alias property name
56  * @np:         Pointer to device_node that the alias stands for
57  * @id:         Index value from end of alias name
58  * @stem:       Alias string without the index
59  */
60 struct alias_prop {
61         struct list_head link;
62         const char *alias;
63         struct device_node *np;
64         int id;
65         char stem[0];
66 };
67
68 int of_n_addr_cells(const struct device_node *np)
69 {
70         const __be32 *ip;
71
72         do {
73                 if (np->parent)
74                         np = np->parent;
75                 ip = of_get_property(np, "#address-cells", NULL);
76                 if (ip)
77                         return be32_to_cpup(ip);
78         } while (np->parent);
79
80         /* No #address-cells property for the root node */
81         return OF_ROOT_NODE_ADDR_CELLS_DEFAULT;
82 }
83
84 int of_n_size_cells(const struct device_node *np)
85 {
86         const __be32 *ip;
87
88         do {
89                 if (np->parent)
90                         np = np->parent;
91                 ip = of_get_property(np, "#size-cells", NULL);
92                 if (ip)
93                         return be32_to_cpup(ip);
94         } while (np->parent);
95
96         /* No #size-cells property for the root node */
97         return OF_ROOT_NODE_SIZE_CELLS_DEFAULT;
98 }
99
100 int of_simple_addr_cells(const struct device_node *np)
101 {
102         const __be32 *ip;
103
104         ip = of_get_property(np, "#address-cells", NULL);
105         if (ip)
106                 return be32_to_cpup(ip);
107
108         /* Return a default of 2 to match fdt_address_cells()*/
109         return 2;
110 }
111
112 int of_simple_size_cells(const struct device_node *np)
113 {
114         const __be32 *ip;
115
116         ip = of_get_property(np, "#size-cells", NULL);
117         if (ip)
118                 return be32_to_cpup(ip);
119
120         /* Return a default of 2 to match fdt_size_cells()*/
121         return 2;
122 }
123
124 struct property *of_find_property(const struct device_node *np,
125                                   const char *name, int *lenp)
126 {
127         struct property *pp;
128
129         if (!np)
130                 return NULL;
131
132         for (pp = np->properties; pp; pp = pp->next) {
133                 if (strcmp(pp->name, name) == 0) {
134                         if (lenp)
135                                 *lenp = pp->length;
136                         break;
137                 }
138         }
139         if (!pp && lenp)
140                 *lenp = -FDT_ERR_NOTFOUND;
141
142         return pp;
143 }
144
145 struct device_node *of_find_all_nodes(struct device_node *prev)
146 {
147         struct device_node *np;
148
149         if (!prev) {
150                 np = gd->of_root;
151         } else if (prev->child) {
152                 np = prev->child;
153         } else {
154                 /*
155                  * Walk back up looking for a sibling, or the end of the
156                  * structure
157                  */
158                 np = prev;
159                 while (np->parent && !np->sibling)
160                         np = np->parent;
161                 np = np->sibling; /* Might be null at the end of the tree */
162         }
163
164         return np;
165 }
166
167 const void *of_get_property(const struct device_node *np, const char *name,
168                             int *lenp)
169 {
170         struct property *pp = of_find_property(np, name, lenp);
171
172         return pp ? pp->value : NULL;
173 }
174
175 const struct property *of_get_first_property(const struct device_node *np)
176 {
177         if (!np)
178                 return NULL;
179
180         return  np->properties;
181 }
182
183 const struct property *of_get_next_property(const struct device_node *np,
184                                             const struct property *property)
185 {
186         if (!np)
187                 return NULL;
188
189         return property->next;
190 }
191
192 const void *of_get_property_by_prop(const struct device_node *np,
193                                     const struct property *property,
194                                     const char **name,
195                                     int *lenp)
196 {
197         if (!np || !property)
198                 return NULL;
199         if (name)
200                 *name = property->name;
201         if (lenp)
202                 *lenp = property->length;
203
204         return property->value;
205 }
206
207 static const char *of_prop_next_string(struct property *prop, const char *cur)
208 {
209         const void *curv = cur;
210
211         if (!prop)
212                 return NULL;
213
214         if (!cur)
215                 return prop->value;
216
217         curv += strlen(cur) + 1;
218         if (curv >= prop->value + prop->length)
219                 return NULL;
220
221         return curv;
222 }
223
224 int of_device_is_compatible(const struct device_node *device,
225                             const char *compat, const char *type,
226                             const char *name)
227 {
228         struct property *prop;
229         const char *cp;
230         int index = 0, score = 0;
231
232         /* Compatible match has highest priority */
233         if (compat && compat[0]) {
234                 prop = of_find_property(device, "compatible", NULL);
235                 for (cp = of_prop_next_string(prop, NULL); cp;
236                      cp = of_prop_next_string(prop, cp), index++) {
237                         if (of_compat_cmp(cp, compat, strlen(compat)) == 0) {
238                                 score = INT_MAX/2 - (index << 2);
239                                 break;
240                         }
241                 }
242                 if (!score)
243                         return 0;
244         }
245
246         /* Matching type is better than matching name */
247         if (type && type[0]) {
248                 if (!device->type || of_node_cmp(type, device->type))
249                         return 0;
250                 score += 2;
251         }
252
253         /* Matching name is a bit better than not */
254         if (name && name[0]) {
255                 if (!device->name || of_node_cmp(name, device->name))
256                         return 0;
257                 score++;
258         }
259
260         return score;
261 }
262
263 bool of_device_is_available(const struct device_node *device)
264 {
265         const char *status;
266         int statlen;
267
268         if (!device)
269                 return false;
270
271         status = of_get_property(device, "status", &statlen);
272         if (status == NULL)
273                 return true;
274
275         if (statlen > 0) {
276                 if (!strcmp(status, "okay"))
277                         return true;
278         }
279
280         return false;
281 }
282
283 struct device_node *of_get_parent(const struct device_node *node)
284 {
285         const struct device_node *np;
286
287         if (!node)
288                 return NULL;
289
290         np = of_node_get(node->parent);
291
292         return (struct device_node *)np;
293 }
294
295 static struct device_node *__of_get_next_child(const struct device_node *node,
296                                                struct device_node *prev)
297 {
298         struct device_node *next;
299
300         if (!node)
301                 return NULL;
302
303         next = prev ? prev->sibling : node->child;
304         /*
305          * coverity[dead_error_line : FALSE]
306          * Dead code here since our current implementation of of_node_get()
307          * always returns NULL (Coverity CID 163245). But we leave it as is
308          * since we may want to implement get/put later.
309          */
310         for (; next; next = next->sibling)
311                 if (of_node_get(next))
312                         break;
313         of_node_put(prev);
314         return next;
315 }
316
317 #define __for_each_child_of_node(parent, child) \
318         for (child = __of_get_next_child(parent, NULL); child != NULL; \
319              child = __of_get_next_child(parent, child))
320
321 static struct device_node *__of_find_node_by_path(struct device_node *parent,
322                                                   const char *path)
323 {
324         struct device_node *child;
325         int len;
326
327         len = strcspn(path, "/:");
328         if (!len)
329                 return NULL;
330
331         __for_each_child_of_node(parent, child) {
332                 const char *name = strrchr(child->full_name, '/');
333
334                 name++;
335                 if (strncmp(path, name, len) == 0 && (strlen(name) == len))
336                         return child;
337         }
338         return NULL;
339 }
340
341 #define for_each_property_of_node(dn, pp) \
342         for (pp = dn->properties; pp != NULL; pp = pp->next)
343
344 struct device_node *of_find_node_opts_by_path(const char *path,
345                                               const char **opts)
346 {
347         struct device_node *np = NULL;
348         struct property *pp;
349         const char *separator = strchr(path, ':');
350
351         if (opts)
352                 *opts = separator ? separator + 1 : NULL;
353
354         if (strcmp(path, "/") == 0)
355                 return of_node_get(gd->of_root);
356
357         /* The path could begin with an alias */
358         if (*path != '/') {
359                 int len;
360                 const char *p = separator;
361
362                 if (!p)
363                         p = strchrnul(path, '/');
364                 len = p - path;
365
366                 /* of_aliases must not be NULL */
367                 if (!of_aliases)
368                         return NULL;
369
370                 for_each_property_of_node(of_aliases, pp) {
371                         if (strlen(pp->name) == len && !strncmp(pp->name, path,
372                                                                 len)) {
373                                 np = of_find_node_by_path(pp->value);
374                                 break;
375                         }
376                 }
377                 if (!np)
378                         return NULL;
379                 path = p;
380         }
381
382         /* Step down the tree matching path components */
383         if (!np)
384                 np = of_node_get(gd->of_root);
385         while (np && *path == '/') {
386                 struct device_node *tmp = np;
387
388                 path++; /* Increment past '/' delimiter */
389                 np = __of_find_node_by_path(np, path);
390                 of_node_put(tmp);
391                 path = strchrnul(path, '/');
392                 if (separator && separator < path)
393                         break;
394         }
395
396         return np;
397 }
398
399 struct device_node *of_find_compatible_node(struct device_node *from,
400                 const char *type, const char *compatible)
401 {
402         struct device_node *np;
403
404         for_each_of_allnodes_from(from, np)
405                 if (of_device_is_compatible(np, compatible, type, NULL) &&
406                     of_node_get(np))
407                         break;
408         of_node_put(from);
409
410         return np;
411 }
412
413 static int of_device_has_prop_value(const struct device_node *device,
414                                     const char *propname, const void *propval,
415                                     int proplen)
416 {
417         struct property *prop = of_find_property(device, propname, NULL);
418
419         if (!prop || !prop->value || prop->length != proplen)
420                 return 0;
421         return !memcmp(prop->value, propval, proplen);
422 }
423
424 struct device_node *of_find_node_by_prop_value(struct device_node *from,
425                                                const char *propname,
426                                                const void *propval, int proplen)
427 {
428         struct device_node *np;
429
430         for_each_of_allnodes_from(from, np) {
431                 if (of_device_has_prop_value(np, propname, propval, proplen) &&
432                     of_node_get(np))
433                         break;
434         }
435         of_node_put(from);
436
437         return np;
438 }
439
440 struct device_node *of_find_node_by_phandle(phandle handle)
441 {
442         struct device_node *np;
443
444         if (!handle)
445                 return NULL;
446
447         for_each_of_allnodes(np)
448                 if (np->phandle == handle)
449                         break;
450         (void)of_node_get(np);
451
452         return np;
453 }
454
455 /**
456  * of_find_property_value_of_size() - find property of given size
457  *
458  * Search for a property in a device node and validate the requested size.
459  *
460  * @np:         device node from which the property value is to be read.
461  * @propname:   name of the property to be searched.
462  * @len:        requested length of property value
463  *
464  * @return the property value on success, -EINVAL if the property does not
465  * exist, -ENODATA if property does not have a value, and -EOVERFLOW if the
466  * property data isn't large enough.
467  */
468 static void *of_find_property_value_of_size(const struct device_node *np,
469                                             const char *propname, u32 len)
470 {
471         struct property *prop = of_find_property(np, propname, NULL);
472
473         if (!prop)
474                 return ERR_PTR(-EINVAL);
475         if (!prop->value)
476                 return ERR_PTR(-ENODATA);
477         if (len > prop->length)
478                 return ERR_PTR(-EOVERFLOW);
479
480         return prop->value;
481 }
482
483 int of_read_u32(const struct device_node *np, const char *propname, u32 *outp)
484 {
485         return of_read_u32_index(np, propname, 0, outp);
486 }
487
488 int of_read_u32_array(const struct device_node *np, const char *propname,
489                       u32 *out_values, size_t sz)
490 {
491         const __be32 *val;
492
493         debug("%s: %s: ", __func__, propname);
494         val = of_find_property_value_of_size(np, propname,
495                                              sz * sizeof(*out_values));
496
497         if (IS_ERR(val))
498                 return PTR_ERR(val);
499
500         debug("size %zd\n", sz);
501         while (sz--)
502                 *out_values++ = be32_to_cpup(val++);
503
504         return 0;
505 }
506
507 int of_read_u32_index(const struct device_node *np, const char *propname,
508                       int index, u32 *outp)
509 {
510         const __be32 *val;
511
512         debug("%s: %s: ", __func__, propname);
513         if (!np)
514                 return -EINVAL;
515
516         val = of_find_property_value_of_size(np, propname,
517                                              sizeof(*outp) * (index + 1));
518         if (IS_ERR(val)) {
519                 debug("(not found)\n");
520                 return PTR_ERR(val);
521         }
522
523         *outp = be32_to_cpup(val + index);
524         debug("%#x (%d)\n", *outp, *outp);
525
526         return 0;
527 }
528
529 int of_read_u64(const struct device_node *np, const char *propname, u64 *outp)
530 {
531         const __be64 *val;
532
533         debug("%s: %s: ", __func__, propname);
534         if (!np)
535                 return -EINVAL;
536         val = of_find_property_value_of_size(np, propname, sizeof(*outp));
537         if (IS_ERR(val)) {
538                 debug("(not found)\n");
539                 return PTR_ERR(val);
540         }
541
542         *outp = be64_to_cpup(val);
543         debug("%#llx (%lld)\n", (unsigned long long)*outp,
544               (unsigned long long)*outp);
545
546         return 0;
547 }
548
549 int of_property_match_string(const struct device_node *np, const char *propname,
550                              const char *string)
551 {
552         const struct property *prop = of_find_property(np, propname, NULL);
553         size_t l;
554         int i;
555         const char *p, *end;
556
557         if (!prop)
558                 return -EINVAL;
559         if (!prop->value)
560                 return -ENODATA;
561
562         p = prop->value;
563         end = p + prop->length;
564
565         for (i = 0; p < end; i++, p += l) {
566                 l = strnlen(p, end - p) + 1;
567                 if (p + l > end)
568                         return -EILSEQ;
569                 debug("comparing %s with %s\n", string, p);
570                 if (strcmp(string, p) == 0)
571                         return i; /* Found it; return index */
572         }
573         return -ENODATA;
574 }
575
576 /**
577  * of_property_read_string_helper() - Utility helper for parsing string properties
578  * @np:         device node from which the property value is to be read.
579  * @propname:   name of the property to be searched.
580  * @out_strs:   output array of string pointers.
581  * @sz:         number of array elements to read.
582  * @skip:       Number of strings to skip over at beginning of list.
583  *
584  * Don't call this function directly. It is a utility helper for the
585  * of_property_read_string*() family of functions.
586  */
587 int of_property_read_string_helper(const struct device_node *np,
588                                    const char *propname, const char **out_strs,
589                                    size_t sz, int skip)
590 {
591         const struct property *prop = of_find_property(np, propname, NULL);
592         int l = 0, i = 0;
593         const char *p, *end;
594
595         if (!prop)
596                 return -EINVAL;
597         if (!prop->value)
598                 return -ENODATA;
599         p = prop->value;
600         end = p + prop->length;
601
602         for (i = 0; p < end && (!out_strs || i < skip + sz); i++, p += l) {
603                 l = strnlen(p, end - p) + 1;
604                 if (p + l > end)
605                         return -EILSEQ;
606                 if (out_strs && i >= skip)
607                         *out_strs++ = p;
608         }
609         i -= skip;
610         return i <= 0 ? -ENODATA : i;
611 }
612
613 static int __of_parse_phandle_with_args(const struct device_node *np,
614                                         const char *list_name,
615                                         const char *cells_name,
616                                         int cell_count, int index,
617                                         struct of_phandle_args *out_args)
618 {
619         const __be32 *list, *list_end;
620         int rc = 0, cur_index = 0;
621         uint32_t count;
622         struct device_node *node = NULL;
623         phandle phandle;
624         int size;
625
626         /* Retrieve the phandle list property */
627         list = of_get_property(np, list_name, &size);
628         if (!list)
629                 return -ENOENT;
630         list_end = list + size / sizeof(*list);
631
632         /* Loop over the phandles until all the requested entry is found */
633         while (list < list_end) {
634                 rc = -EINVAL;
635                 count = 0;
636
637                 /*
638                  * If phandle is 0, then it is an empty entry with no
639                  * arguments.  Skip forward to the next entry.
640                  */
641                 phandle = be32_to_cpup(list++);
642                 if (phandle) {
643                         /*
644                          * Find the provider node and parse the #*-cells
645                          * property to determine the argument length.
646                          *
647                          * This is not needed if the cell count is hard-coded
648                          * (i.e. cells_name not set, but cell_count is set),
649                          * except when we're going to return the found node
650                          * below.
651                          */
652                         if (cells_name || cur_index == index) {
653                                 node = of_find_node_by_phandle(phandle);
654                                 if (!node) {
655                                         debug("%s: could not find phandle\n",
656                                               np->full_name);
657                                         goto err;
658                                 }
659                         }
660
661                         if (cells_name) {
662                                 if (of_read_u32(node, cells_name, &count)) {
663                                         debug("%s: could not get %s for %s\n",
664                                               np->full_name, cells_name,
665                                               node->full_name);
666                                         goto err;
667                                 }
668                         } else {
669                                 count = cell_count;
670                         }
671
672                         /*
673                          * Make sure that the arguments actually fit in the
674                          * remaining property data length
675                          */
676                         if (list + count > list_end) {
677                                 debug("%s: arguments longer than property\n",
678                                       np->full_name);
679                                 goto err;
680                         }
681                 }
682
683                 /*
684                  * All of the error cases above bail out of the loop, so at
685                  * this point, the parsing is successful. If the requested
686                  * index matches, then fill the out_args structure and return,
687                  * or return -ENOENT for an empty entry.
688                  */
689                 rc = -ENOENT;
690                 if (cur_index == index) {
691                         if (!phandle)
692                                 goto err;
693
694                         if (out_args) {
695                                 int i;
696                                 if (WARN_ON(count > OF_MAX_PHANDLE_ARGS))
697                                         count = OF_MAX_PHANDLE_ARGS;
698                                 out_args->np = node;
699                                 out_args->args_count = count;
700                                 for (i = 0; i < count; i++)
701                                         out_args->args[i] =
702                                                         be32_to_cpup(list++);
703                         } else {
704                                 of_node_put(node);
705                         }
706
707                         /* Found it! return success */
708                         return 0;
709                 }
710
711                 of_node_put(node);
712                 node = NULL;
713                 list += count;
714                 cur_index++;
715         }
716
717         /*
718          * Unlock node before returning result; will be one of:
719          * -ENOENT : index is for empty phandle
720          * -EINVAL : parsing error on data
721          * [1..n]  : Number of phandle (count mode; when index = -1)
722          */
723         rc = index < 0 ? cur_index : -ENOENT;
724  err:
725         if (node)
726                 of_node_put(node);
727         return rc;
728 }
729
730 struct device_node *of_parse_phandle(const struct device_node *np,
731                                      const char *phandle_name, int index)
732 {
733         struct of_phandle_args args;
734
735         if (index < 0)
736                 return NULL;
737
738         if (__of_parse_phandle_with_args(np, phandle_name, NULL, 0, index,
739                                          &args))
740                 return NULL;
741
742         return args.np;
743 }
744
745 int of_parse_phandle_with_args(const struct device_node *np,
746                                const char *list_name, const char *cells_name,
747                                int index, struct of_phandle_args *out_args)
748 {
749         if (index < 0)
750                 return -EINVAL;
751
752         return __of_parse_phandle_with_args(np, list_name, cells_name, 0,
753                                             index, out_args);
754 }
755
756 int of_count_phandle_with_args(const struct device_node *np,
757                                const char *list_name, const char *cells_name)
758 {
759         return __of_parse_phandle_with_args(np, list_name, cells_name, 0,
760                                             -1, NULL);
761 }
762
763 static void of_alias_add(struct alias_prop *ap, struct device_node *np,
764                          int id, const char *stem, int stem_len)
765 {
766         ap->np = np;
767         ap->id = id;
768         strncpy(ap->stem, stem, stem_len);
769         ap->stem[stem_len] = 0;
770         list_add_tail(&ap->link, &aliases_lookup);
771         debug("adding DT alias:%s: stem=%s id=%i node=%s\n",
772               ap->alias, ap->stem, ap->id, of_node_full_name(np));
773 }
774
775 int of_alias_scan(void)
776 {
777         struct property *pp;
778
779         of_aliases = of_find_node_by_path("/aliases");
780         of_chosen = of_find_node_by_path("/chosen");
781         if (of_chosen == NULL)
782                 of_chosen = of_find_node_by_path("/chosen@0");
783
784         if (of_chosen) {
785                 const char *name;
786
787                 name = of_get_property(of_chosen, "stdout-path", NULL);
788                 if (name)
789                         of_stdout = of_find_node_opts_by_path(name,
790                                                         &of_stdout_options);
791         }
792
793         if (!of_aliases)
794                 return 0;
795
796         for_each_property_of_node(of_aliases, pp) {
797                 const char *start = pp->name;
798                 const char *end = start + strlen(start);
799                 struct device_node *np;
800                 struct alias_prop *ap;
801                 ulong id;
802                 int len;
803
804                 /* Skip those we do not want to proceed */
805                 if (!strcmp(pp->name, "name") ||
806                     !strcmp(pp->name, "phandle") ||
807                     !strcmp(pp->name, "linux,phandle"))
808                         continue;
809
810                 np = of_find_node_by_path(pp->value);
811                 if (!np)
812                         continue;
813
814                 /*
815                  * walk the alias backwards to extract the id and work out
816                  * the 'stem' string
817                  */
818                 while (isdigit(*(end-1)) && end > start)
819                         end--;
820                 len = end - start;
821
822                 if (strict_strtoul(end, 10, &id) < 0)
823                         continue;
824
825                 /* Allocate an alias_prop with enough space for the stem */
826                 ap = malloc(sizeof(*ap) + len + 1);
827                 if (!ap)
828                         return -ENOMEM;
829                 memset(ap, 0, sizeof(*ap) + len + 1);
830                 ap->alias = start;
831                 of_alias_add(ap, np, id, start, len);
832         }
833
834         return 0;
835 }
836
837 int of_alias_get_id(const struct device_node *np, const char *stem)
838 {
839         struct alias_prop *app;
840         int id = -ENODEV;
841
842         mutex_lock(&of_mutex);
843         list_for_each_entry(app, &aliases_lookup, link) {
844                 if (strcmp(app->stem, stem) != 0)
845                         continue;
846
847                 if (np == app->np) {
848                         id = app->id;
849                         break;
850                 }
851         }
852         mutex_unlock(&of_mutex);
853
854         return id;
855 }
856
857 int of_alias_get_highest_id(const char *stem)
858 {
859         struct alias_prop *app;
860         int id = -1;
861
862         mutex_lock(&of_mutex);
863         list_for_each_entry(app, &aliases_lookup, link) {
864                 if (strcmp(app->stem, stem) != 0)
865                         continue;
866
867                 if (app->id > id)
868                         id = app->id;
869         }
870         mutex_unlock(&of_mutex);
871
872         return id;
873 }
874
875 struct device_node *of_get_stdout(void)
876 {
877         return of_stdout;
878 }