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