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