xref: /rk3399_rockchip-uboot/arch/arm/mach-rockchip/board.c (revision c95f09d3e8643ebcae3e4e2b9beccfa10acd1c0c)
1 /*
2  * (C) Copyright 2017 Rockchip Electronics Co., Ltd.
3  *
4  * SPDX-License-Identifier:     GPL-2.0+
5  */
6 
7 #include <common.h>
8 #include <version.h>
9 #include <abuf.h>
10 #include <amp.h>
11 #include <android_ab.h>
12 #include <android_bootloader.h>
13 #include <android_image.h>
14 #include <bidram.h>
15 #include <boot_rkimg.h>
16 #include <cli.h>
17 #include <clk.h>
18 #include <console.h>
19 #include <debug_uart.h>
20 #include <dm.h>
21 #include <dvfs.h>
22 #include <fdt_support.h>
23 #include <io-domain.h>
24 #include <image.h>
25 #include <key.h>
26 #include <memblk.h>
27 #include <misc.h>
28 #include <of_live.h>
29 #include <mtd_blk.h>
30 #include <ram.h>
31 #include <rng.h>
32 #include <rockchip_debugger.h>
33 #include <syscon.h>
34 #include <sysmem.h>
35 #include <video_rockchip.h>
36 #include <xbc.h>
37 #include <asm/io.h>
38 #include <asm/gpio.h>
39 #include <android_avb/rk_avb_ops_user.h>
40 #include <dm/uclass-internal.h>
41 #include <dm/root.h>
42 #include <power/charge_display.h>
43 #include <power/regulator.h>
44 #include <optee_include/OpteeClientInterface.h>
45 #include <optee_include/OpteeClientApiLib.h>
46 #include <optee_include/tee_api_defines.h>
47 #include <asm/arch/boot_mode.h>
48 #include <asm/arch/clock.h>
49 #include <asm/arch/cpu.h>
50 #include <asm/arch/hotkey.h>
51 #include <asm/arch/param.h>
52 #include <asm/arch/periph.h>
53 #include <asm/arch/resource_img.h>
54 #include <asm/arch/rk_atags.h>
55 #include <asm/arch/vendor.h>
56 #ifdef CONFIG_ROCKCHIP_EINK_DISPLAY
57 #include <rk_eink.h>
58 #endif
59 #ifdef CONFIG_ROCKCHIP_MINIDUMP
60 #include <rk_mini_dump.h>
61 #endif
62 
63 #ifdef CONFIG_ARM64
64 static ulong orig_images_ep;
65 #endif
66 
67 __weak int rk_board_late_init(void)
68 {
69 	return 0;
70 }
71 
72 __weak int rk_board_fdt_fixup(void *blob)
73 {
74 	return 0;
75 }
76 
77 __weak int rk_board_dm_fdt_fixup(void *blob)
78 {
79 	return 0;
80 }
81 
82 __weak int soc_clk_dump(void)
83 {
84 	return 0;
85 }
86 
87 __weak int set_armclk_rate(void)
88 {
89 	return 0;
90 }
91 
92 __weak int rk_board_init(void)
93 {
94 	return 0;
95 }
96 
97 #ifdef CONFIG_ROCKCHIP_SET_ETHADDR
98 /*
99  * define serialno max length, the max length is 512 Bytes
100  * The remaining bytes are used to ensure that the first 512 bytes
101  * are valid when executing 'env_set("serial#", value)'.
102  */
103 #define VENDOR_SN_MAX	513
104 #define CPUID_LEN	0x10
105 
106 #define MAX_ETHERNET	0x2
107 
108 static int rockchip_set_ethaddr(void)
109 {
110 	__maybe_unused bool need_write = false;
111 	bool randomed = false;
112 	char buf[ARP_HLEN_ASCII + 1], mac[16];
113 	u8 ethaddr[ARP_HLEN * MAX_ETHERNET] = {0};
114 	int i, ret = -EINVAL;
115 
116 #ifdef CONFIG_ROCKCHIP_VENDOR_PARTITION
117 	ret = vendor_storage_read(LAN_MAC_ID, ethaddr, sizeof(ethaddr));
118 #endif
119 	for (i = 0; i < MAX_ETHERNET; i++) {
120 		if (ret <= 0 || !is_valid_ethaddr(&ethaddr[i * ARP_HLEN])) {
121 			if (!randomed) {
122 				net_random_ethaddr(&ethaddr[i * ARP_HLEN]);
123 				randomed = true;
124 			} else {
125 				if (i > 0) {
126 					memcpy(&ethaddr[i * ARP_HLEN],
127 					       &ethaddr[(i - 1) * ARP_HLEN],
128 					       ARP_HLEN);
129 					ethaddr[i * ARP_HLEN] |= 0x02;
130 					ethaddr[i * ARP_HLEN] += (i << 2);
131 				}
132 			}
133 
134 			need_write = true;
135 		}
136 
137 		if (is_valid_ethaddr(&ethaddr[i * ARP_HLEN])) {
138 			snprintf(buf, ARP_HLEN_ASCII + 1, "%pM", &ethaddr[i * ARP_HLEN]);
139 			if (i == 0)
140 				memcpy(mac, "ethaddr", sizeof("ethaddr"));
141 			else
142 				sprintf(mac, "eth%daddr", i);
143 			env_set(mac, buf);
144 		}
145 	}
146 
147 #ifdef CONFIG_ROCKCHIP_VENDOR_PARTITION
148 	if (need_write) {
149 		ret = vendor_storage_write(LAN_MAC_ID,
150 					   ethaddr, sizeof(ethaddr));
151 		if (ret < 0)
152 			printf("%s: vendor_storage_write failed %d\n",
153 			       __func__, ret);
154 	}
155 #endif
156 	return 0;
157 }
158 #endif
159 
160 #ifdef CONFIG_ROCKCHIP_SET_SN
161 static int rockchip_set_serialno(void)
162 {
163 	u8 low[CPUID_LEN / 2], high[CPUID_LEN / 2];
164 	u8 cpuid[CPUID_LEN] = {0};
165 	char serialno_str[VENDOR_SN_MAX];
166 	int ret = 0, i;
167 	u64 serialno;
168 
169 	/* Read serial number from vendor storage part */
170 	memset(serialno_str, 0, VENDOR_SN_MAX);
171 
172 #ifdef CONFIG_ROCKCHIP_VENDOR_PARTITION
173 	int j;
174 
175 	ret = vendor_storage_read(SN_ID, serialno_str, (VENDOR_SN_MAX-1));
176 	if (ret > 0) {
177 		j = strlen(serialno_str);
178 		for (i = 0; i < j; i++) {
179 			if ((serialno_str[i] >= 'a' && serialno_str[i] <= 'z') ||
180 			    (serialno_str[i] >= 'A' && serialno_str[i] <= 'Z') ||
181 			    (serialno_str[i] >= '0' && serialno_str[i] <= '9')) {
182 				continue;
183 			} else {
184 				if (i > 0)
185 					serialno_str[i] = 0x0;
186 				break;
187 			}
188 		}
189 
190 		/* valid character count > 0 */
191 		if (i > 0) {
192 			serialno_str[i + 1] = 0x0;
193 			env_set("serial#", serialno_str);
194 		}
195 	}
196 #endif
197 	if (!env_get("serial#")) {
198 #if defined(CONFIG_ROCKCHIP_EFUSE) || defined(CONFIG_ROCKCHIP_OTP)
199 		struct udevice *dev;
200 
201 		/* retrieve the device */
202 		if (IS_ENABLED(CONFIG_ROCKCHIP_EFUSE))
203 			ret = uclass_get_device_by_driver(UCLASS_MISC,
204 							  DM_GET_DRIVER(rockchip_efuse),
205 							  &dev);
206 		else
207 			ret = uclass_get_device_by_driver(UCLASS_MISC,
208 							  DM_GET_DRIVER(rockchip_otp),
209 							  &dev);
210 
211 		if (ret) {
212 			printf("%s: could not find efuse/otp device\n", __func__);
213 			return ret;
214 		}
215 
216 		/* read the cpu_id range from the efuses */
217 		ret = misc_read(dev, CFG_CPUID_OFFSET, &cpuid, sizeof(cpuid));
218 		if (ret) {
219 			printf("%s: read cpuid from efuse/otp failed, ret=%d\n",
220 			       __func__, ret);
221 			return ret;
222 		}
223 #else
224 		/* generate random cpuid */
225 		for (i = 0; i < CPUID_LEN; i++)
226 			cpuid[i] = (u8)(rand());
227 #endif
228 		/* Generate the serial number based on CPU ID */
229 		for (i = 0; i < 8; i++) {
230 			low[i] = cpuid[1 + (i << 1)];
231 			high[i] = cpuid[i << 1];
232 		}
233 
234 		serialno = crc32_no_comp(0, low, 8);
235 		serialno |= (u64)crc32_no_comp(serialno, high, 8) << 32;
236 		snprintf(serialno_str, sizeof(serialno_str), "%llx", serialno);
237 
238 		env_set("serial#", serialno_str);
239 	}
240 
241 	return ret;
242 }
243 #endif
244 
245 #if defined(CONFIG_USB_FUNCTION_FASTBOOT)
246 int fb_set_reboot_flag(void)
247 {
248 	printf("Setting reboot to fastboot flag ...\n");
249 	writel(BOOT_FASTBOOT, CONFIG_ROCKCHIP_BOOT_MODE_REG);
250 
251 	return 0;
252 }
253 #endif
254 
255 #ifdef CONFIG_ROCKCHIP_USB_BOOT
256 static int boot_from_udisk(void)
257 {
258 	struct blk_desc *desc;
259 	struct udevice *dev;
260 	void *fdt_addr;
261 	u32 fdt_size;
262 	int devnum = -1;
263 	char buf[32];
264 
265 	/* Booting priority: mmc1 > udisk */
266 	if (!strcmp(env_get("devtype"), "mmc") && !strcmp(env_get("devnum"), "1"))
267 		return 0;
268 
269 	if (!run_command("usb start", -1)) {
270 		for (blk_first_device(IF_TYPE_USB, &dev);
271 		     dev;
272 		     blk_next_device(&dev)) {
273 			desc = dev_get_uclass_platdata(dev);
274 			printf("Scanning usb %d ...\n", desc->devnum);
275 			if (desc->type == DEV_TYPE_UNKNOWN)
276 				continue;
277 
278 			if (desc->lba > 0L && desc->blksz > 0L) {
279 				devnum = desc->devnum;
280 				break;
281 			}
282 		}
283 		if (devnum < 0) {
284 			printf("No usb mass storage found\n");
285 			return -ENODEV;
286 		}
287 
288 		desc = blk_get_devnum_by_type(IF_TYPE_USB, devnum);
289 		if (!desc) {
290 			printf("No usb %d found\n", devnum);
291 			return -ENODEV;
292 		}
293 
294 		snprintf(buf, 32, "rkimgtest usb %d", devnum);
295 		if (!run_command(buf, -1)) {
296 			snprintf(buf, 32, "%d", devnum);
297 			rockchip_set_bootdev(desc);
298 			env_set("devtype", "usb");
299 			env_set("devnum", buf);
300 			printf("=== Booting from usb %d ===\n", devnum);
301 
302 			/*
303 			 * If current kernel dtb is not from embedded dtb:
304 			 *
305 			 * Use 'gd->fdt_blob_kern' to reload the kernel dtb
306 			 * from current bootdev(udisk) in the late bootflow.
307 			 */
308 			if (!gd->fdt_blob_kern) {
309 				fdt_size = fdt_totalsize(gd->fdt_blob);
310 				fdt_addr = memalign(ARCH_DMA_MINALIGN, fdt_size);
311 				if (!fdt_addr)
312 					return -ENOMEM;
313 
314 				/* destroy kernel dtb and resource list */
315 				memcpy(fdt_addr, gd->fdt_blob, fdt_size);
316 				fdt_set_magic((void *)gd->fdt_blob, ~0);
317 				sysmem_free((phys_addr_t)gd->fdt_blob);
318 				resource_destroy();
319 
320 				gd->fdt_blob_kern = fdt_addr;
321 				gd->fdt_blob = fdt_addr;
322 			}
323 		} else {
324 			printf("No available udisk image on usb %d\n", devnum);
325 			return -ENODEV;
326 		}
327 	}
328 
329 	return 0;
330 }
331 #endif
332 
333 static void env_fixup(void)
334 {
335 	struct memblock mem;
336 	ulong u_addr_r;
337 	phys_size_t end;
338 	char *addr_r;
339 
340 #ifdef ENV_MEM_LAYOUT_SETTINGS1
341 	const char *env_addr0[] = {
342 		"scriptaddr", "pxefile_addr_r",
343 		"fdt_addr_r", "kernel_addr_r", "kernel_addr_c", "ramdisk_addr_r",
344 	};
345 	const char *env_addr1[] = {
346 		"scriptaddr1", "pxefile_addr1_r",
347 		"fdt_addr1_r", "kernel_addr1_r", "kernel_addr1_c", "ramdisk_addr1_r",
348 	};
349 	int i;
350 
351 	/* 128M is a typical ram size for most platform, so as default here */
352 	if (gd->ram_size <= SZ_128M) {
353 		/* Replace orignal xxx_addr_r */
354 		for (i = 0; i < ARRAY_SIZE(env_addr1); i++) {
355 			addr_r = env_get(env_addr1[i]);
356 			if (addr_r)
357 				env_set(env_addr0[i], addr_r);
358 		}
359 	}
360 #endif
361 	/* No BL32 ? */
362 	if (!(gd->flags & GD_FLG_BL32_ENABLED)) {
363 		/*
364 		 * [1] Move kernel to lower address if possible.
365 		 */
366 		addr_r = env_get("kernel_addr_no_low_bl32_r");
367 		if (addr_r)
368 			env_set("kernel_addr_r", addr_r);
369 
370 		/*
371 		 * [2] Move ramdisk at BL32 position if need.
372 		 *
373 		 * 0x0a200000 and 0x08400000 are rockchip traditional address
374 		 * of BL32 and ramdisk:
375 		 *
376 		 * |------------|------------|
377 		 * |    BL32    |  ramdisk   |
378 		 * |------------|------------|
379 		 *
380 		 * Move ramdisk to BL32 address to fix sysmem alloc failed
381 		 * issue on the board with critical memory(ie. 256MB).
382 		 */
383 		if (gd->ram_size > SZ_128M && gd->ram_size <= SZ_256M) {
384 			u_addr_r = env_get_ulong("ramdisk_addr_r", 16, 0);
385 			if (u_addr_r == 0x0a200000)
386 				env_set("ramdisk_addr_r", "0x08400000");
387 		}
388 	} else {
389 		mem = param_parse_optee_mem();
390 
391 		/*
392 		 * [1] Move kernel forward if possible.
393 		 */
394 		if (mem.base > SZ_128M) {
395 			addr_r = env_get("kernel_addr_no_low_bl32_r");
396 			if (addr_r)
397 				env_set("kernel_addr_r", addr_r);
398 		}
399 
400 		/*
401 		 * [2] Move ramdisk backward if optee enlarge.
402 		 */
403 		end = mem.base + mem.size;
404 		u_addr_r = env_get_ulong("ramdisk_addr_r", 16, 0);
405 		if (u_addr_r >= mem.base && u_addr_r < end)
406 			env_set_hex("ramdisk_addr_r", end);
407 	}
408 }
409 
410 static void cmdline_handle(void)
411 {
412 	struct blk_desc *dev_desc;
413 	int if_type;
414 	int devnum;
415 
416 	param_parse_pubkey_fuse_programmed();
417 
418 	dev_desc = rockchip_get_bootdev();
419 	if (!dev_desc)
420 		return;
421 
422 	/*
423 	 * 1. From rk356x, the sd/udisk recovery update flag was moved from
424 	 *    IDB to Android BCB.
425 	 *
426 	 * 2. Udisk is init at the late boot_from_udisk(), but
427 	 *    rockchip_get_boot_mode() actually only read once,
428 	 *    we need to update boot mode according to udisk BCB.
429 	 */
430 	if_type = dev_desc->if_type;
431 	devnum = dev_desc->devnum;
432 	if ((if_type == IF_TYPE_MMC && devnum == 1) || (if_type == IF_TYPE_USB)) {
433 		if (get_bcb_recovery_msg() == BCB_MSG_RECOVERY_RK_FWUPDATE) {
434 			if (if_type == IF_TYPE_MMC && devnum == 1) {
435 				env_update("bootargs", "sdfwupdate");
436 			} else if (if_type == IF_TYPE_USB) {
437 				env_update("bootargs", "usbfwupdate");
438 				env_set("reboot_mode", "recovery-usb");
439 			}
440 		} else {
441 			if (if_type == IF_TYPE_USB)
442 				env_set("reboot_mode", "normal");
443 		}
444 	}
445 
446 	if (rockchip_get_boot_mode() == BOOT_MODE_QUIESCENT)
447 		env_update("bootargs", "androidboot.quiescent=1 pwm_bl.quiescent=1");
448 }
449 
450 static void scan_run_cmd(void)
451 {
452 	char *config = CONFIG_ROCKCHIP_CMD;
453 	char *cmd, *key;
454 
455 	key = strchr(config, ' ');
456 	if (!key)
457 		return;
458 
459 	cmd = strdup(config);
460 	cmd[key - config] = 0;
461 	key++;
462 
463 	if (!strcmp(key, "-")) {
464 		run_command(cmd, 0);
465 	} else {
466 #ifdef CONFIG_DM_KEY
467 		ulong map;
468 
469 		map = simple_strtoul(key, NULL, 10);
470 		if (key_is_pressed(key_read(map))) {
471 			printf("## Key<%ld> pressed... run cmd '%s'\n", map, cmd);
472 			run_command(cmd, 0);
473 		}
474 #endif
475 	}
476 }
477 
478 int board_late_init(void)
479 {
480 #ifdef CONFIG_ROCKCHIP_SET_ETHADDR
481 	rockchip_set_ethaddr();
482 #endif
483 #ifdef CONFIG_ROCKCHIP_SET_SN
484 	rockchip_set_serialno();
485 #endif
486 	setup_download_mode();
487 	scan_run_cmd();
488 #ifdef CONFIG_ROCKCHIP_USB_BOOT
489 	boot_from_udisk();
490 #endif
491 #ifdef CONFIG_DM_CHARGE_DISPLAY
492 	charge_display();
493 #endif
494 
495 #ifdef CONFIG_ROCKCHIP_MINIDUMP
496 	rk_minidump_init();
497 #endif
498 
499 #ifdef CONFIG_DRM_ROCKCHIP
500 	if ((rockchip_get_boot_mode() != BOOT_MODE_QUIESCENT) &&
501 	     !smp_event1(SEVT_3, STID_16))
502 		rockchip_show_logo();
503 #endif
504 
505 #ifdef CONFIG_ROCKCHIP_EINK_DISPLAY
506 	rockchip_eink_show_uboot_logo();
507 #endif
508 #if (CONFIG_ROCKCHIP_BOOT_MODE_REG > 0)
509 	setup_boot_mode();
510 #endif
511 	env_fixup();
512 	soc_clk_dump();
513 	cmdline_handle();
514 #ifdef CONFIG_AMP
515 	amp_cpus_on();
516 #endif
517 	return rk_board_late_init();
518 }
519 
520 static void early_download(void)
521 {
522 #if defined(CONFIG_PWRKEY_DNL_TRIGGER_NUM) && \
523 		(CONFIG_PWRKEY_DNL_TRIGGER_NUM > 0)
524 	if (pwrkey_download_init())
525 		printf("Pwrkey download init failed\n");
526 #endif
527 
528 #if (CONFIG_ROCKCHIP_BOOT_MODE_REG > 0)
529 	if (is_hotkey(HK_BROM_DNL)) {
530 		printf("Enter bootrom download...");
531 		flushc();
532 		writel(BOOT_BROM_DOWNLOAD, CONFIG_ROCKCHIP_BOOT_MODE_REG);
533 		do_reset(NULL, 0, 0, NULL);
534 		printf("failed!\n");
535 	}
536 #endif
537 }
538 
539 static void board_debug_init(void)
540 {
541 	if (!gd->serial.using_pre_serial &&
542 	    !(gd->flags & GD_FLG_DISABLE_CONSOLE))
543 		debug_uart_init();
544 
545 	if (tstc()) {
546 		gd->console_evt = getc();
547 		if (gd->console_evt <= 0x1a) /* 'z' */
548 			printf("Hotkey: ctrl+%c\n", gd->console_evt + 'a' - 1);
549 	}
550 
551 	if (IS_ENABLED(CONFIG_CONSOLE_DISABLE_CLI))
552 		printf("Cmd interface: disabled\n");
553 }
554 
555 int board_init(void)
556 {
557 	smp_event1(SEVT_0, 0);
558 
559 	board_debug_init();
560 #ifdef DEBUG
561 	soc_clk_dump();
562 #endif
563 #ifdef CONFIG_OPTEE_CLIENT
564 	optee_client_init();
565 #endif
566 #ifdef CONFIG_USING_KERNEL_DTB
567 	init_kernel_dtb();
568 #endif
569 	early_download();
570 
571 	clks_probe();
572 
573 #ifdef CONFIG_DM_REGULATOR
574 	if (smp_event1(SEVT_3, STID_18))
575 		smp_event1(SEVT_1, STID_18);
576 	else
577 		regulators_enable_boot_on(is_hotkey(HK_REGULATOR));
578 #endif
579 #ifdef CONFIG_ROCKCHIP_IO_DOMAIN
580 	io_domain_init();
581 #endif
582 	set_armclk_rate();
583 #ifdef CONFIG_DM_DVFS
584 	dvfs_init(true);
585 #endif
586 #ifdef CONFIG_ANDROID_AB
587 	if (ab_decrease_tries())
588 		printf("Decrease ab tries count fail!\n");
589 #endif
590 	return rk_board_init();
591 }
592 
593 int interrupt_debugger_init(void)
594 {
595 #ifdef CONFIG_ROCKCHIP_DEBUGGER
596 	return rockchip_debugger_init();
597 #else
598 	return 0;
599 #endif
600 }
601 
602 #ifdef CONFIG_SANITY_CPU_SWAP
603 static void sanity_cpu_swap(void *blob)
604 {
605 	int cpus_offset;
606 	int noffset;
607 	ulong mpidr;
608 	ulong reg;
609 
610 	cpus_offset = fdt_path_offset(blob, "/cpus");
611 	if (cpus_offset < 0)
612 		return;
613 
614 	for (noffset = fdt_first_subnode(blob, cpus_offset);
615 	     noffset >= 0;
616 	     noffset = fdt_next_subnode(blob, noffset)) {
617 		const struct fdt_property *prop;
618 		int len;
619 
620 		prop = fdt_get_property(blob, noffset, "device_type", &len);
621 		if (!prop)
622 			continue;
623 		if (len < 4)
624 			continue;
625 		if (strcmp(prop->data, "cpu"))
626 			continue;
627 
628 		/* only sanity first cpu */
629 		reg = (ulong)fdtdec_get_addr_size_auto_parent(blob, cpus_offset, noffset,
630                                                               "reg", 0, NULL, false);
631 		mpidr = read_mpidr() & 0xfff;
632 		if ((mpidr & reg) != reg) {
633 			printf("CPU swap error: Loader and Kernel firmware mismatch! "
634 			       "Current cpu0 \"reg\" is 0x%lx but kernel dtb requires 0x%lx\n",
635 			       mpidr, reg);
636 			run_command("download", 0);
637 		}
638 		return;
639 	}
640 }
641 #endif
642 
643 static int rockchip_dm_late_init(void *blob)
644 {
645 	struct udevice *dev;
646 
647 	/* Prepare for board_rng_seed(), dryrun and ignore result */
648 	if (IS_ENABLED(CONFIG_BOARD_RNG_SEED) && IS_ENABLED(CONFIG_DM_RNG))
649 		uclass_get_device(UCLASS_RNG, 0, &dev);
650 
651 	return 0;
652 }
653 
654 int board_fdt_fixup(void *blob)
655 {
656 #ifdef CONFIG_SANITY_CPU_SWAP
657 	sanity_cpu_swap(blob);
658 #endif
659 	/*
660 	 * Device's platdata points to orignal fdt blob property,
661 	 * access DM device before any fdt fixup.
662 	 *
663 	 * Do board specific init and common init.
664 	 */
665 	rk_board_dm_fdt_fixup(blob);
666 	rockchip_dm_late_init(blob);
667 
668 	smp_event1(SEVT_2, STID_16);
669 
670 	/* Common fixup for DRM */
671 #ifdef CONFIG_DRM_ROCKCHIP
672 	rockchip_display_fixup(blob);
673 #endif
674 
675 #ifdef CONFIG_ROCKCHIP_VENDOR_PARTITION
676 	vendor_storage_fixup(blob);
677 #endif
678 
679 	return rk_board_fdt_fixup(blob);
680 }
681 
682 #if defined(CONFIG_ARM64_BOOT_AARCH32) || !defined(CONFIG_ARM64)
683 /*
684  * Common for OP-TEE:
685  *	64-bit & 32-bit mode: share memory dcache is always enabled;
686  *
687  * Common for U-Boot:
688  *	64-bit mode: MMU table is static defined in rkxxx.c file, all memory
689  *		     regions are mapped. That's good to match OP-TEE MMU policy.
690  *
691  *	32-bit mode: MMU table is setup according to gd->bd->bi_dram[..] where
692  *		     the OP-TEE region has been reserved, so it can not be
693  *		     mapped(i.e. dcache is disabled). That's *NOT* good to match
694  *		     OP-TEE MMU policy.
695  *
696  * For the data coherence when communication between U-Boot and OP-TEE, U-Boot
697  * should follow OP-TEE MMU policy.
698  *
699  * So 32-bit mode U-Boot should map OP-TEE share memory as dcache enabled.
700  */
701 int board_initr_caches_fixup(void)
702 {
703 #ifdef CONFIG_OPTEE_CLIENT
704 	struct memblock mem;
705 
706 	mem.base = 0;
707 	mem.size = 0;
708 
709 	optee_get_shm_config(&mem.base, &mem.size);
710 	if (mem.size)
711 		mmu_set_region_dcache_behaviour(mem.base, mem.size,
712 						DCACHE_WRITEBACK);
713 #endif
714 	return 0;
715 }
716 #endif
717 
718 void arch_preboot_os(uint32_t bootm_state, bootm_headers_t *images)
719 {
720 	if (!(bootm_state & BOOTM_STATE_OS_PREP))
721 		return;
722 
723 #ifdef CONFIG_ARM64
724 	u8 *data = (void *)images->ep;
725 
726 	/*
727 	 * Fix kernel 5.10 arm64 boot warning:
728 	 * "[Firmware Bug]: Kernel image misaligned at boot, please fix your bootloader!"
729 	 *
730 	 * kernel: 5.10 commit 120dc60d0bdb ("arm64: get rid of TEXT_OFFSET")
731 	 * arm64 kernel version:
732 	 *	data[10] == 0x00 if kernel version >= 5.10: N*2MB align
733 	 *	data[10] == 0x08 if kernel version <  5.10: N*2MB + 0x80000(TEXT_OFFSET)
734 	 *
735 	 * Why fix here?
736 	 *   1. this is the common and final path for any boot command.
737 	 *   2. don't influence original boot flow, just fix it exactly before
738 	 *	jumping kernel.
739 	 *
740 	 * But relocation is in board_quiesce_devices() until all decompress
741 	 * done, mainly for saving boot time.
742 	 */
743 
744 	orig_images_ep = images->ep;
745 
746 	if (data[10] == 0x00) {
747 		if (round_down(images->ep, SZ_2M) != images->ep)
748 			images->ep = round_down(images->ep, SZ_2M);
749 	} else {
750 		if (IS_ALIGNED(images->ep, SZ_2M))
751 			images->ep += 0x80000;
752 	}
753 #endif
754 	hotkey_run(HK_CLI_OS_PRE);
755 }
756 
757 void enable_caches(void)
758 {
759 	icache_enable();
760 	dcache_enable();
761 }
762 
763 #ifdef CONFIG_LMB
764 /*
765  * Using last bi_dram[...] to initialize "bootm_low" and "bootm_mapsize".
766  * This makes lmb_alloc_base() always alloc from tail of sdram.
767  * If we don't assign it, bi_dram[0] is used by default and it may cause
768  * lmb_alloc_base() fail when bi_dram[0] range is small.
769  */
770 void board_lmb_reserve(struct lmb *lmb)
771 {
772 	char bootm_mapsize[32];
773 	char bootm_low[32];
774 	u64 start, size;
775 	int i;
776 
777 	for (i = 0; i < CONFIG_NR_DRAM_BANKS; i++) {
778 		if (!gd->bd->bi_dram[i].size)
779 			break;
780 	}
781 
782 	start = gd->bd->bi_dram[i - 1].start;
783 	size = gd->bd->bi_dram[i - 1].size;
784 
785 	/*
786 	 * 32-bit kernel: ramdisk/fdt shouldn't be loaded to highmem area(768MB+),
787 	 * otherwise "Unable to handle kernel paging request at virtual address ...".
788 	 *
789 	 * So that we hope limit highest address at 768M, but there comes the the
790 	 * problem: ramdisk is a compressed image and it expands after descompress,
791 	 * so it accesses 768MB+ and brings the above "Unable to handle kernel ...".
792 	 *
793 	 * We make a appointment that the highest memory address is 512MB, it
794 	 * makes lmb alloc safer.
795 	 */
796 #ifndef CONFIG_ARM64
797 	if (start >= ((u64)CONFIG_SYS_SDRAM_BASE + SZ_512M)) {
798 		start = gd->bd->bi_dram[i - 2].start;
799 		size = gd->bd->bi_dram[i - 2].size;
800 	}
801 
802 	if ((start + size) > ((u64)CONFIG_SYS_SDRAM_BASE + SZ_512M))
803 		size = (u64)CONFIG_SYS_SDRAM_BASE + SZ_512M - start;
804 #endif
805 	sprintf(bootm_low, "0x%llx", start);
806 	sprintf(bootm_mapsize, "0x%llx", size);
807 	env_set("bootm_low", bootm_low);
808 	env_set("bootm_mapsize", bootm_mapsize);
809 }
810 #endif
811 
812 #ifdef CONFIG_BIDRAM
813 int board_bidram_reserve(struct bidram *bidram)
814 {
815 	struct memblock mem;
816 	int ret;
817 
818 	/* ATF */
819 	mem = param_parse_atf_mem();
820 	ret = bidram_reserve(MEM_ATF, mem.base, mem.size);
821 	if (ret)
822 		return ret;
823 
824 	/* PSTORE/ATAGS/SHM */
825 	mem = param_parse_common_resv_mem();
826 	ret = bidram_reserve(MEM_SHM, mem.base, mem.size);
827 	if (ret)
828 		return ret;
829 
830 	/* OP-TEE */
831 	mem = param_parse_optee_mem();
832 	ret = bidram_reserve(MEM_OPTEE, mem.base, mem.size);
833 	if (ret)
834 		return ret;
835 
836 	return 0;
837 }
838 
839 #ifdef CONFIG_SYSMEM
840 int board_sysmem_reserve(struct sysmem *sysmem)
841 {
842 #ifdef CONFIG_SKIP_RELOCATE_UBOOT
843 	if (!sysmem_alloc_base_by_name("NO-RELOC-CODE",
844 	    CONFIG_SYS_TEXT_BASE, SZ_2M)) {
845 		printf("Failed to reserve sysmem for U-Boot code\n");
846 		return -ENOMEM;
847 	}
848 #endif
849 	return 0;
850 }
851 #endif
852 
853 parse_fn_t board_bidram_parse_fn(void)
854 {
855 	return param_parse_ddr_mem;
856 }
857 #endif
858 
859 int board_init_f_boot_flags(void)
860 {
861 	int boot_flags = 0;
862 
863 #ifdef CONFIG_ARM64
864 	asm volatile("mrs %0, cntfrq_el0" : "=r" (gd->arch.timer_rate_hz));
865 #else
866 	asm volatile("mrc p15, 0, %0, c14, c0, 0" : "=r" (gd->arch.timer_rate_hz));
867 #endif
868 
869 #if CONFIG_IS_ENABLED(FPGA_ROCKCHIP)
870 	arch_fpga_init();
871 #endif
872 #ifdef CONFIG_PSTORE
873 	param_parse_pstore();
874 #endif
875 	param_parse_pre_serial(&boot_flags);
876 
877 	/* The highest priority to turn off (override) console */
878 #if defined(CONFIG_DISABLE_CONSOLE)
879 	boot_flags |= GD_FLG_DISABLE_CONSOLE;
880 #endif
881 
882 	return boot_flags;
883 }
884 
885 #if defined(CONFIG_USB_GADGET)
886 #include <usb.h>
887 #if defined(CONFIG_USB_GADGET_DWC2_OTG)
888 #include <fdt_support.h>
889 #include <usb/dwc2_udc.h>
890 
891 static struct dwc2_plat_otg_data otg_data = {
892 	.rx_fifo_sz	= 512,
893 	.np_tx_fifo_sz	= 16,
894 	.tx_fifo_sz	= 128,
895 };
896 
897 int board_usb_init(int index, enum usb_init_type init)
898 {
899 	const void *blob = gd->fdt_blob;
900 	const fdt32_t *reg;
901 	fdt_addr_t addr;
902 	int node;
903 
904 	/* find the usb_otg node */
905 	node = fdt_node_offset_by_compatible(blob, -1, "snps,dwc2");
906 
907 retry:
908 	if (node > 0) {
909 		reg = fdt_getprop(blob, node, "reg", NULL);
910 		if (!reg)
911 			return -EINVAL;
912 
913 		addr = fdt_translate_address(blob, node, reg);
914 		if (addr == OF_BAD_ADDR) {
915 			pr_err("Not found usb_otg address\n");
916 			return -EINVAL;
917 		}
918 
919 #if defined(CONFIG_ROCKCHIP_RK3288)
920 		if (addr != 0xff580000) {
921 			node = fdt_node_offset_by_compatible(blob, node,
922 							     "snps,dwc2");
923 			goto retry;
924 		}
925 #endif
926 	} else {
927 		/*
928 		 * With kernel dtb support, rk3288 dwc2 otg node
929 		 * use the rockchip legacy dwc2 driver "dwc_otg_310"
930 		 * with the compatible "rockchip,rk3288_usb20_otg",
931 		 * and rk3368 also use the "dwc_otg_310" driver with
932 		 * the compatible "rockchip,rk3368-usb".
933 		 */
934 #if defined(CONFIG_ROCKCHIP_RK3288)
935 		node = fdt_node_offset_by_compatible(blob, -1,
936 				"rockchip,rk3288_usb20_otg");
937 #elif defined(CONFIG_ROCKCHIP_RK3368)
938 		node = fdt_node_offset_by_compatible(blob, -1,
939 				"rockchip,rk3368-usb");
940 #endif
941 		if (node > 0) {
942 			goto retry;
943 		} else {
944 			pr_err("Not found usb_otg device\n");
945 			return -ENODEV;
946 		}
947 	}
948 
949 	otg_data.regs_otg = (uintptr_t)addr;
950 
951 	return dwc2_udc_probe(&otg_data);
952 }
953 
954 int board_usb_cleanup(int index, enum usb_init_type init)
955 {
956 	return 0;
957 }
958 #elif defined(CONFIG_USB_DWC3_GADGET) /* CONFIG_USB_GADGET_DWC2_OTG */
959 #include <dwc3-uboot.h>
960 
961 int board_usb_cleanup(int index, enum usb_init_type init)
962 {
963 	dwc3_uboot_exit(index);
964 	return 0;
965 }
966 
967 #endif /* CONFIG_USB_DWC3_GADGET */
968 #endif /* CONFIG_USB_GADGET */
969 
970 static void bootm_no_reloc(void)
971 {
972 	char *ramdisk_high;
973 	char *fdt_high;
974 
975 	if (!env_get_yesno("bootm-no-reloc"))
976 		return;
977 
978 	ramdisk_high = env_get("initrd_high");
979 	fdt_high = env_get("fdt_high");
980 
981 	if (!fdt_high) {
982 		env_set_hex("fdt_high", -1UL);
983 		printf("Fdt ");
984 	}
985 
986 	if (!ramdisk_high) {
987 		env_set_hex("initrd_high", -1UL);
988 		printf("Ramdisk ");
989 	}
990 
991 	if (!fdt_high || !ramdisk_high)
992 		printf("skip relocation\n");
993 }
994 
995 int bootm_board_start(void)
996 {
997 	/*
998 	 * print console record data
999 	 *
1000 	 * On some rockchip platforms, uart debug and sdmmc pin are multiplex.
1001 	 * If boot from sdmmc mode, the console data would be record in buffer,
1002 	 * we switch to uart debug function in order to print it after loading
1003 	 * images.
1004 	 */
1005 #if 0
1006 	if (!strcmp("mmc", env_get("devtype")) &&
1007 	    !strcmp("1", env_get("devnum"))) {
1008 		printf("IOMUX: sdmmc => uart debug");
1009 		pinctrl_select_state(gd->cur_serial_dev, "default");
1010 		console_record_print_purge();
1011 	}
1012 #endif
1013 	/* disable bootm relcation to save boot time */
1014 	bootm_no_reloc();
1015 
1016 	/* PCBA test needs more permission */
1017 	if (get_bcb_recovery_msg() == BCB_MSG_RECOVERY_PCBA)
1018 		env_update("bootargs", "androidboot.selinux=permissive");
1019 
1020 	/* sysmem */
1021 	hotkey_run(HK_SYSMEM);
1022 	sysmem_overflow_check();
1023 
1024 	return 0;
1025 }
1026 
1027 int bootm_image_populate_dtb(void *img)
1028 {
1029 	if ((gd->flags & GD_FLG_KDTB_READY) && !gd->fdt_blob_kern)
1030 		sysmem_free((phys_addr_t)gd->fdt_blob);
1031 	else
1032 		gd->fdt_blob = (void *)env_get_ulong("fdt_addr_r", 16, 0);
1033 
1034 	return rockchip_ram_read_dtb_file(img, (void *)gd->fdt_blob);
1035 }
1036 
1037 /*
1038  * Implement it to support CLI command:
1039  *   - Android: bootm [aosp addr]
1040  *   - FIT:     bootm [fit addr]
1041  *   - uImage:  bootm [uimage addr]
1042  *
1043  * Purpose:
1044  *   - The original bootm command args require fdt addr on AOSP,
1045  *     which is not flexible on rockchip boot/recovery.img.
1046  *   - Take Android/FIT/uImage image into sysmem management to avoid image
1047  *     memory overlap.
1048  */
1049 #if defined(CONFIG_ANDROID_BOOTLOADER) ||	\
1050 	defined(CONFIG_ROCKCHIP_FIT_IMAGE) ||	\
1051 	defined(CONFIG_ROCKCHIP_UIMAGE)
1052 int board_do_bootm(int argc, char * const argv[])
1053 {
1054 	int format;
1055 	void *img;
1056 
1057 	/* only 'bootm' full image goes further */
1058 	if (argc != 2)
1059 		return 0;
1060 
1061 	img = (void *)simple_strtoul(argv[1], NULL, 16);
1062 	format = (genimg_get_format(img));
1063 
1064 	/* Android */
1065 #ifdef CONFIG_ANDROID_BOOT_IMAGE
1066 	if (format == IMAGE_FORMAT_ANDROID) {
1067 		struct andr_img_hdr *hdr;
1068 		ulong load_addr;
1069 		ulong size;
1070 		int ret;
1071 
1072 		hdr = (struct andr_img_hdr *)img;
1073 		printf("BOOTM: transferring to board Android\n");
1074 
1075 		load_addr = env_get_ulong("kernel_addr_r", 16, 0);
1076 		load_addr -= hdr->page_size;
1077 		size = android_image_get_end(hdr) - (ulong)hdr;
1078 
1079 		if (!sysmem_alloc_base(MEM_ANDROID, (ulong)hdr, size))
1080 			return -ENOMEM;
1081 
1082 		ret = bootm_image_populate_dtb(img);
1083 		if (ret) {
1084 			printf("bootm can't read dtb, ret=%d\n", ret);
1085 			return ret;
1086 		}
1087 
1088 		ret = android_image_memcpy_separate(hdr, &load_addr);
1089 		if (ret) {
1090 			printf("board do bootm failed, ret=%d\n", ret);
1091 			return ret;
1092 		}
1093 
1094 		return android_bootloader_boot_kernel(load_addr);
1095 	}
1096 #endif
1097 
1098 	/* FIT */
1099 #if IMAGE_ENABLE_FIT
1100 	if (format == IMAGE_FORMAT_FIT) {
1101 		char boot_cmd[64];
1102 		int ret;
1103 
1104 		printf("BOOTM: transferring to board FIT\n");
1105 
1106 		ret = bootm_image_populate_dtb(img);
1107 		if (ret) {
1108 			printf("bootm can't read dtb, ret=%d\n", ret);
1109 			return ret;
1110 		}
1111 		snprintf(boot_cmd, sizeof(boot_cmd), "boot_fit %s", argv[1]);
1112 		return run_command(boot_cmd, 0);
1113 	}
1114 #endif
1115 
1116 	/* uImage */
1117 #if 0
1118 #if defined(CONFIG_IMAGE_FORMAT_LEGACY)
1119 	if (format == IMAGE_FORMAT_LEGACY &&
1120 	    image_get_type(img) == IH_TYPE_MULTI) {
1121 		char boot_cmd[64];
1122 
1123 		printf("BOOTM: transferring to board uImage\n");
1124 		snprintf(boot_cmd, sizeof(boot_cmd), "boot_uimage %s", argv[1]);
1125 		return run_command(boot_cmd, 0);
1126 	}
1127 #endif
1128 #endif
1129 	return 0;
1130 }
1131 #endif
1132 
1133 void autoboot_command_fail_handle(void)
1134 {
1135 #ifdef CONFIG_ANDROID_AB
1136 	if (rk_avb_ab_have_bootable_slot() == true)
1137 		run_command("reset;", 0);
1138 	else
1139 		run_command("fastboot usb 0;", 0);
1140 #endif
1141 
1142 #ifdef CONFIG_AVB_VBMETA_PUBLIC_KEY_VALIDATE
1143 	run_command("download", 0);
1144 	run_command("fastboot usb 0;", 0);
1145 #endif
1146 
1147 }
1148 
1149 #ifdef CONFIG_FIT_ROLLBACK_PROTECT
1150 
1151 #define FIT_ROLLBACK_INDEX_LOCATION	0x66697472	/* "fitr" */
1152 
1153 int fit_read_otp_rollback_index(uint32_t fit_index, uint32_t *otp_index)
1154 {
1155 #ifdef CONFIG_OPTEE_CLIENT
1156 	u64 index;
1157 	int ret;
1158 
1159 	ret = trusty_read_rollback_index(FIT_ROLLBACK_INDEX_LOCATION, &index);
1160 	if (ret) {
1161 		if (ret != TEE_ERROR_ITEM_NOT_FOUND)
1162 			return ret;
1163 
1164 		index = 0;
1165 		printf("Initial otp index as %d\n", fit_index);
1166 	}
1167 
1168 	*otp_index = (uint32_t)index;
1169 #else
1170 	*otp_index = 0;
1171 #endif
1172 
1173 	return 0;
1174 }
1175 
1176 int fit_write_trusty_rollback_index(u32 trusty_index)
1177 {
1178 	if (!trusty_index)
1179 		return 0;
1180 #ifdef CONFIG_OPTEE_CLIENT
1181 	return trusty_write_rollback_index(FIT_ROLLBACK_INDEX_LOCATION,
1182 					   (u64)trusty_index);
1183 #else
1184 	return 0;
1185 #endif
1186 }
1187 #endif
1188 
1189 void board_quiesce_devices(void *images)
1190 {
1191 #ifdef CONFIG_ROCKCHIP_PRELOADER_ATAGS
1192 	/* Destroy atags makes next warm boot safer */
1193 	atags_destroy();
1194 #endif
1195 #ifdef CONFIG_FIT_ROLLBACK_PROTECT
1196 	int ret;
1197 
1198 	ret = fit_write_trusty_rollback_index(gd->rollback_index);
1199 	if (ret) {
1200 		panic("Failed to write fit rollback index %d, ret=%d",
1201 		      gd->rollback_index, ret);
1202 	}
1203 #endif
1204 #ifdef CONFIG_ROCKCHIP_HW_DECOMPRESS
1205 	misc_decompress_cleanup();
1206 #endif
1207 #ifdef CONFIG_ARM64
1208 	bootm_headers_t *bootm_images = (bootm_headers_t *)images;
1209 
1210 	/* relocate kernel after decompress cleanup */
1211 	if (orig_images_ep && orig_images_ep != bootm_images->ep) {
1212 		memmove((char *)bootm_images->ep, (const char *)orig_images_ep,
1213 			bootm_images->os.image_len);
1214 		printf("== DO RELOCATE == Kernel from 0x%08lx to 0x%08lx\n",
1215 		       orig_images_ep, bootm_images->ep);
1216 	}
1217 #endif
1218 	smp_event1(SEVT_0, -1);
1219 
1220 	hotkey_run(HK_CMDLINE);
1221 	hotkey_run(HK_CLI_OS_GO);
1222 #ifdef CONFIG_ROCKCHIP_REBOOT_TEST
1223 	do_reset(NULL, 0, 0, NULL);
1224 #endif
1225 }
1226 
1227 /*
1228  * Use hardware rng to seed Linux random
1229  *
1230  * 'Android_14 + GKI' requires this information.
1231  */
1232 int board_rng_seed(struct abuf *buf)
1233 {
1234 #ifdef CONFIG_DM_RNG
1235 	struct udevice *dev;
1236 #endif
1237 	size_t len = 32;
1238 	u8 *data;
1239 	int i;
1240 
1241 	data = malloc(len);
1242 	if (!data) {
1243 	        printf("Out of memory\n");
1244 	        return -ENOMEM;
1245 	}
1246 
1247 #ifdef CONFIG_DM_RNG
1248 	if (uclass_get_device(UCLASS_RNG, 0, &dev) || dm_rng_read(dev, data, len))
1249 #endif
1250 	{
1251 		printf("board seed: Pseudo\n");
1252 		for (i = 0; i < len; i++)
1253 			data[i] = (u8)rand();
1254 	}
1255 
1256 	abuf_init_set(buf, data, len);
1257 
1258 	return 0;
1259 }
1260 
1261 /*
1262  * Pass fwver when any available.
1263  */
1264 static void bootargs_add_fwver(bool verbose)
1265 {
1266 #ifdef CONFIG_ROCKCHIP_PRELOADER_ATAGS
1267 	struct tag *t;
1268 	char *list1 = NULL;
1269 	char *list2 = NULL;
1270 	char *fwver = NULL;
1271 	char *p = PLAIN_VERSION;
1272 	int i, end;
1273 
1274 	t = atags_get_tag(ATAG_FWVER);
1275 	if (t) {
1276 		list1 = calloc(1, sizeof(struct tag_fwver));
1277 		if (!list1)
1278 			return;
1279 		for (i = 0; i < FW_MAX; i++) {
1280 			if (t->u.fwver.ver[i][0] != '\0') {
1281 				strcat(list1, t->u.fwver.ver[i]);
1282 				strcat(list1, ",");
1283 			}
1284 		}
1285 	}
1286 
1287 	list2 = calloc(1, FWVER_LEN);
1288 	if (!list2)
1289 		goto out;
1290 	strcat(list2, "uboot-");
1291 	/* optional */
1292 #ifdef BUILD_TAG
1293 	strcat(list2, BUILD_TAG);
1294 	strcat(list2, "-");
1295 #endif
1296 	/* optional */
1297 	if (strcmp(PLAIN_VERSION, "2017.09")) {
1298 		strncat(list2, p + strlen("2017.09-g"), 10);
1299 		strcat(list2, "-");
1300 	}
1301 	strcat(list2, U_BOOT_DMI_DATE);
1302 
1303 	/* merge ! */
1304 	if (list1 || list2) {
1305 		fwver = calloc(1, sizeof(struct tag_fwver));
1306 		if (!fwver)
1307 			goto out;
1308 
1309 		strcat(fwver, "androidboot.fwver=");
1310 		if (list1)
1311 			strcat(fwver, list1);
1312 		if (list2) {
1313 			strcat(fwver, list2);
1314 		} else {
1315 			end = strlen(fwver) - 1;
1316 			fwver[end] = '\0'; /* omit last ',' */
1317 		}
1318 		if (verbose)
1319 			printf("## fwver: %s\n\n", fwver);
1320 		env_update("bootargs", fwver);
1321 		env_set("fwver", fwver + strlen("androidboot."));
1322 	}
1323 out:
1324 	if (list1)
1325 		free(list1);
1326 	if (list2)
1327 		free(list2);
1328 	if (fwver)
1329 		free(fwver);
1330 #endif
1331 }
1332 
1333 static void bootargs_add_android(bool verbose)
1334 {
1335 #ifdef CONFIG_ANDROID_AB
1336 	ab_update_root_partition();
1337 #endif
1338 
1339 	/* Android header v4+ need this handle */
1340 #ifdef CONFIG_ANDROID_BOOT_IMAGE
1341 	struct andr_img_hdr *hdr;
1342 	char *fwver;
1343 
1344 	hdr = (void *)env_get_ulong("android_addr_r", 16, 0);
1345 	if (hdr && !android_image_check_header(hdr) && hdr->header_version >= 4) {
1346 		if (env_update_extract_subset("bootargs", "andr_bootargs", "androidboot."))
1347 			printf("extract androidboot.xxx error\n");
1348 		if (verbose)
1349 			printf("## bootargs(android): %s\n\n", env_get("andr_bootargs"));
1350 
1351 		/* for kernel cmdline can be read */
1352 		fwver = env_get("fwver");
1353 		if (fwver) {
1354 			env_update("bootargs", fwver);
1355 			env_set("fwver", NULL);
1356 		}
1357 	}
1358 #endif
1359 }
1360 
1361 static void bootargs_add_partition(bool verbose)
1362 {
1363 #if defined(CONFIG_ENVF) || defined(CONFIG_ENV_PARTITION)
1364 	char *part_type[] = { "mtdparts", "blkdevparts" };
1365 	char *part_list;
1366 	char *env;
1367 	int id = 0;
1368 
1369 	env = env_get(part_type[id]);
1370 	if (!env)
1371 		env = env_get(part_type[++id]);
1372 	if (env) {
1373 		if (!strstr(env, part_type[id])) {
1374 			part_list = calloc(1, strlen(env) + strlen(part_type[id]) + 2);
1375 			if (part_list) {
1376 				strcat(part_list, part_type[id]);
1377 				strcat(part_list, "=");
1378 				strcat(part_list, env);
1379 			}
1380 		} else {
1381 			part_list = env;
1382 		}
1383 		env_update("bootargs", part_list);
1384 		if (verbose)
1385 			printf("## parts: %s\n\n", part_list);
1386 	}
1387 
1388 	env = env_get("sys_bootargs");
1389 	if (env) {
1390 		env_update("bootargs", env);
1391 		if (verbose)
1392 			printf("## sys_bootargs: %s\n\n", env);
1393 	}
1394 #endif
1395 
1396 #ifdef CONFIG_MTD_BLK
1397 	if (!env_get("mtdparts")) {
1398 		char *mtd_par_info = mtd_part_parse(NULL);
1399 
1400 		if (mtd_par_info) {
1401 			if (memcmp(env_get("devtype"), "mtd", 3) == 0)
1402 				env_update("bootargs", mtd_par_info);
1403 		}
1404 	}
1405 #endif
1406 }
1407 
1408 static void bootargs_add_dtb_dtbo(void *fdt, bool verbose)
1409 {
1410 	/* bootargs_ext is used when dtbo is applied. */
1411 	const char *arr_bootargs[] = { "bootargs", "bootargs_ext" };
1412 	const char *bootargs;
1413 	char *msg = "kernel";
1414 	int i, noffset;
1415 
1416 	/* find or create "/chosen" node. */
1417 	noffset = fdt_find_or_add_subnode(fdt, 0, "chosen");
1418 	if (noffset < 0)
1419 		return;
1420 
1421 	for (i = 0; i < ARRAY_SIZE(arr_bootargs); i++) {
1422 		bootargs = fdt_getprop(fdt, noffset, arr_bootargs[i], NULL);
1423 		if (!bootargs)
1424 			continue;
1425 		if (verbose)
1426 			printf("## bootargs(%s-%s): %s\n\n",
1427 			       msg, arr_bootargs[i], bootargs);
1428 		/*
1429 		 * Append kernel bootargs
1430 		 * If use AB system, delete default "root=" which route
1431 		 * to rootfs. Then the ab bootctl will choose the
1432 		 * high priority system to boot and add its UUID
1433 		 * to cmdline. The format is "roo=PARTUUID=xxxx...".
1434 		 */
1435 #ifdef CONFIG_ANDROID_AB
1436 		env_update_filter("bootargs", bootargs, "root=");
1437 #else
1438 		env_update("bootargs", bootargs);
1439 #endif
1440 	}
1441 }
1442 
1443 char *board_fdt_chosen_bootargs(void *fdt)
1444 {
1445 	int verbose = is_hotkey(HK_CMDLINE);
1446 	const char *bootargs;
1447 
1448 	/* debug */
1449 	hotkey_run(HK_INITCALL);
1450 	if (verbose)
1451 		printf("## bootargs(u-boot): %s\n\n", env_get("bootargs"));
1452 
1453 	bootargs_add_dtb_dtbo(fdt, verbose);
1454 	bootargs_add_partition(verbose);
1455 	bootargs_add_fwver(verbose);
1456 	bootargs_add_android(verbose);
1457 
1458 	/*
1459 	 * Initrd fixup: remove unused "initrd=0x...,0x...",
1460 	 * this for compatible with legacy parameter.txt
1461 	 */
1462 	env_delete("bootargs", "initrd=", 0);
1463 
1464 	/*
1465 	 * If uart is required to be disabled during
1466 	 * power on, it would be not initialized by
1467 	 * any pre-loader and U-Boot.
1468 	 *
1469 	 * If we don't remove earlycon from commandline,
1470 	 * kernel hangs while using earlycon to putc/getc
1471 	 * which may dead loop for waiting uart status.
1472 	 * (It seems the root cause is baundrate is not
1473 	 * initilalized)
1474 	 *
1475 	 * So let's remove earlycon from commandline.
1476 	 */
1477 	if (gd->flags & GD_FLG_DISABLE_CONSOLE)
1478 		env_delete("bootargs", "earlycon=", 0);
1479 
1480 	bootargs = env_get("bootargs");
1481 	if (verbose)
1482 		printf("## bootargs(merged): %s\n\n", bootargs);
1483 
1484 	return (char *)bootargs;
1485 }
1486 
1487 int ft_verify_fdt(void *fdt)
1488 {
1489 	/* for android header v4+, we load bootparams and fixup initrd */
1490 #if defined(CONFIG_ANDROID_BOOT_IMAGE) && defined(CONFIG_XBC)
1491 	struct andr_img_hdr *hdr;
1492 	uint64_t initrd_start, initrd_end;
1493 	char *bootargs, *p;
1494 	int nodeoffset;
1495 	int is_u64, err;
1496 	u32 len;
1497 
1498 	hdr = (void *)env_get_ulong("android_addr_r", 16, 0);
1499 	if (!hdr || android_image_check_header(hdr) ||
1500 	    hdr->header_version < 4)
1501 		return 1;
1502 
1503 	bootargs = env_get("andr_bootargs");
1504 	if (!bootargs)
1505 		return 1;
1506 
1507 	/* trans character: space to new line */
1508 	p = bootargs;
1509 	while (*p++) {
1510 		if (*p == ' ')
1511 			*p = '\n';
1512 	}
1513 
1514 	debug("## andr_bootargs: %s\n", bootargs);
1515 
1516 	/*
1517 	 * add boot params right after bootconfig
1518 	 *
1519 	 * because we can get final full bootargs in board_fdt_chosen_bootargs(),
1520 	 * android_image_get_ramdisk() is early than that.
1521 	 *
1522 	 * we have to add boot params by now.
1523 	 */
1524 	len = addBootConfigParameters((char *)bootargs, strlen(bootargs),
1525 		(u64)hdr->ramdisk_addr + hdr->ramdisk_size +
1526 		hdr->vendor_ramdisk_size, hdr->vendor_bootconfig_size);
1527 	if (len < 0) {
1528 		printf("error: addBootConfigParameters\n");
1529 		return 0;
1530 	}
1531 
1532 	nodeoffset = fdt_subnode_offset(fdt, 0, "chosen");
1533 	if (nodeoffset < 0) {
1534 		printf("error: No /chosen node\n");
1535 		return 0;
1536 	}
1537 
1538 	/* fixup initrd with real value */
1539 	fdt_delprop(fdt, nodeoffset, "linux,initrd-start");
1540 	fdt_delprop(fdt, nodeoffset, "linux,initrd-end");
1541 
1542 	is_u64 = (fdt_address_cells(fdt, 0) == 2);
1543 	initrd_start = hdr->ramdisk_addr;
1544 	initrd_end = initrd_start + hdr->ramdisk_size +
1545 			hdr->vendor_ramdisk_size +
1546 			hdr->vendor_bootconfig_size + len;
1547 	err = fdt_setprop_uxx(fdt, nodeoffset, "linux,initrd-start",
1548 			      initrd_start, is_u64);
1549 	if (err < 0) {
1550 		printf("WARNING: could not set linux,initrd-start %s.\n",
1551 		       fdt_strerror(err));
1552 		return 0;
1553 	}
1554 	err = fdt_setprop_uxx(fdt, nodeoffset, "linux,initrd-end",
1555 			      initrd_end, is_u64);
1556 	if (err < 0) {
1557 		printf("WARNING: could not set linux,initrd-end %s.\n",
1558 		       fdt_strerror(err));
1559 		return 0;
1560 	}
1561 #endif
1562 	return 1;
1563 }
1564 
1565