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