GNU Linux-libre 4.14.290-gnu1
[releases.git] / drivers / of / fdt.c
1 /*
2  * Functions for working with the Flattened Device Tree data format
3  *
4  * Copyright 2009 Benjamin Herrenschmidt, IBM Corp
5  * benh@kernel.crashing.org
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * version 2 as published by the Free Software Foundation.
10  */
11
12 #define pr_fmt(fmt)     "OF: fdt: " fmt
13
14 #include <linux/crc32.h>
15 #include <linux/kernel.h>
16 #include <linux/initrd.h>
17 #include <linux/memblock.h>
18 #include <linux/mutex.h>
19 #include <linux/of.h>
20 #include <linux/of_fdt.h>
21 #include <linux/of_reserved_mem.h>
22 #include <linux/sizes.h>
23 #include <linux/string.h>
24 #include <linux/errno.h>
25 #include <linux/slab.h>
26 #include <linux/libfdt.h>
27 #include <linux/debugfs.h>
28 #include <linux/serial_core.h>
29 #include <linux/sysfs.h>
30 #include <linux/random.h>
31
32 #include <asm/setup.h>  /* for COMMAND_LINE_SIZE */
33 #include <asm/page.h>
34
35 #include "of_private.h"
36
37 /*
38  * of_fdt_limit_memory - limit the number of regions in the /memory node
39  * @limit: maximum entries
40  *
41  * Adjust the flattened device tree to have at most 'limit' number of
42  * memory entries in the /memory node. This function may be called
43  * any time after initial_boot_param is set.
44  */
45 void of_fdt_limit_memory(int limit)
46 {
47         int memory;
48         int len;
49         const void *val;
50         int nr_address_cells = OF_ROOT_NODE_ADDR_CELLS_DEFAULT;
51         int nr_size_cells = OF_ROOT_NODE_SIZE_CELLS_DEFAULT;
52         const __be32 *addr_prop;
53         const __be32 *size_prop;
54         int root_offset;
55         int cell_size;
56
57         root_offset = fdt_path_offset(initial_boot_params, "/");
58         if (root_offset < 0)
59                 return;
60
61         addr_prop = fdt_getprop(initial_boot_params, root_offset,
62                                 "#address-cells", NULL);
63         if (addr_prop)
64                 nr_address_cells = fdt32_to_cpu(*addr_prop);
65
66         size_prop = fdt_getprop(initial_boot_params, root_offset,
67                                 "#size-cells", NULL);
68         if (size_prop)
69                 nr_size_cells = fdt32_to_cpu(*size_prop);
70
71         cell_size = sizeof(uint32_t)*(nr_address_cells + nr_size_cells);
72
73         memory = fdt_path_offset(initial_boot_params, "/memory");
74         if (memory > 0) {
75                 val = fdt_getprop(initial_boot_params, memory, "reg", &len);
76                 if (len > limit*cell_size) {
77                         len = limit*cell_size;
78                         pr_debug("Limiting number of entries to %d\n", limit);
79                         fdt_setprop(initial_boot_params, memory, "reg", val,
80                                         len);
81                 }
82         }
83 }
84
85 /**
86  * of_fdt_is_compatible - Return true if given node from the given blob has
87  * compat in its compatible list
88  * @blob: A device tree blob
89  * @node: node to test
90  * @compat: compatible string to compare with compatible list.
91  *
92  * On match, returns a non-zero value with smaller values returned for more
93  * specific compatible values.
94  */
95 static int of_fdt_is_compatible(const void *blob,
96                       unsigned long node, const char *compat)
97 {
98         const char *cp;
99         int cplen;
100         unsigned long l, score = 0;
101
102         cp = fdt_getprop(blob, node, "compatible", &cplen);
103         if (cp == NULL)
104                 return 0;
105         while (cplen > 0) {
106                 score++;
107                 if (of_compat_cmp(cp, compat, strlen(compat)) == 0)
108                         return score;
109                 l = strlen(cp) + 1;
110                 cp += l;
111                 cplen -= l;
112         }
113
114         return 0;
115 }
116
117 /**
118  * of_fdt_is_big_endian - Return true if given node needs BE MMIO accesses
119  * @blob: A device tree blob
120  * @node: node to test
121  *
122  * Returns true if the node has a "big-endian" property, or if the kernel
123  * was compiled for BE *and* the node has a "native-endian" property.
124  * Returns false otherwise.
125  */
126 bool of_fdt_is_big_endian(const void *blob, unsigned long node)
127 {
128         if (fdt_getprop(blob, node, "big-endian", NULL))
129                 return true;
130         if (IS_ENABLED(CONFIG_CPU_BIG_ENDIAN) &&
131             fdt_getprop(blob, node, "native-endian", NULL))
132                 return true;
133         return false;
134 }
135
136 /**
137  * of_fdt_match - Return true if node matches a list of compatible values
138  */
139 int of_fdt_match(const void *blob, unsigned long node,
140                  const char *const *compat)
141 {
142         unsigned int tmp, score = 0;
143
144         if (!compat)
145                 return 0;
146
147         while (*compat) {
148                 tmp = of_fdt_is_compatible(blob, node, *compat);
149                 if (tmp && (score == 0 || (tmp < score)))
150                         score = tmp;
151                 compat++;
152         }
153
154         return score;
155 }
156
157 static void *unflatten_dt_alloc(void **mem, unsigned long size,
158                                        unsigned long align)
159 {
160         void *res;
161
162         *mem = PTR_ALIGN(*mem, align);
163         res = *mem;
164         *mem += size;
165
166         return res;
167 }
168
169 static void populate_properties(const void *blob,
170                                 int offset,
171                                 void **mem,
172                                 struct device_node *np,
173                                 const char *nodename,
174                                 bool dryrun)
175 {
176         struct property *pp, **pprev = NULL;
177         int cur;
178         bool has_name = false;
179
180         pprev = &np->properties;
181         for (cur = fdt_first_property_offset(blob, offset);
182              cur >= 0;
183              cur = fdt_next_property_offset(blob, cur)) {
184                 const __be32 *val;
185                 const char *pname;
186                 u32 sz;
187
188                 val = fdt_getprop_by_offset(blob, cur, &pname, &sz);
189                 if (!val) {
190                         pr_warn("Cannot locate property at 0x%x\n", cur);
191                         continue;
192                 }
193
194                 if (!pname) {
195                         pr_warn("Cannot find property name at 0x%x\n", cur);
196                         continue;
197                 }
198
199                 if (!strcmp(pname, "name"))
200                         has_name = true;
201
202                 pp = unflatten_dt_alloc(mem, sizeof(struct property),
203                                         __alignof__(struct property));
204                 if (dryrun)
205                         continue;
206
207                 /* We accept flattened tree phandles either in
208                  * ePAPR-style "phandle" properties, or the
209                  * legacy "linux,phandle" properties.  If both
210                  * appear and have different values, things
211                  * will get weird. Don't do that.
212                  */
213                 if (!strcmp(pname, "phandle") ||
214                     !strcmp(pname, "linux,phandle")) {
215                         if (!np->phandle)
216                                 np->phandle = be32_to_cpup(val);
217                 }
218
219                 /* And we process the "ibm,phandle" property
220                  * used in pSeries dynamic device tree
221                  * stuff
222                  */
223                 if (!strcmp(pname, "ibm,phandle"))
224                         np->phandle = be32_to_cpup(val);
225
226                 pp->name   = (char *)pname;
227                 pp->length = sz;
228                 pp->value  = (__be32 *)val;
229                 *pprev     = pp;
230                 pprev      = &pp->next;
231         }
232
233         /* With version 0x10 we may not have the name property,
234          * recreate it here from the unit name if absent
235          */
236         if (!has_name) {
237                 const char *p = nodename, *ps = p, *pa = NULL;
238                 int len;
239
240                 while (*p) {
241                         if ((*p) == '@')
242                                 pa = p;
243                         else if ((*p) == '/')
244                                 ps = p + 1;
245                         p++;
246                 }
247
248                 if (pa < ps)
249                         pa = p;
250                 len = (pa - ps) + 1;
251                 pp = unflatten_dt_alloc(mem, sizeof(struct property) + len,
252                                         __alignof__(struct property));
253                 if (!dryrun) {
254                         pp->name   = "name";
255                         pp->length = len;
256                         pp->value  = pp + 1;
257                         *pprev     = pp;
258                         pprev      = &pp->next;
259                         memcpy(pp->value, ps, len - 1);
260                         ((char *)pp->value)[len - 1] = 0;
261                         pr_debug("fixed up name for %s -> %s\n",
262                                  nodename, (char *)pp->value);
263                 }
264         }
265
266         if (!dryrun)
267                 *pprev = NULL;
268 }
269
270 static unsigned int populate_node(const void *blob,
271                                   int offset,
272                                   void **mem,
273                                   struct device_node *dad,
274                                   unsigned int fpsize,
275                                   struct device_node **pnp,
276                                   bool dryrun)
277 {
278         struct device_node *np;
279         const char *pathp;
280         unsigned int l, allocl;
281         int new_format = 0;
282
283         pathp = fdt_get_name(blob, offset, &l);
284         if (!pathp) {
285                 *pnp = NULL;
286                 return 0;
287         }
288
289         allocl = ++l;
290
291         /* version 0x10 has a more compact unit name here instead of the full
292          * path. we accumulate the full path size using "fpsize", we'll rebuild
293          * it later. We detect this because the first character of the name is
294          * not '/'.
295          */
296         if ((*pathp) != '/') {
297                 new_format = 1;
298                 if (fpsize == 0) {
299                         /* root node: special case. fpsize accounts for path
300                          * plus terminating zero. root node only has '/', so
301                          * fpsize should be 2, but we want to avoid the first
302                          * level nodes to have two '/' so we use fpsize 1 here
303                          */
304                         fpsize = 1;
305                         allocl = 2;
306                         l = 1;
307                         pathp = "";
308                 } else {
309                         /* account for '/' and path size minus terminal 0
310                          * already in 'l'
311                          */
312                         fpsize += l;
313                         allocl = fpsize;
314                 }
315         }
316
317         np = unflatten_dt_alloc(mem, sizeof(struct device_node) + allocl,
318                                 __alignof__(struct device_node));
319         if (!dryrun) {
320                 char *fn;
321                 of_node_init(np);
322                 np->full_name = fn = ((char *)np) + sizeof(*np);
323                 if (new_format) {
324                         /* rebuild full path for new format */
325                         if (dad && dad->parent) {
326                                 strcpy(fn, dad->full_name);
327 #ifdef DEBUG
328                                 if ((strlen(fn) + l + 1) != allocl) {
329                                         pr_debug("%s: p: %d, l: %d, a: %d\n",
330                                                 pathp, (int)strlen(fn),
331                                                 l, allocl);
332                                 }
333 #endif
334                                 fn += strlen(fn);
335                         }
336                         *(fn++) = '/';
337                 }
338                 memcpy(fn, pathp, l);
339
340                 if (dad != NULL) {
341                         np->parent = dad;
342                         np->sibling = dad->child;
343                         dad->child = np;
344                 }
345         }
346
347         populate_properties(blob, offset, mem, np, pathp, dryrun);
348         if (!dryrun) {
349                 np->name = of_get_property(np, "name", NULL);
350                 np->type = of_get_property(np, "device_type", NULL);
351
352                 if (!np->name)
353                         np->name = "<NULL>";
354                 if (!np->type)
355                         np->type = "<NULL>";
356         }
357
358         *pnp = np;
359         return fpsize;
360 }
361
362 static void reverse_nodes(struct device_node *parent)
363 {
364         struct device_node *child, *next;
365
366         /* In-depth first */
367         child = parent->child;
368         while (child) {
369                 reverse_nodes(child);
370
371                 child = child->sibling;
372         }
373
374         /* Reverse the nodes in the child list */
375         child = parent->child;
376         parent->child = NULL;
377         while (child) {
378                 next = child->sibling;
379
380                 child->sibling = parent->child;
381                 parent->child = child;
382                 child = next;
383         }
384 }
385
386 /**
387  * unflatten_dt_nodes - Alloc and populate a device_node from the flat tree
388  * @blob: The parent device tree blob
389  * @mem: Memory chunk to use for allocating device nodes and properties
390  * @dad: Parent struct device_node
391  * @nodepp: The device_node tree created by the call
392  *
393  * It returns the size of unflattened device tree or error code
394  */
395 static int unflatten_dt_nodes(const void *blob,
396                               void *mem,
397                               struct device_node *dad,
398                               struct device_node **nodepp)
399 {
400         struct device_node *root;
401         int offset = 0, depth = 0, initial_depth = 0;
402 #define FDT_MAX_DEPTH   64
403         unsigned int fpsizes[FDT_MAX_DEPTH];
404         struct device_node *nps[FDT_MAX_DEPTH];
405         void *base = mem;
406         bool dryrun = !base;
407
408         if (nodepp)
409                 *nodepp = NULL;
410
411         /*
412          * We're unflattening device sub-tree if @dad is valid. There are
413          * possibly multiple nodes in the first level of depth. We need
414          * set @depth to 1 to make fdt_next_node() happy as it bails
415          * immediately when negative @depth is found. Otherwise, the device
416          * nodes except the first one won't be unflattened successfully.
417          */
418         if (dad)
419                 depth = initial_depth = 1;
420
421         root = dad;
422         fpsizes[depth] = dad ? strlen(of_node_full_name(dad)) : 0;
423         nps[depth] = dad;
424
425         for (offset = 0;
426              offset >= 0 && depth >= initial_depth;
427              offset = fdt_next_node(blob, offset, &depth)) {
428                 if (WARN_ON_ONCE(depth >= FDT_MAX_DEPTH))
429                         continue;
430
431                 fpsizes[depth+1] = populate_node(blob, offset, &mem,
432                                                  nps[depth],
433                                                  fpsizes[depth],
434                                                  &nps[depth+1], dryrun);
435                 if (!fpsizes[depth+1])
436                         return mem - base;
437
438                 if (!dryrun && nodepp && !*nodepp)
439                         *nodepp = nps[depth+1];
440                 if (!dryrun && !root)
441                         root = nps[depth+1];
442         }
443
444         if (offset < 0 && offset != -FDT_ERR_NOTFOUND) {
445                 pr_err("Error %d processing FDT\n", offset);
446                 return -EINVAL;
447         }
448
449         /*
450          * Reverse the child list. Some drivers assumes node order matches .dts
451          * node order
452          */
453         if (!dryrun)
454                 reverse_nodes(root);
455
456         return mem - base;
457 }
458
459 /**
460  * __unflatten_device_tree - create tree of device_nodes from flat blob
461  *
462  * unflattens a device-tree, creating the
463  * tree of struct device_node. It also fills the "name" and "type"
464  * pointers of the nodes so the normal device-tree walking functions
465  * can be used.
466  * @blob: The blob to expand
467  * @dad: Parent device node
468  * @mynodes: The device_node tree created by the call
469  * @dt_alloc: An allocator that provides a virtual address to memory
470  * for the resulting tree
471  *
472  * Returns NULL on failure or the memory chunk containing the unflattened
473  * device tree on success.
474  */
475 void *__unflatten_device_tree(const void *blob,
476                               struct device_node *dad,
477                               struct device_node **mynodes,
478                               void *(*dt_alloc)(u64 size, u64 align),
479                               bool detached)
480 {
481         int size;
482         void *mem;
483
484         pr_debug(" -> unflatten_device_tree()\n");
485
486         if (!blob) {
487                 pr_debug("No device tree pointer\n");
488                 return NULL;
489         }
490
491         pr_debug("Unflattening device tree:\n");
492         pr_debug("magic: %08x\n", fdt_magic(blob));
493         pr_debug("size: %08x\n", fdt_totalsize(blob));
494         pr_debug("version: %08x\n", fdt_version(blob));
495
496         if (fdt_check_header(blob)) {
497                 pr_err("Invalid device tree blob header\n");
498                 return NULL;
499         }
500
501         /* First pass, scan for size */
502         size = unflatten_dt_nodes(blob, NULL, dad, NULL);
503         if (size < 0)
504                 return NULL;
505
506         size = ALIGN(size, 4);
507         pr_debug("  size is %d, allocating...\n", size);
508
509         /* Allocate memory for the expanded device tree */
510         mem = dt_alloc(size + 4, __alignof__(struct device_node));
511         if (!mem)
512                 return NULL;
513
514         memset(mem, 0, size);
515
516         *(__be32 *)(mem + size) = cpu_to_be32(0xdeadbeef);
517
518         pr_debug("  unflattening %p...\n", mem);
519
520         /* Second pass, do actual unflattening */
521         unflatten_dt_nodes(blob, mem, dad, mynodes);
522         if (be32_to_cpup(mem + size) != 0xdeadbeef)
523                 pr_warning("End of tree marker overwritten: %08x\n",
524                            be32_to_cpup(mem + size));
525
526         if (detached && mynodes) {
527                 of_node_set_flag(*mynodes, OF_DETACHED);
528                 pr_debug("unflattened tree is detached\n");
529         }
530
531         pr_debug(" <- unflatten_device_tree()\n");
532         return mem;
533 }
534
535 static void *kernel_tree_alloc(u64 size, u64 align)
536 {
537         return kzalloc(size, GFP_KERNEL);
538 }
539
540 static DEFINE_MUTEX(of_fdt_unflatten_mutex);
541
542 /**
543  * of_fdt_unflatten_tree - create tree of device_nodes from flat blob
544  * @blob: Flat device tree blob
545  * @dad: Parent device node
546  * @mynodes: The device tree created by the call
547  *
548  * unflattens the device-tree passed by the firmware, creating the
549  * tree of struct device_node. It also fills the "name" and "type"
550  * pointers of the nodes so the normal device-tree walking functions
551  * can be used.
552  *
553  * Returns NULL on failure or the memory chunk containing the unflattened
554  * device tree on success.
555  */
556 void *of_fdt_unflatten_tree(const unsigned long *blob,
557                             struct device_node *dad,
558                             struct device_node **mynodes)
559 {
560         void *mem;
561
562         mutex_lock(&of_fdt_unflatten_mutex);
563         mem = __unflatten_device_tree(blob, dad, mynodes, &kernel_tree_alloc,
564                                       true);
565         mutex_unlock(&of_fdt_unflatten_mutex);
566
567         return mem;
568 }
569 EXPORT_SYMBOL_GPL(of_fdt_unflatten_tree);
570
571 /* Everything below here references initial_boot_params directly. */
572 int __initdata dt_root_addr_cells;
573 int __initdata dt_root_size_cells;
574
575 void *initial_boot_params;
576
577 #ifdef CONFIG_OF_EARLY_FLATTREE
578
579 static u32 of_fdt_crc32;
580
581 /**
582  * res_mem_reserve_reg() - reserve all memory described in 'reg' property
583  */
584 static int __init __reserved_mem_reserve_reg(unsigned long node,
585                                              const char *uname)
586 {
587         int t_len = (dt_root_addr_cells + dt_root_size_cells) * sizeof(__be32);
588         phys_addr_t base, size;
589         int len;
590         const __be32 *prop;
591         int nomap, first = 1;
592
593         prop = of_get_flat_dt_prop(node, "reg", &len);
594         if (!prop)
595                 return -ENOENT;
596
597         if (len && len % t_len != 0) {
598                 pr_err("Reserved memory: invalid reg property in '%s', skipping node.\n",
599                        uname);
600                 return -EINVAL;
601         }
602
603         nomap = of_get_flat_dt_prop(node, "no-map", NULL) != NULL;
604
605         while (len >= t_len) {
606                 base = dt_mem_next_cell(dt_root_addr_cells, &prop);
607                 size = dt_mem_next_cell(dt_root_size_cells, &prop);
608
609                 if (size &&
610                     early_init_dt_reserve_memory_arch(base, size, nomap) == 0)
611                         pr_debug("Reserved memory: reserved region for node '%s': base %pa, size %lu MiB\n",
612                                 uname, &base, (unsigned long)(size / SZ_1M));
613                 else
614                         pr_info("Reserved memory: failed to reserve memory for node '%s': base %pa, size %lu MiB\n",
615                                 uname, &base, (unsigned long)(size / SZ_1M));
616
617                 len -= t_len;
618                 if (first) {
619                         fdt_reserved_mem_save_node(node, uname, base, size);
620                         first = 0;
621                 }
622         }
623         return 0;
624 }
625
626 /**
627  * __reserved_mem_check_root() - check if #size-cells, #address-cells provided
628  * in /reserved-memory matches the values supported by the current implementation,
629  * also check if ranges property has been provided
630  */
631 static int __init __reserved_mem_check_root(unsigned long node)
632 {
633         const __be32 *prop;
634
635         prop = of_get_flat_dt_prop(node, "#size-cells", NULL);
636         if (!prop || be32_to_cpup(prop) != dt_root_size_cells)
637                 return -EINVAL;
638
639         prop = of_get_flat_dt_prop(node, "#address-cells", NULL);
640         if (!prop || be32_to_cpup(prop) != dt_root_addr_cells)
641                 return -EINVAL;
642
643         prop = of_get_flat_dt_prop(node, "ranges", NULL);
644         if (!prop)
645                 return -EINVAL;
646         return 0;
647 }
648
649 /**
650  * fdt_scan_reserved_mem() - scan a single FDT node for reserved memory
651  */
652 static int __init __fdt_scan_reserved_mem(unsigned long node, const char *uname,
653                                           int depth, void *data)
654 {
655         static int found;
656         const char *status;
657         int err;
658
659         if (!found && depth == 1 && strcmp(uname, "reserved-memory") == 0) {
660                 if (__reserved_mem_check_root(node) != 0) {
661                         pr_err("Reserved memory: unsupported node format, ignoring\n");
662                         /* break scan */
663                         return 1;
664                 }
665                 found = 1;
666                 /* scan next node */
667                 return 0;
668         } else if (!found) {
669                 /* scan next node */
670                 return 0;
671         } else if (found && depth < 2) {
672                 /* scanning of /reserved-memory has been finished */
673                 return 1;
674         }
675
676         status = of_get_flat_dt_prop(node, "status", NULL);
677         if (status && strcmp(status, "okay") != 0 && strcmp(status, "ok") != 0)
678                 return 0;
679
680         err = __reserved_mem_reserve_reg(node, uname);
681         if (err == -ENOENT && of_get_flat_dt_prop(node, "size", NULL))
682                 fdt_reserved_mem_save_node(node, uname, 0, 0);
683
684         /* scan next node */
685         return 0;
686 }
687
688 /**
689  * early_init_fdt_scan_reserved_mem() - create reserved memory regions
690  *
691  * This function grabs memory from early allocator for device exclusive use
692  * defined in device tree structures. It should be called by arch specific code
693  * once the early allocator (i.e. memblock) has been fully activated.
694  */
695 void __init early_init_fdt_scan_reserved_mem(void)
696 {
697         int n;
698         u64 base, size;
699
700         if (!initial_boot_params)
701                 return;
702
703         /* Process header /memreserve/ fields */
704         for (n = 0; ; n++) {
705                 fdt_get_mem_rsv(initial_boot_params, n, &base, &size);
706                 if (!size)
707                         break;
708                 early_init_dt_reserve_memory_arch(base, size, 0);
709         }
710
711         of_scan_flat_dt(__fdt_scan_reserved_mem, NULL);
712         fdt_init_reserved_mem();
713 }
714
715 /**
716  * early_init_fdt_reserve_self() - reserve the memory used by the FDT blob
717  */
718 void __init early_init_fdt_reserve_self(void)
719 {
720         if (!initial_boot_params)
721                 return;
722
723         /* Reserve the dtb region */
724         early_init_dt_reserve_memory_arch(__pa(initial_boot_params),
725                                           fdt_totalsize(initial_boot_params),
726                                           0);
727 }
728
729 /**
730  * of_scan_flat_dt - scan flattened tree blob and call callback on each.
731  * @it: callback function
732  * @data: context data pointer
733  *
734  * This function is used to scan the flattened device-tree, it is
735  * used to extract the memory information at boot before we can
736  * unflatten the tree
737  */
738 int __init of_scan_flat_dt(int (*it)(unsigned long node,
739                                      const char *uname, int depth,
740                                      void *data),
741                            void *data)
742 {
743         const void *blob = initial_boot_params;
744         const char *pathp;
745         int offset, rc = 0, depth = -1;
746
747         if (!blob)
748                 return 0;
749
750         for (offset = fdt_next_node(blob, -1, &depth);
751              offset >= 0 && depth >= 0 && !rc;
752              offset = fdt_next_node(blob, offset, &depth)) {
753
754                 pathp = fdt_get_name(blob, offset, NULL);
755                 if (*pathp == '/')
756                         pathp = kbasename(pathp);
757                 rc = it(offset, pathp, depth, data);
758         }
759         return rc;
760 }
761
762 /**
763  * of_scan_flat_dt_subnodes - scan sub-nodes of a node call callback on each.
764  * @it: callback function
765  * @data: context data pointer
766  *
767  * This function is used to scan sub-nodes of a node.
768  */
769 int __init of_scan_flat_dt_subnodes(unsigned long parent,
770                                     int (*it)(unsigned long node,
771                                               const char *uname,
772                                               void *data),
773                                     void *data)
774 {
775         const void *blob = initial_boot_params;
776         int node;
777
778         fdt_for_each_subnode(node, blob, parent) {
779                 const char *pathp;
780                 int rc;
781
782                 pathp = fdt_get_name(blob, node, NULL);
783                 if (*pathp == '/')
784                         pathp = kbasename(pathp);
785                 rc = it(node, pathp, data);
786                 if (rc)
787                         return rc;
788         }
789         return 0;
790 }
791
792 /**
793  * of_get_flat_dt_subnode_by_name - get the subnode by given name
794  *
795  * @node: the parent node
796  * @uname: the name of subnode
797  * @return offset of the subnode, or -FDT_ERR_NOTFOUND if there is none
798  */
799
800 int of_get_flat_dt_subnode_by_name(unsigned long node, const char *uname)
801 {
802         return fdt_subnode_offset(initial_boot_params, node, uname);
803 }
804
805 /**
806  * of_get_flat_dt_root - find the root node in the flat blob
807  */
808 unsigned long __init of_get_flat_dt_root(void)
809 {
810         return 0;
811 }
812
813 /**
814  * of_get_flat_dt_size - Return the total size of the FDT
815  */
816 int __init of_get_flat_dt_size(void)
817 {
818         return fdt_totalsize(initial_boot_params);
819 }
820
821 /**
822  * of_get_flat_dt_prop - Given a node in the flat blob, return the property ptr
823  *
824  * This function can be used within scan_flattened_dt callback to get
825  * access to properties
826  */
827 const void *__init of_get_flat_dt_prop(unsigned long node, const char *name,
828                                        int *size)
829 {
830         return fdt_getprop(initial_boot_params, node, name, size);
831 }
832
833 /**
834  * of_flat_dt_is_compatible - Return true if given node has compat in compatible list
835  * @node: node to test
836  * @compat: compatible string to compare with compatible list.
837  */
838 int __init of_flat_dt_is_compatible(unsigned long node, const char *compat)
839 {
840         return of_fdt_is_compatible(initial_boot_params, node, compat);
841 }
842
843 /**
844  * of_flat_dt_match - Return true if node matches a list of compatible values
845  */
846 int __init of_flat_dt_match(unsigned long node, const char *const *compat)
847 {
848         return of_fdt_match(initial_boot_params, node, compat);
849 }
850
851 /**
852  * of_get_flat_dt_prop - Given a node in the flat blob, return the phandle
853  */
854 uint32_t __init of_get_flat_dt_phandle(unsigned long node)
855 {
856         return fdt_get_phandle(initial_boot_params, node);
857 }
858
859 struct fdt_scan_status {
860         const char *name;
861         int namelen;
862         int depth;
863         int found;
864         int (*iterator)(unsigned long node, const char *uname, int depth, void *data);
865         void *data;
866 };
867
868 const char * __init of_flat_dt_get_machine_name(void)
869 {
870         const char *name;
871         unsigned long dt_root = of_get_flat_dt_root();
872
873         name = of_get_flat_dt_prop(dt_root, "model", NULL);
874         if (!name)
875                 name = of_get_flat_dt_prop(dt_root, "compatible", NULL);
876         return name;
877 }
878
879 /**
880  * of_flat_dt_match_machine - Iterate match tables to find matching machine.
881  *
882  * @default_match: A machine specific ptr to return in case of no match.
883  * @get_next_compat: callback function to return next compatible match table.
884  *
885  * Iterate through machine match tables to find the best match for the machine
886  * compatible string in the FDT.
887  */
888 const void * __init of_flat_dt_match_machine(const void *default_match,
889                 const void * (*get_next_compat)(const char * const**))
890 {
891         const void *data = NULL;
892         const void *best_data = default_match;
893         const char *const *compat;
894         unsigned long dt_root;
895         unsigned int best_score = ~1, score = 0;
896
897         dt_root = of_get_flat_dt_root();
898         while ((data = get_next_compat(&compat))) {
899                 score = of_flat_dt_match(dt_root, compat);
900                 if (score > 0 && score < best_score) {
901                         best_data = data;
902                         best_score = score;
903                 }
904         }
905         if (!best_data) {
906                 const char *prop;
907                 int size;
908
909                 pr_err("\n unrecognized device tree list:\n[ ");
910
911                 prop = of_get_flat_dt_prop(dt_root, "compatible", &size);
912                 if (prop) {
913                         while (size > 0) {
914                                 printk("'%s' ", prop);
915                                 size -= strlen(prop) + 1;
916                                 prop += strlen(prop) + 1;
917                         }
918                 }
919                 printk("]\n\n");
920                 return NULL;
921         }
922
923         pr_info("Machine model: %s\n", of_flat_dt_get_machine_name());
924
925         return best_data;
926 }
927
928 #ifdef CONFIG_BLK_DEV_INITRD
929 #ifndef __early_init_dt_declare_initrd
930 static void __early_init_dt_declare_initrd(unsigned long start,
931                                            unsigned long end)
932 {
933         initrd_start = (unsigned long)__va(start);
934         initrd_end = (unsigned long)__va(end);
935         initrd_below_start_ok = 1;
936 }
937 #endif
938
939 /**
940  * early_init_dt_check_for_initrd - Decode initrd location from flat tree
941  * @node: reference to node containing initrd location ('chosen')
942  */
943 static void __init early_init_dt_check_for_initrd(unsigned long node)
944 {
945         u64 start, end;
946         int len;
947         const __be32 *prop;
948
949         pr_debug("Looking for initrd properties... ");
950
951         prop = of_get_flat_dt_prop(node, "linux,initrd-start", &len);
952         if (!prop)
953                 return;
954         start = of_read_number(prop, len/4);
955
956         prop = of_get_flat_dt_prop(node, "linux,initrd-end", &len);
957         if (!prop)
958                 return;
959         end = of_read_number(prop, len/4);
960
961         __early_init_dt_declare_initrd(start, end);
962
963         pr_debug("initrd_start=0x%llx  initrd_end=0x%llx\n",
964                  (unsigned long long)start, (unsigned long long)end);
965 }
966 #else
967 static inline void early_init_dt_check_for_initrd(unsigned long node)
968 {
969 }
970 #endif /* CONFIG_BLK_DEV_INITRD */
971
972 #ifdef CONFIG_SERIAL_EARLYCON
973
974 int __init early_init_dt_scan_chosen_stdout(void)
975 {
976         int offset;
977         const char *p, *q, *options = NULL;
978         int l;
979         const struct earlycon_id **p_match;
980         const void *fdt = initial_boot_params;
981
982         offset = fdt_path_offset(fdt, "/chosen");
983         if (offset < 0)
984                 offset = fdt_path_offset(fdt, "/chosen@0");
985         if (offset < 0)
986                 return -ENOENT;
987
988         p = fdt_getprop(fdt, offset, "stdout-path", &l);
989         if (!p)
990                 p = fdt_getprop(fdt, offset, "linux,stdout-path", &l);
991         if (!p || !l)
992                 return -ENOENT;
993
994         q = strchrnul(p, ':');
995         if (*q != '\0')
996                 options = q + 1;
997         l = q - p;
998
999         /* Get the node specified by stdout-path */
1000         offset = fdt_path_offset_namelen(fdt, p, l);
1001         if (offset < 0) {
1002                 pr_warn("earlycon: stdout-path %.*s not found\n", l, p);
1003                 return 0;
1004         }
1005
1006         for (p_match = __earlycon_table; p_match < __earlycon_table_end;
1007              p_match++) {
1008                 const struct earlycon_id *match = *p_match;
1009
1010                 if (!match->compatible[0])
1011                         continue;
1012
1013                 if (fdt_node_check_compatible(fdt, offset, match->compatible))
1014                         continue;
1015
1016                 of_setup_earlycon(match, offset, options);
1017                 return 0;
1018         }
1019         return -ENODEV;
1020 }
1021 #endif
1022
1023 /**
1024  * early_init_dt_scan_root - fetch the top level address and size cells
1025  */
1026 int __init early_init_dt_scan_root(unsigned long node, const char *uname,
1027                                    int depth, void *data)
1028 {
1029         const __be32 *prop;
1030
1031         if (depth != 0)
1032                 return 0;
1033
1034         dt_root_size_cells = OF_ROOT_NODE_SIZE_CELLS_DEFAULT;
1035         dt_root_addr_cells = OF_ROOT_NODE_ADDR_CELLS_DEFAULT;
1036
1037         prop = of_get_flat_dt_prop(node, "#size-cells", NULL);
1038         if (prop)
1039                 dt_root_size_cells = be32_to_cpup(prop);
1040         pr_debug("dt_root_size_cells = %x\n", dt_root_size_cells);
1041
1042         prop = of_get_flat_dt_prop(node, "#address-cells", NULL);
1043         if (prop)
1044                 dt_root_addr_cells = be32_to_cpup(prop);
1045         pr_debug("dt_root_addr_cells = %x\n", dt_root_addr_cells);
1046
1047         /* break now */
1048         return 1;
1049 }
1050
1051 u64 __init dt_mem_next_cell(int s, const __be32 **cellp)
1052 {
1053         const __be32 *p = *cellp;
1054
1055         *cellp = p + s;
1056         return of_read_number(p, s);
1057 }
1058
1059 /**
1060  * early_init_dt_scan_memory - Look for and parse memory nodes
1061  */
1062 int __init early_init_dt_scan_memory(unsigned long node, const char *uname,
1063                                      int depth, void *data)
1064 {
1065         const char *type = of_get_flat_dt_prop(node, "device_type", NULL);
1066         const __be32 *reg, *endp;
1067         int l;
1068         bool hotpluggable;
1069
1070         /* We are scanning "memory" nodes only */
1071         if (type == NULL) {
1072                 /*
1073                  * The longtrail doesn't have a device_type on the
1074                  * /memory node, so look for the node called /memory@0.
1075                  */
1076                 if (!IS_ENABLED(CONFIG_PPC32) || depth != 1 || strcmp(uname, "memory@0") != 0)
1077                         return 0;
1078         } else if (strcmp(type, "memory") != 0)
1079                 return 0;
1080
1081         reg = of_get_flat_dt_prop(node, "linux,usable-memory", &l);
1082         if (reg == NULL)
1083                 reg = of_get_flat_dt_prop(node, "reg", &l);
1084         if (reg == NULL)
1085                 return 0;
1086
1087         endp = reg + (l / sizeof(__be32));
1088         hotpluggable = of_get_flat_dt_prop(node, "hotpluggable", NULL);
1089
1090         pr_debug("memory scan node %s, reg size %d,\n", uname, l);
1091
1092         while ((endp - reg) >= (dt_root_addr_cells + dt_root_size_cells)) {
1093                 u64 base, size;
1094
1095                 base = dt_mem_next_cell(dt_root_addr_cells, &reg);
1096                 size = dt_mem_next_cell(dt_root_size_cells, &reg);
1097
1098                 if (size == 0)
1099                         continue;
1100                 pr_debug(" - %llx ,  %llx\n", (unsigned long long)base,
1101                     (unsigned long long)size);
1102
1103                 early_init_dt_add_memory_arch(base, size);
1104
1105                 if (!hotpluggable)
1106                         continue;
1107
1108                 if (early_init_dt_mark_hotplug_memory_arch(base, size))
1109                         pr_warn("failed to mark hotplug range 0x%llx - 0x%llx\n",
1110                                 base, base + size);
1111         }
1112
1113         return 0;
1114 }
1115
1116 int __init early_init_dt_scan_chosen(unsigned long node, const char *uname,
1117                                      int depth, void *data)
1118 {
1119         int l;
1120         const char *p;
1121         const void *rng_seed;
1122
1123         pr_debug("search \"chosen\", depth: %d, uname: %s\n", depth, uname);
1124
1125         if (depth != 1 || !data ||
1126             (strcmp(uname, "chosen") != 0 && strcmp(uname, "chosen@0") != 0))
1127                 return 0;
1128
1129         early_init_dt_check_for_initrd(node);
1130
1131         /* Retrieve command line */
1132         p = of_get_flat_dt_prop(node, "bootargs", &l);
1133         if (p != NULL && l > 0)
1134                 strlcpy(data, p, min((int)l, COMMAND_LINE_SIZE));
1135
1136         /*
1137          * CONFIG_CMDLINE is meant to be a default in case nothing else
1138          * managed to set the command line, unless CONFIG_CMDLINE_FORCE
1139          * is set in which case we override whatever was found earlier.
1140          */
1141 #ifdef CONFIG_CMDLINE
1142 #if defined(CONFIG_CMDLINE_EXTEND)
1143         strlcat(data, " ", COMMAND_LINE_SIZE);
1144         strlcat(data, CONFIG_CMDLINE, COMMAND_LINE_SIZE);
1145 #elif defined(CONFIG_CMDLINE_FORCE)
1146         strlcpy(data, CONFIG_CMDLINE, COMMAND_LINE_SIZE);
1147 #else
1148         /* No arguments from boot loader, use kernel's  cmdl*/
1149         if (!((char *)data)[0])
1150                 strlcpy(data, CONFIG_CMDLINE, COMMAND_LINE_SIZE);
1151 #endif
1152 #endif /* CONFIG_CMDLINE */
1153
1154         pr_debug("Command line is: %s\n", (char*)data);
1155
1156         rng_seed = of_get_flat_dt_prop(node, "rng-seed", &l);
1157         if (rng_seed && l > 0) {
1158                 add_bootloader_randomness(rng_seed, l);
1159
1160                 /* try to clear seed so it won't be found. */
1161                 fdt_nop_property(initial_boot_params, node, "rng-seed");
1162
1163                 /* update CRC check value */
1164                 of_fdt_crc32 = crc32_be(~0, initial_boot_params,
1165                                 fdt_totalsize(initial_boot_params));
1166         }
1167
1168         /* break now */
1169         return 1;
1170 }
1171
1172 #ifdef CONFIG_HAVE_MEMBLOCK
1173 #ifndef MIN_MEMBLOCK_ADDR
1174 #define MIN_MEMBLOCK_ADDR       __pa(PAGE_OFFSET)
1175 #endif
1176 #ifndef MAX_MEMBLOCK_ADDR
1177 #define MAX_MEMBLOCK_ADDR       ((phys_addr_t)~0)
1178 #endif
1179
1180 void __init __weak early_init_dt_add_memory_arch(u64 base, u64 size)
1181 {
1182         const u64 phys_offset = MIN_MEMBLOCK_ADDR;
1183
1184         if (!PAGE_ALIGNED(base)) {
1185                 if (size < PAGE_SIZE - (base & ~PAGE_MASK)) {
1186                         pr_warn("Ignoring memory block 0x%llx - 0x%llx\n",
1187                                 base, base + size);
1188                         return;
1189                 }
1190                 size -= PAGE_SIZE - (base & ~PAGE_MASK);
1191                 base = PAGE_ALIGN(base);
1192         }
1193         size &= PAGE_MASK;
1194
1195         if (base > MAX_MEMBLOCK_ADDR) {
1196                 pr_warning("Ignoring memory block 0x%llx - 0x%llx\n",
1197                                 base, base + size);
1198                 return;
1199         }
1200
1201         if (base + size - 1 > MAX_MEMBLOCK_ADDR) {
1202                 pr_warning("Ignoring memory range 0x%llx - 0x%llx\n",
1203                                 ((u64)MAX_MEMBLOCK_ADDR) + 1, base + size);
1204                 size = MAX_MEMBLOCK_ADDR - base + 1;
1205         }
1206
1207         if (base + size < phys_offset) {
1208                 pr_warning("Ignoring memory block 0x%llx - 0x%llx\n",
1209                            base, base + size);
1210                 return;
1211         }
1212         if (base < phys_offset) {
1213                 pr_warning("Ignoring memory range 0x%llx - 0x%llx\n",
1214                            base, phys_offset);
1215                 size -= phys_offset - base;
1216                 base = phys_offset;
1217         }
1218         memblock_add(base, size);
1219 }
1220
1221 int __init __weak early_init_dt_mark_hotplug_memory_arch(u64 base, u64 size)
1222 {
1223         return memblock_mark_hotplug(base, size);
1224 }
1225
1226 int __init __weak early_init_dt_reserve_memory_arch(phys_addr_t base,
1227                                         phys_addr_t size, bool nomap)
1228 {
1229         if (nomap)
1230                 return memblock_remove(base, size);
1231         return memblock_reserve(base, size);
1232 }
1233
1234 /*
1235  * called from unflatten_device_tree() to bootstrap devicetree itself
1236  * Architectures can override this definition if memblock isn't used
1237  */
1238 void * __init __weak early_init_dt_alloc_memory_arch(u64 size, u64 align)
1239 {
1240         return __va(memblock_alloc(size, align));
1241 }
1242 #else
1243 void __init __weak early_init_dt_add_memory_arch(u64 base, u64 size)
1244 {
1245         WARN_ON(1);
1246 }
1247
1248 int __init __weak early_init_dt_mark_hotplug_memory_arch(u64 base, u64 size)
1249 {
1250         return -ENOSYS;
1251 }
1252
1253 int __init __weak early_init_dt_reserve_memory_arch(phys_addr_t base,
1254                                         phys_addr_t size, bool nomap)
1255 {
1256         pr_err("Reserved memory not supported, ignoring range %pa - %pa%s\n",
1257                   &base, &size, nomap ? " (nomap)" : "");
1258         return -ENOSYS;
1259 }
1260
1261 void * __init __weak early_init_dt_alloc_memory_arch(u64 size, u64 align)
1262 {
1263         WARN_ON(1);
1264         return NULL;
1265 }
1266 #endif
1267
1268 bool __init early_init_dt_verify(void *params)
1269 {
1270         if (!params)
1271                 return false;
1272
1273         /* check device tree validity */
1274         if (fdt_check_header(params))
1275                 return false;
1276
1277         /* Setup flat device-tree pointer */
1278         initial_boot_params = params;
1279         of_fdt_crc32 = crc32_be(~0, initial_boot_params,
1280                                 fdt_totalsize(initial_boot_params));
1281         return true;
1282 }
1283
1284
1285 void __init early_init_dt_scan_nodes(void)
1286 {
1287         /* Retrieve various information from the /chosen node */
1288         of_scan_flat_dt(early_init_dt_scan_chosen, boot_command_line);
1289
1290         /* Initialize {size,address}-cells info */
1291         of_scan_flat_dt(early_init_dt_scan_root, NULL);
1292
1293         /* Setup memory, calling early_init_dt_add_memory_arch */
1294         of_scan_flat_dt(early_init_dt_scan_memory, NULL);
1295 }
1296
1297 bool __init early_init_dt_scan(void *params)
1298 {
1299         bool status;
1300
1301         status = early_init_dt_verify(params);
1302         if (!status)
1303                 return false;
1304
1305         early_init_dt_scan_nodes();
1306         return true;
1307 }
1308
1309 /**
1310  * unflatten_device_tree - create tree of device_nodes from flat blob
1311  *
1312  * unflattens the device-tree passed by the firmware, creating the
1313  * tree of struct device_node. It also fills the "name" and "type"
1314  * pointers of the nodes so the normal device-tree walking functions
1315  * can be used.
1316  */
1317 void __init unflatten_device_tree(void)
1318 {
1319         __unflatten_device_tree(initial_boot_params, NULL, &of_root,
1320                                 early_init_dt_alloc_memory_arch, false);
1321
1322         /* Get pointer to "/chosen" and "/aliases" nodes for use everywhere */
1323         of_alias_scan(early_init_dt_alloc_memory_arch);
1324
1325         unittest_unflatten_overlay_base();
1326 }
1327
1328 /**
1329  * unflatten_and_copy_device_tree - copy and create tree of device_nodes from flat blob
1330  *
1331  * Copies and unflattens the device-tree passed by the firmware, creating the
1332  * tree of struct device_node. It also fills the "name" and "type"
1333  * pointers of the nodes so the normal device-tree walking functions
1334  * can be used. This should only be used when the FDT memory has not been
1335  * reserved such is the case when the FDT is built-in to the kernel init
1336  * section. If the FDT memory is reserved already then unflatten_device_tree
1337  * should be used instead.
1338  */
1339 void __init unflatten_and_copy_device_tree(void)
1340 {
1341         int size;
1342         void *dt;
1343
1344         if (!initial_boot_params) {
1345                 pr_warn("No valid device tree found, continuing without\n");
1346                 return;
1347         }
1348
1349         size = fdt_totalsize(initial_boot_params);
1350         dt = early_init_dt_alloc_memory_arch(size,
1351                                              roundup_pow_of_two(FDT_V17_SIZE));
1352
1353         if (dt) {
1354                 memcpy(dt, initial_boot_params, size);
1355                 initial_boot_params = dt;
1356         }
1357         unflatten_device_tree();
1358 }
1359
1360 #ifdef CONFIG_SYSFS
1361 static ssize_t of_fdt_raw_read(struct file *filp, struct kobject *kobj,
1362                                struct bin_attribute *bin_attr,
1363                                char *buf, loff_t off, size_t count)
1364 {
1365         memcpy(buf, initial_boot_params + off, count);
1366         return count;
1367 }
1368
1369 static int __init of_fdt_raw_init(void)
1370 {
1371         static struct bin_attribute of_fdt_raw_attr =
1372                 __BIN_ATTR(fdt, S_IRUSR, of_fdt_raw_read, NULL, 0);
1373
1374         if (!initial_boot_params)
1375                 return 0;
1376
1377         if (of_fdt_crc32 != crc32_be(~0, initial_boot_params,
1378                                      fdt_totalsize(initial_boot_params))) {
1379                 pr_warn("not creating '/sys/firmware/fdt': CRC check failed\n");
1380                 return 0;
1381         }
1382         of_fdt_raw_attr.size = fdt_totalsize(initial_boot_params);
1383         return sysfs_create_bin_file(firmware_kobj, &of_fdt_raw_attr);
1384 }
1385 late_initcall(of_fdt_raw_init);
1386 #endif
1387
1388 #endif /* CONFIG_OF_EARLY_FLATTREE */