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