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