xref: /rk3399_rockchip-uboot/common/android_bootloader.c (revision 68555ad7900c537e97b67a1c4387d93b59b08359)
1 /*
2  * Copyright (C) 2016 The Android Open Source Project
3  *
4  * SPDX-License-Identifier: BSD-2-Clause
5  */
6 
7 #include <android_bootloader.h>
8 #include <android_bootloader_message.h>
9 #include <android_avb/avb_slot_verify.h>
10 #include <android_avb/avb_ops_user.h>
11 #include <android_avb/rk_avb_ops_user.h>
12 #include <android_image.h>
13 #include <android_ab.h>
14 #include <bootm.h>
15 #include <asm/arch/hotkey.h>
16 #include <cli.h>
17 #include <common.h>
18 #include <dt_table.h>
19 #include <image-android-dt.h>
20 #include <malloc.h>
21 #include <fdt_support.h>
22 #include <fs.h>
23 #include <boot_rkimg.h>
24 #include <attestation_key.h>
25 #include <keymaster.h>
26 #include <linux/libfdt_env.h>
27 #include <optee_include/OpteeClientInterface.h>
28 #include <bidram.h>
29 #include <console.h>
30 #include <sysmem.h>
31 
32 DECLARE_GLOBAL_DATA_PTR;
33 
34 int android_bootloader_message_load(
35 	struct blk_desc *dev_desc,
36 	const disk_partition_t *part_info,
37 	struct android_bootloader_message *message)
38 {
39 	ulong message_blocks = sizeof(struct android_bootloader_message) /
40 	    part_info->blksz;
41 	if (message_blocks > part_info->size) {
42 		printf("misc partition too small.\n");
43 		return -1;
44 	}
45 
46 	if (blk_dread(dev_desc, part_info->start + android_bcb_msg_sector_offset(),
47 	     message_blocks, message) !=
48 	    message_blocks) {
49 		printf("Could not read from misc partition\n");
50 		return -1;
51 	}
52 	debug("ANDROID: Loaded BCB, %lu blocks.\n", message_blocks);
53 	return 0;
54 }
55 
56 static int android_bootloader_message_write(
57 	struct blk_desc *dev_desc,
58 	const disk_partition_t *part_info,
59 	struct android_bootloader_message *message)
60 {
61 	ulong message_blocks = sizeof(struct android_bootloader_message) /
62 	    part_info->blksz + android_bcb_msg_sector_offset();
63 
64 	if (message_blocks > part_info->size) {
65 		printf("misc partition too small.\n");
66 		return -1;
67 	}
68 
69 	if (blk_dwrite(dev_desc, part_info->start, message_blocks, message) !=
70 	    message_blocks) {
71 		printf("Could not write to misc partition\n");
72 		return -1;
73 	}
74 	debug("ANDROID: Wrote new BCB, %lu blocks.\n", message_blocks);
75 	return 0;
76 }
77 
78 static enum android_boot_mode android_bootloader_load_and_clear_mode(
79 	struct blk_desc *dev_desc,
80 	const disk_partition_t *misc_part_info)
81 {
82 	struct android_bootloader_message bcb;
83 
84 #ifdef CONFIG_FASTBOOT
85 	char *bootloader_str;
86 
87 	/* Check for message from bootloader stored in RAM from a previous boot.
88 	 */
89 	bootloader_str = (char *)CONFIG_FASTBOOT_BUF_ADDR;
90 	if (!strcmp("reboot-bootloader", bootloader_str)) {
91 		bootloader_str[0] = '\0';
92 		return ANDROID_BOOT_MODE_BOOTLOADER;
93 	}
94 #endif
95 
96 	/* Check and update the BCB message if needed. */
97 	if (android_bootloader_message_load(dev_desc, misc_part_info, &bcb) <
98 	    0) {
99 		printf("WARNING: Unable to load the BCB.\n");
100 		return ANDROID_BOOT_MODE_NORMAL;
101 	}
102 
103 	if (!strcmp("bootonce-bootloader", bcb.command)) {
104 		/* Erase the message in the BCB since this value should be used
105 		 * only once.
106 		 */
107 		memset(bcb.command, 0, sizeof(bcb.command));
108 		android_bootloader_message_write(dev_desc, misc_part_info,
109 						 &bcb);
110 		return ANDROID_BOOT_MODE_BOOTLOADER;
111 	}
112 
113 	if (!strcmp("boot-recovery", bcb.command))
114 		return ANDROID_BOOT_MODE_RECOVERY;
115 
116 	if (!strcmp("boot-fastboot", bcb.command))
117 		return ANDROID_BOOT_MODE_RECOVERY;
118 
119 	return ANDROID_BOOT_MODE_NORMAL;
120 }
121 
122 int android_bcb_write(char *cmd)
123 {
124 	struct android_bootloader_message message = {0};
125 	disk_partition_t part_info;
126 	struct blk_desc *dev_desc;
127 	int ret;
128 
129 	if (!cmd)
130 		return -ENOMEM;
131 
132 	if (strlen(cmd) >= 32)
133 		return -ENOMEM;
134 
135 	dev_desc = rockchip_get_bootdev();
136 	if (!dev_desc) {
137 		printf("%s: dev_desc is NULL!\n", __func__);
138 		return -ENODEV;
139 	}
140 
141 	ret = part_get_info_by_name(dev_desc, ANDROID_PARTITION_MISC, &part_info);
142 	if (ret < 0) {
143 		printf("%s: Could not found misc partition, just run recovery\n",
144 		       __func__);
145 		return -ENODEV;
146 	}
147 
148 	strcpy(message.command, cmd);
149 	return android_bootloader_message_write(dev_desc, &part_info, &message);
150 }
151 
152 /**
153  * Return the reboot reason string for the passed boot mode.
154  *
155  * @param mode	The Android Boot mode.
156  * @return a pointer to the reboot reason string for mode.
157  */
158 static const char *android_boot_mode_str(enum android_boot_mode mode)
159 {
160 	switch (mode) {
161 	case ANDROID_BOOT_MODE_NORMAL:
162 		return "(none)";
163 	case ANDROID_BOOT_MODE_RECOVERY:
164 		return "recovery";
165 	case ANDROID_BOOT_MODE_BOOTLOADER:
166 		return "bootloader";
167 	}
168 	return NULL;
169 }
170 
171 static int android_bootloader_boot_bootloader(void)
172 {
173 	const char *fastboot_cmd = env_get("fastbootcmd");
174 
175 	if (fastboot_cmd == NULL) {
176 		printf("fastboot_cmd is null, run default fastboot_cmd!\n");
177 		fastboot_cmd = "fastboot usb 0";
178 	}
179 
180 	return run_command(fastboot_cmd, CMD_FLAG_ENV);
181 }
182 
183 #ifdef CONFIG_SUPPORT_OEM_DTB
184 static int android_bootloader_get_fdt(const char *part_name,
185 		const char *load_file_name)
186 {
187 	struct blk_desc *dev_desc;
188 	disk_partition_t part_info;
189 	char *fdt_addr = NULL;
190 	char dev_part[3] = {0};
191 	loff_t bytes = 0;
192 	loff_t pos = 0;
193 	loff_t len_read;
194 	unsigned long addr = 0;
195 	int part_num = -1;
196 	int ret;
197 
198 	dev_desc = rockchip_get_bootdev();
199 	if (!dev_desc) {
200 		printf("%s: dev_desc is NULL!\n", __func__);
201 		return -1;
202 	}
203 
204 	part_num = part_get_info_by_name(dev_desc, part_name, &part_info);
205 	if (part_num < 0) {
206 		printf("ANDROID: Could not find partition \"%s\"\n", part_name);
207 		return -1;
208 	}
209 
210 	snprintf(dev_part, ARRAY_SIZE(dev_part), ":%x", part_num);
211 	if (fs_set_blk_dev_with_part(dev_desc, part_num))
212 		return -1;
213 
214 	fdt_addr = env_get("fdt_addr_r");
215 	if (!fdt_addr) {
216 		printf("ANDROID: No Found FDT Load Address.\n");
217 		return -1;
218 	}
219 	addr = simple_strtoul(fdt_addr, NULL, 16);
220 
221 	ret = fs_read(load_file_name, addr, pos, bytes, &len_read);
222 	if (ret < 0)
223 		return -1;
224 
225 	return 0;
226 }
227 #endif
228 
229 /*
230  *   Test on RK3308 AARCH64 mode (Cortex A35 816 MHZ) boot with eMMC:
231  *
232  *   |-------------------------------------------------------------------|
233  *   | Format    |  Size(Byte) | Ratio | Decomp time(ms) | Boot time(ms) |
234  *   |-------------------------------------------------------------------|
235  *   | Image     | 7720968     |       |                 |     488       |
236  *   |-------------------------------------------------------------------|
237  *   | Image.lz4 | 4119448     | 53%   |       59        |     455       |
238  *   |-------------------------------------------------------------------|
239  *   | Image.lzo | 3858322     | 49%   |       141       |     536       |
240  *   |-------------------------------------------------------------------|
241  *   | Image.gz  | 3529108     | 45%   |       222       |     609       |
242  *   |-------------------------------------------------------------------|
243  *   | Image.bz2 | 3295914     | 42%   |       2940      |               |
244  *   |-------------------------------------------------------------------|
245  *   | Image.lzma| 2683750     | 34%   |                 |               |
246  *   |-------------------------------------------------------------------|
247  */
248 static int sysmem_alloc_uncomp_kernel(ulong andr_hdr,
249 				      ulong uncomp_kaddr, u32 comp)
250 {
251 	struct andr_img_hdr *hdr = (struct andr_img_hdr *)andr_hdr;
252 	ulong ksize, kaddr;
253 
254 	if (comp != IH_COMP_NONE) {
255 		/* Release compressed sysmem */
256 		kaddr = env_get_hex("kernel_addr_c", 0);
257 		if (!kaddr)
258 			kaddr = env_get_hex("kernel_addr_r", 0);
259 		kaddr -= hdr->page_size;
260 		if (sysmem_free((phys_addr_t)kaddr))
261 			return -EINVAL;
262 #ifdef CONFIG_SKIP_RELOCATE_UBOOT
263 		sysmem_free(CONFIG_SYS_TEXT_BASE);
264 #endif
265 		/*
266 		 * Use smaller Ratio to get larger estimated uncompress
267 		 * kernel size.
268 		 */
269 		if (comp == IH_COMP_ZIMAGE)
270 			ksize = hdr->kernel_size * 100 / 45;
271 		else if (comp == IH_COMP_LZ4)
272 			ksize = hdr->kernel_size * 100 / 50;
273 		else if (comp == IH_COMP_LZO)
274 			ksize = hdr->kernel_size * 100 / 45;
275 		else if (comp == IH_COMP_GZIP)
276 			ksize = hdr->kernel_size * 100 / 40;
277 		else if (comp == IH_COMP_BZIP2)
278 			ksize = hdr->kernel_size * 100 / 40;
279 		else if (comp == IH_COMP_LZMA)
280 			ksize = hdr->kernel_size * 100 / 30;
281 		else
282 			ksize = hdr->kernel_size;
283 
284 		kaddr = uncomp_kaddr;
285 		ksize = ALIGN(ksize, 512);
286 		if (!sysmem_alloc_base(MEM_UNCOMP_KERNEL,
287 				       (phys_addr_t)kaddr, ksize))
288 			return -ENOMEM;
289 	}
290 
291 	return 0;
292 }
293 
294 int android_bootloader_boot_kernel(unsigned long kernel_address)
295 {
296 	char *kernel_addr_r = env_get("kernel_addr_r");
297 	char *kernel_addr_c = env_get("kernel_addr_c");
298 	char *fdt_addr = env_get("fdt_addr_r");
299 	char kernel_addr_str[12];
300 	char comp_str[32] = {0};
301 	ulong comp_type;
302 	const char *comp_name[] = {
303 		[IH_COMP_NONE]  = "IMAGE",
304 		[IH_COMP_GZIP]  = "GZIP",
305 		[IH_COMP_BZIP2] = "BZIP2",
306 		[IH_COMP_LZMA]  = "LZMA",
307 		[IH_COMP_LZO]   = "LZO",
308 		[IH_COMP_LZ4]   = "LZ4",
309 		[IH_COMP_ZIMAGE]= "ZIMAGE",
310 	};
311 	char *bootm_args[] = {
312 		kernel_addr_str, kernel_addr_str, fdt_addr, NULL };
313 
314 	comp_type = env_get_ulong("os_comp", 10, 0);
315 	sprintf(kernel_addr_str, "0x%08lx", kernel_address);
316 
317 	if (comp_type != IH_COMP_NONE) {
318 		if (comp_type == IH_COMP_ZIMAGE &&
319 		    kernel_addr_r && !kernel_addr_c) {
320 			kernel_addr_c = kernel_addr_r;
321 			kernel_addr_r = __stringify(CONFIG_SYS_SDRAM_BASE);
322 		}
323 		snprintf(comp_str, 32, "%s%s%s",
324 			 "(Uncompress to ", kernel_addr_r, ")");
325 	}
326 
327 	printf("Booting %s kernel at %s%s with fdt at %s...\n\n\n",
328 	       comp_name[comp_type],
329 	       comp_type != IH_COMP_NONE ? kernel_addr_c : kernel_addr_r,
330 	       comp_str, fdt_addr);
331 
332 	hotkey_run(HK_SYSMEM);
333 
334 	/*
335 	 * Check whether there is enough space for uncompress kernel,
336 	 * Actually, here only gives a sysmem warning message when failed
337 	 * but never return -1.
338 	 */
339 	if (sysmem_alloc_uncomp_kernel(kernel_address,
340 				       simple_strtoul(kernel_addr_r, NULL, 16),
341 				       comp_type))
342 		return -1;
343 
344 	return do_bootm_states(NULL, 0, ARRAY_SIZE(bootm_args), bootm_args,
345 		BOOTM_STATE_START |
346 		BOOTM_STATE_FINDOS | BOOTM_STATE_FINDOTHER |
347 		BOOTM_STATE_LOADOS |
348 #ifdef CONFIG_SYS_BOOT_RAMDISK_HIGH
349 		BOOTM_STATE_RAMDISK |
350 #endif
351 		BOOTM_STATE_OS_PREP | BOOTM_STATE_OS_FAKE_GO |
352 		BOOTM_STATE_OS_GO, &images, 1);
353 }
354 
355 static char *strjoin(const char **chunks, char separator)
356 {
357 	int len, joined_len = 0;
358 	char *ret, *current;
359 	const char **p;
360 
361 	for (p = chunks; *p; p++)
362 		joined_len += strlen(*p) + 1;
363 
364 	if (!joined_len) {
365 		ret = malloc(1);
366 		if (ret)
367 			ret[0] = '\0';
368 		return ret;
369 	}
370 
371 	ret = malloc(joined_len);
372 	current = ret;
373 	if (!ret)
374 		return ret;
375 
376 	for (p = chunks; *p; p++) {
377 		len = strlen(*p);
378 		memcpy(current, *p, len);
379 		current += len;
380 		*current = separator;
381 		current++;
382 	}
383 	/* Replace the last separator by a \0. */
384 	current[-1] = '\0';
385 	return ret;
386 }
387 
388 /** android_assemble_cmdline - Assemble the command line to pass to the kernel
389  * @return a newly allocated string
390  */
391 char *android_assemble_cmdline(const char *slot_suffix,
392 				      const char *extra_args)
393 {
394 	const char *cmdline_chunks[16];
395 	const char **current_chunk = cmdline_chunks;
396 	char *env_cmdline, *cmdline, *rootdev_input, *serialno;
397 	char *allocated_suffix = NULL;
398 	char *allocated_serialno = NULL;
399 	char *allocated_rootdev = NULL;
400 	unsigned long rootdev_len;
401 
402 	env_cmdline = env_get("bootargs");
403 	if (env_cmdline)
404 		*(current_chunk++) = env_cmdline;
405 
406 	/* The |slot_suffix| needs to be passed to the kernel to know what
407 	 * slot to boot from.
408 	 */
409 	if (slot_suffix) {
410 		allocated_suffix = malloc(strlen(ANDROID_ARG_SLOT_SUFFIX) +
411 					  strlen(slot_suffix) + 1);
412 		memset(allocated_suffix, 0, strlen(ANDROID_ARG_SLOT_SUFFIX)
413 		       + strlen(slot_suffix) + 1);
414 		strcpy(allocated_suffix, ANDROID_ARG_SLOT_SUFFIX);
415 		strcat(allocated_suffix, slot_suffix);
416 		*(current_chunk++) = allocated_suffix;
417 	}
418 
419 	serialno = env_get("serial#");
420 	if (serialno) {
421 		allocated_serialno = malloc(strlen(ANDROID_ARG_SERIALNO) +
422 					  strlen(serialno) + 1);
423 		memset(allocated_serialno, 0, strlen(ANDROID_ARG_SERIALNO) +
424 				strlen(serialno) + 1);
425 		strcpy(allocated_serialno, ANDROID_ARG_SERIALNO);
426 		strcat(allocated_serialno, serialno);
427 		*(current_chunk++) = allocated_serialno;
428 	}
429 
430 	rootdev_input = env_get("android_rootdev");
431 	if (rootdev_input) {
432 		rootdev_len = strlen(ANDROID_ARG_ROOT) + CONFIG_SYS_CBSIZE + 1;
433 		allocated_rootdev = malloc(rootdev_len);
434 		strcpy(allocated_rootdev, ANDROID_ARG_ROOT);
435 		cli_simple_process_macros(rootdev_input,
436 					  allocated_rootdev +
437 					  strlen(ANDROID_ARG_ROOT));
438 		/* Make sure that the string is null-terminated since the
439 		 * previous could not copy to the end of the input string if it
440 		 * is too big.
441 		 */
442 		allocated_rootdev[rootdev_len - 1] = '\0';
443 		*(current_chunk++) = allocated_rootdev;
444 	}
445 
446 	if (extra_args)
447 		*(current_chunk++) = extra_args;
448 
449 	*(current_chunk++) = NULL;
450 	cmdline = strjoin(cmdline_chunks, ' ');
451 	free(allocated_suffix);
452 	free(allocated_rootdev);
453 	return cmdline;
454 }
455 
456 #ifdef CONFIG_ANDROID_AVB
457 static void slot_set_unbootable(AvbABSlotData* slot)
458 {
459 	slot->priority = 0;
460 	slot->tries_remaining = 0;
461 	slot->successful_boot = 0;
462 }
463 
464 static AvbSlotVerifyResult android_slot_verify(char *boot_partname,
465 			       unsigned long *android_load_address,
466 			       char *slot_suffix)
467 {
468 	const char *requested_partitions[1] = {NULL};
469 	uint8_t unlocked = true;
470 	AvbOps *ops;
471 	AvbSlotVerifyFlags flags;
472 	AvbSlotVerifyData *slot_data[1] = {NULL};
473 	AvbSlotVerifyResult verify_result;
474 	AvbABData ab_data, ab_data_orig;
475 	size_t slot_index_to_boot = 0;
476 	char verify_state[38] = {0};
477 	char can_boot = 1;
478 	char retry_no_vbmeta_partition = 1;
479 	unsigned long load_address = *android_load_address;
480 	struct andr_img_hdr *hdr;
481 
482 	requested_partitions[0] = boot_partname;
483 	ops = avb_ops_user_new();
484 	if (ops == NULL) {
485 		printf("avb_ops_user_new() failed!\n");
486 		return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
487 	}
488 
489 	if (ops->read_is_device_unlocked(ops, (bool *)&unlocked) != AVB_IO_RESULT_OK)
490 		printf("Error determining whether device is unlocked.\n");
491 
492 	printf("read_is_device_unlocked() ops returned that device is %s\n",
493 	       (unlocked & LOCK_MASK)? "UNLOCKED" : "LOCKED");
494 
495 	flags = AVB_SLOT_VERIFY_FLAGS_NONE;
496 	if (unlocked & LOCK_MASK)
497 		flags |= AVB_SLOT_VERIFY_FLAGS_ALLOW_VERIFICATION_ERROR;
498 
499 	if(load_metadata(ops->ab_ops, &ab_data, &ab_data_orig)) {
500 		printf("Can not load metadata\n");
501 		return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
502 	}
503 
504 	if (!strncmp(slot_suffix, "_a", 2))
505 		slot_index_to_boot = 0;
506 	else if (!strncmp(slot_suffix, "_b", 2))
507 		slot_index_to_boot = 1;
508 	else
509 		slot_index_to_boot = 0;
510 
511 	if (strcmp(boot_partname, "recovery") == 0)
512 		flags |= AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION;
513 
514 retry_verify:
515 	verify_result =
516 	avb_slot_verify(ops,
517 			requested_partitions,
518 			slot_suffix,
519 			flags,
520 			AVB_HASHTREE_ERROR_MODE_RESTART,
521 			&slot_data[0]);
522 	if (verify_result != AVB_SLOT_VERIFY_RESULT_OK &&
523 	    verify_result != AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED) {
524 		if (retry_no_vbmeta_partition && strcmp(boot_partname, "recovery") == 0) {
525 			printf("Verify recovery with vbmeta.\n");
526 			flags &= ~AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION;
527 			retry_no_vbmeta_partition = 0;
528 			goto retry_verify;
529 		}
530 	}
531 
532 	strcat(verify_state, ANDROID_VERIFY_STATE);
533 	switch (verify_result) {
534 	case AVB_SLOT_VERIFY_RESULT_OK:
535 		if (unlocked & LOCK_MASK)
536 			strcat(verify_state, "orange");
537 		else
538 			strcat(verify_state, "green");
539 		break;
540 	case AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED:
541 		if (unlocked & LOCK_MASK)
542 			strcat(verify_state, "orange");
543 		else
544 			strcat(verify_state, "yellow");
545 		break;
546 	case AVB_SLOT_VERIFY_RESULT_ERROR_OOM:
547 	case AVB_SLOT_VERIFY_RESULT_ERROR_IO:
548 	case AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA:
549 	case AVB_SLOT_VERIFY_RESULT_ERROR_UNSUPPORTED_VERSION:
550 	case AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION:
551 	case AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX:
552 	default:
553 		if (unlocked & LOCK_MASK)
554 			strcat(verify_state, "orange");
555 		else
556 			strcat(verify_state, "red");
557 		break;
558 	}
559 
560 	if (!slot_data[0]) {
561 		can_boot = 0;
562 		goto out;
563 	}
564 
565 	if (verify_result == AVB_SLOT_VERIFY_RESULT_OK ||
566 	    verify_result == AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED ||
567 	    (unlocked & LOCK_MASK)) {
568 		int len = 0;
569 		char *bootargs, *newbootargs;
570 
571 		if (*slot_data[0]->cmdline) {
572 			debug("Kernel command line: %s\n", slot_data[0]->cmdline);
573 			len += strlen(slot_data[0]->cmdline);
574 		}
575 
576 		bootargs = env_get("bootargs");
577 		if (bootargs)
578 			len += strlen(bootargs);
579 
580 		newbootargs = malloc(len + 2);
581 
582 		if (!newbootargs) {
583 			puts("Error: malloc in android_slot_verify failed!\n");
584 			return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
585 		}
586 		*newbootargs = '\0';
587 
588 		if (bootargs) {
589 			strcpy(newbootargs, bootargs);
590 			strcat(newbootargs, " ");
591 		}
592 		if (*slot_data[0]->cmdline)
593 			strcat(newbootargs, slot_data[0]->cmdline);
594 		env_set("bootargs", newbootargs);
595 
596 		hdr = (void *)slot_data[0]->loaded_partitions->data;
597 
598 		/*
599 		 *		populate boot_img_hdr_v3
600 		 *
601 		 * If allow verification error: the image is loaded by
602 		 * ops->get_preloaded_partition() which auto populates
603 		 * boot_img_hdr_v3.
604 		 *
605 		 * If not allow verification error: the image is full loaded
606 		 * by ops->read_from_partition() which doesn't populate
607 		 * boot_img_hdr_v3, we need to fix it here.
608 		 */
609 		if (hdr->header_version >= 3 &&
610 		    !(flags & AVB_SLOT_VERIFY_FLAGS_ALLOW_VERIFICATION_ERROR)) {
611 			struct andr_img_hdr *v3hdr;
612 			struct blk_desc *dev_desc;
613 			disk_partition_t part;
614 
615 			dev_desc = rockchip_get_bootdev();
616 			if (!dev_desc)
617 				return -1;
618 
619 			if (part_get_info_by_name(dev_desc,
620 						  boot_partname, &part) < 0)
621 				return -1;
622 
623 			v3hdr = populate_andr_img_hdr(dev_desc, &part);
624 			if (v3hdr) {
625 				memcpy(hdr, v3hdr, sizeof(*v3hdr));
626 				free(v3hdr);
627 			}
628 		}
629 
630 		/* Reserve page_size */
631 		load_address -= hdr->page_size;
632 		if (android_image_memcpy_separate(hdr, &load_address)) {
633 			printf("Failed to separate copy android image\n");
634 			return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
635 		}
636 		*android_load_address = load_address;
637 	} else {
638 		slot_set_unbootable(&ab_data.slots[slot_index_to_boot]);
639 	}
640 
641 out:
642 	env_update("bootargs", verify_state);
643 	if (save_metadata_if_changed(ops->ab_ops, &ab_data, &ab_data_orig)) {
644 		printf("Can not save metadata\n");
645 		verify_result = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
646 	}
647 
648 	if (slot_data[0] != NULL)
649 		avb_slot_verify_data_free(slot_data[0]);
650 
651 	if ((unlocked & LOCK_MASK) && can_boot)
652 		return 0;
653 	else
654 		return verify_result;
655 }
656 #endif
657 
658 #if defined(CONFIG_CMD_DTIMG) && defined(CONFIG_OF_LIBFDT_OVERLAY)
659 
660 /*
661  * Default return index 0.
662  */
663 __weak int board_select_fdt_index(ulong dt_table_hdr)
664 {
665 /*
666  * User can use "dt_for_each_entry(entry, hdr, idx)" to iterate
667  * over all dt entry of DT image and pick up which they want.
668  *
669  * Example:
670  *	struct dt_table_entry *entry;
671  *	int index;
672  *
673  *	dt_for_each_entry(entry, dt_table_hdr, index) {
674  *
675  *		.... (use entry)
676  *	}
677  *
678  *	return index;
679  */
680 	return 0;
681 }
682 
683 static int android_get_dtbo(ulong *fdt_dtbo,
684 			    const struct andr_img_hdr *hdr,
685 			    int *index, const char *part_dtbo)
686 {
687 	struct dt_table_header *dt_hdr = NULL;
688 	struct blk_desc *dev_desc;
689 	disk_partition_t part_info;
690 	u32 blk_offset, blk_cnt;
691 	void *buf;
692 	ulong e_addr;
693 	u32 e_size;
694 	int e_idx;
695 	int ret;
696 
697 	/* Get partition info */
698 	dev_desc = rockchip_get_bootdev();
699 	if (!dev_desc)
700 		return -ENODEV;
701 
702 	ret = part_get_info_by_name(dev_desc, part_dtbo, &part_info);
703 	if (ret < 0) {
704 		printf("No %s partition, ret=%d\n", part_dtbo, ret);
705 		return ret;
706 	}
707 
708 	/* Check dt table header */
709 	if (!strcmp(part_dtbo, PART_RECOVERY))
710 		blk_offset = part_info.start +
711 			     (hdr->recovery_dtbo_offset / part_info.blksz);
712 	else
713 		blk_offset = part_info.start;
714 
715 	dt_hdr = memalign(ARCH_DMA_MINALIGN, part_info.blksz);
716 	if (!dt_hdr)
717 		return -ENOMEM;
718 
719 	ret = blk_dread(dev_desc, blk_offset, 1, dt_hdr);
720 	if (ret != 1)
721 		goto out1;
722 
723 	if (!android_dt_check_header((ulong)dt_hdr)) {
724 		printf("DTBO: invalid dt table header: 0x%x\n", dt_hdr->magic);
725 		ret = -EINVAL;
726 		goto out1;
727 	}
728 
729 #ifdef DEBUG
730 	android_dt_print_contents((ulong)dt_hdr);
731 #endif
732 
733 	blk_cnt = DIV_ROUND_UP(fdt32_to_cpu(dt_hdr->total_size),
734 			       part_info.blksz);
735 	/* Read all DT Image */
736 	buf = memalign(ARCH_DMA_MINALIGN, part_info.blksz * blk_cnt);
737 	if (!buf) {
738 		ret = -ENOMEM;
739 		goto out1;
740 	}
741 
742 	ret = blk_dread(dev_desc, blk_offset, blk_cnt, buf);
743 	if (ret != blk_cnt)
744 		goto out2;
745 
746 	e_idx = board_select_fdt_index((ulong)buf);
747 	if (e_idx < 0) {
748 		printf("%s: failed to select board fdt index\n", __func__);
749 		ret = -EINVAL;
750 		goto out2;
751 	}
752 
753 	ret = android_dt_get_fdt_by_index((ulong)buf, e_idx, &e_addr, &e_size);
754 	if (!ret) {
755 		printf("%s: failed to get fdt, index=%d\n", __func__, e_idx);
756 		ret = -EINVAL;
757 		goto out2;
758 	}
759 
760 	if (fdt_dtbo)
761 		*fdt_dtbo = e_addr;
762 	if (index)
763 		*index = e_idx;
764 
765 	free(dt_hdr);
766 	debug("ANDROID: Loading dt entry to 0x%lx size 0x%x idx %d from \"%s\" part\n",
767 	      e_addr, e_size, e_idx, part_dtbo);
768 
769 	return 0;
770 
771 out2:
772 	free(buf);
773 out1:
774 	free(dt_hdr);
775 
776 	return ret;
777 }
778 
779 int android_fdt_overlay_apply(void *fdt_addr)
780 {
781 	struct andr_img_hdr *hdr;
782 	struct blk_desc *dev_desc;
783 	const char *part_boot = PART_BOOT;
784 	disk_partition_t part_info;
785 	char *fdt_backup;
786 	char *part_dtbo = PART_DTBO;
787 	char buf[32] = {0};
788 	ulong fdt_dtbo = -1;
789 	u32 totalsize;
790 	int index = -1;
791 	int ret;
792 
793 	if (rockchip_get_boot_mode() == BOOT_MODE_RECOVERY) {
794 #ifdef CONFIG_ANDROID_AB
795 		bool can_find_recovery;
796 
797 		can_find_recovery = ab_can_find_recovery_part();
798 		part_boot = can_find_recovery ? PART_RECOVERY : PART_BOOT;
799 		part_dtbo = can_find_recovery ? PART_RECOVERY : PART_DTBO;
800 #else
801 		part_boot = PART_RECOVERY;
802 		part_dtbo = PART_RECOVERY;
803 #endif
804 	}
805 
806 	dev_desc = rockchip_get_bootdev();
807 	if (!dev_desc)
808 		return -ENODEV;
809 
810 	ret = part_get_info_by_name(dev_desc, part_boot, &part_info);
811 	if (ret < 0)
812 		return ret;
813 
814 	hdr = populate_andr_img_hdr(dev_desc, &part_info);
815 	if (!hdr)
816 		return -EINVAL;
817 #ifdef DEBUG
818 	android_print_contents(hdr);
819 #endif
820 
821 	/*
822 	 * recovery_dtbo fields
823 	 *
824 	 * boot_img_hdr_v0: unsupported
825 	 * boot_img_hdr_v1,2: supported
826 	 * boot_img_hdr_v3 + boot.img: supported
827 	 * boot_img_hdr_v3 + recovery.img: unsupported
828 	 */
829 	if ((hdr->header_version == 0) ||
830 	    (hdr->header_version == 3 && !strcmp(part_boot, PART_RECOVERY)) ||
831 	    (hdr->header_version > 3))
832 		goto out;
833 
834 	ret = android_get_dtbo(&fdt_dtbo, (void *)hdr, &index, part_dtbo);
835 	if (!ret) {
836 		phys_size_t fdt_size;
837 
838 		/* Must incease size before overlay */
839 		fdt_size = fdt_totalsize((void *)fdt_addr) +
840 				fdt_totalsize((void *)fdt_dtbo);
841 		if (sysmem_free((phys_addr_t)fdt_addr))
842 			goto out;
843 
844 		if (!sysmem_alloc_base(MEM_FDT_DTBO,
845 				       (phys_addr_t)fdt_addr,
846 					fdt_size + CONFIG_SYS_FDT_PAD))
847 			goto out;
848 		/*
849 		 * Backup main fdt in case of being destroyed by
850 		 * fdt_overlay_apply() when it overlys failed.
851 		 */
852 		totalsize = fdt_totalsize(fdt_addr);
853 		fdt_backup = malloc(totalsize);
854 		if (!fdt_backup)
855 			goto out;
856 
857 		memcpy(fdt_backup, fdt_addr, totalsize);
858 		fdt_increase_size(fdt_addr, fdt_totalsize((void *)fdt_dtbo));
859 		ret = fdt_overlay_apply(fdt_addr, (void *)fdt_dtbo);
860 		if (!ret) {
861 			snprintf(buf, 32, "%s%d", "androidboot.dtbo_idx=", index);
862 			env_update("bootargs", buf);
863 			printf("ANDROID: fdt overlay OK\n");
864 		} else {
865 			memcpy(fdt_addr, fdt_backup, totalsize);
866 			printf("ANDROID: fdt overlay failed, ret=%d\n", ret);
867 		}
868 
869 		free(fdt_backup);
870 	}
871 
872 out:
873 	free(hdr);
874 
875 	return 0;
876 }
877 #endif
878 
879 int android_image_load_by_partname(struct blk_desc *dev_desc,
880 				   const char *boot_partname,
881 				   unsigned long *load_address)
882 {
883 	disk_partition_t boot_part;
884 	int ret, part_num;
885 
886 	part_num = part_get_info_by_name(dev_desc, boot_partname, &boot_part);
887 	if (part_num < 0) {
888 		printf("%s: Can't find part: %s\n", __func__, boot_partname);
889 		return -1;
890 	}
891 	debug("ANDROID: Loading kernel from \"%s\", partition %d.\n",
892 	      boot_part.name, part_num);
893 
894 	ret = android_image_load(dev_desc, &boot_part, *load_address, -1UL);
895 	if (ret < 0) {
896 		debug("%s: %s part load fail, ret=%d\n",
897 		      __func__, boot_part.name, ret);
898 		return ret;
899 	}
900 	*load_address = ret;
901 
902 	return 0;
903 }
904 
905 int android_bootloader_boot_flow(struct blk_desc *dev_desc,
906 				 unsigned long load_address)
907 {
908 	enum android_boot_mode mode = ANDROID_BOOT_MODE_NORMAL;
909 	disk_partition_t misc_part_info;
910 	int part_num;
911 	char *command_line;
912 	char slot_suffix[3] = {0};
913 	const char *mode_cmdline = NULL;
914 	char *boot_partname = ANDROID_PARTITION_BOOT;
915 
916 	/*
917 	 * 1. Load MISC partition and determine the boot mode
918 	 *   clear its value for the next boot if needed.
919 	 */
920 	part_num = part_get_info_by_name(dev_desc, ANDROID_PARTITION_MISC,
921 					 &misc_part_info);
922 	if (part_num < 0) {
923 		printf("Could not find misc partition\n");
924 	} else {
925 #ifdef CONFIG_ANDROID_KEYMASTER_CA
926 		/* load attestation key from misc partition. */
927 		load_attestation_key(dev_desc, &misc_part_info);
928 #endif
929 
930 		mode = android_bootloader_load_and_clear_mode(dev_desc,
931 							      &misc_part_info);
932 #ifdef CONFIG_RKIMG_BOOTLOADER
933 		if (mode == ANDROID_BOOT_MODE_NORMAL) {
934 			if (rockchip_get_boot_mode() == BOOT_MODE_RECOVERY)
935 				mode = ANDROID_BOOT_MODE_RECOVERY;
936 		}
937 #endif
938 	}
939 
940 	printf("ANDROID: reboot reason: \"%s\"\n", android_boot_mode_str(mode));
941 #ifdef CONFIG_ANDROID_AB
942 	/* Get current slot_suffix */
943 	if (ab_get_slot_suffix(slot_suffix))
944 		return -1;
945 #endif
946 	switch (mode) {
947 	case ANDROID_BOOT_MODE_NORMAL:
948 		/* In normal mode, we load the kernel from "boot" but append
949 		 * "skip_initramfs" to the cmdline to make it ignore the
950 		 * recovery initramfs in the boot partition.
951 		 */
952 #ifdef CONFIG_ANDROID_AB
953 		/*  In A/B, the recovery image is built as boot.img, containing the
954 		* recovery's ramdisk. Previously, bootloader used the skip_initramfs
955 		* kernel command line parameter to decide which mode to boot into.
956 		* For Android >=10 and with dynamic partition support, the bootloader
957 		* MUST NOT pass skip_initramfs to the kernel command-line.
958 		* Instead, bootloader should pass androidboot.force_normal_boot=1
959 		* and then Android's first-stage init in ramdisk
960 		* will skip recovery and boot normal Android.
961 		*/
962 		if (ab_is_support_dynamic_partition(dev_desc)) {
963 			mode_cmdline = "androidboot.force_normal_boot=1";
964 		} else {
965 			mode_cmdline = "skip_initramfs";
966 		}
967 #endif
968 		break;
969 	case ANDROID_BOOT_MODE_RECOVERY:
970 		/*
971 		 * In recovery mode, if have recovery partition, we still boot the
972 		 * kernel from "recovery". If not, don't skip the initramfs so it
973 		 * boots to recovery from image in partition "boot".
974 		 */
975 #ifdef CONFIG_ANDROID_AB
976 		boot_partname = ab_can_find_recovery_part() ?
977 			ANDROID_PARTITION_RECOVERY : ANDROID_PARTITION_BOOT;
978 #else
979 		boot_partname = ANDROID_PARTITION_RECOVERY;
980 #endif
981 		break;
982 	case ANDROID_BOOT_MODE_BOOTLOADER:
983 		/* Bootloader mode enters fastboot. If this operation fails we
984 		 * simply return since we can't recover from this situation by
985 		 * switching to another slot.
986 		 */
987 		return android_bootloader_boot_bootloader();
988 	}
989 
990 #ifdef CONFIG_ANDROID_AVB
991 	uint8_t vboot_flag = 0;
992 	disk_partition_t vbmeta_part_info;
993 
994 #ifdef CONFIG_OPTEE_CLIENT
995 	if (trusty_read_vbootkey_enable_flag(&vboot_flag)) {
996 		printf("Can't read vboot flag\n");
997 		return -1;
998 	}
999 #endif
1000 	if (vboot_flag) {
1001 		printf("Vboot=1, SecureBoot enabled, AVB verify\n");
1002 		if (android_slot_verify(boot_partname, &load_address,
1003 					slot_suffix)) {
1004 			printf("AVB verify failed\n");
1005 
1006 			return -1;
1007 		}
1008 	} else {
1009 		part_num = part_get_info_by_name(dev_desc,
1010 						 ANDROID_PARTITION_VBMETA,
1011 						 &vbmeta_part_info);
1012 		if (part_num < 0) {
1013 			printf("Not AVB images, AVB skip\n");
1014 			env_update("bootargs",
1015 				   "androidboot.verifiedbootstate=orange");
1016 			if (android_image_load_by_partname(dev_desc,
1017 							   boot_partname,
1018 							   &load_address)) {
1019 				printf("Android image load failed\n");
1020 				return -1;
1021 			}
1022 		} else {
1023 			printf("Vboot=0, AVB images, AVB verify\n");
1024 			if (android_slot_verify(boot_partname, &load_address,
1025 						slot_suffix)) {
1026 				printf("AVB verify failed\n");
1027 
1028 				return -1;
1029 			}
1030 		}
1031 	}
1032 #else
1033 	/*
1034 	 * 2. Load the boot/recovery from the desired "boot" partition.
1035 	 * Determine if this is an AOSP image.
1036 	 */
1037 	if (android_image_load_by_partname(dev_desc,
1038 					   boot_partname,
1039 					   &load_address)) {
1040 		printf("Android image load failed\n");
1041 		return -1;
1042 	}
1043 #endif
1044 
1045 #ifdef CONFIG_ANDROID_AB
1046 	ab_update_root_uuid();
1047 #endif
1048 
1049 	/* Set Android root variables. */
1050 	env_set_ulong("android_root_devnum", dev_desc->devnum);
1051 	env_set("android_slotsufix", slot_suffix);
1052 
1053 #ifdef CONFIG_FASTBOOT_OEM_UNLOCK
1054 	/* read oem unlock status and attach to bootargs */
1055 	uint8_t unlock = 0;
1056 	TEEC_Result result;
1057 	char oem_unlock[OEM_UNLOCK_ARG_SIZE] = {0};
1058 	result = trusty_read_oem_unlock(&unlock);
1059 	if (result) {
1060 		printf("read oem unlock status with error : 0x%x\n", result);
1061 	} else {
1062 		snprintf(oem_unlock, OEM_UNLOCK_ARG_SIZE, "androidboot.oem_unlocked=%d", unlock);
1063 		env_update("bootargs", oem_unlock);
1064 	}
1065 #endif
1066 
1067 	/* Assemble the command line */
1068 	command_line = android_assemble_cmdline(slot_suffix, mode_cmdline);
1069 	env_update("bootargs", command_line);
1070 
1071 	debug("ANDROID: bootargs: \"%s\"\n", command_line);
1072 
1073 #ifdef CONFIG_SUPPORT_OEM_DTB
1074 	if (android_bootloader_get_fdt(ANDROID_PARTITION_OEM,
1075 				       ANDROID_ARG_FDT_FILENAME)) {
1076 		printf("Can not get the fdt data from oem!\n");
1077 	}
1078 #endif
1079 #ifdef CONFIG_OPTEE_CLIENT
1080 	if (trusty_notify_optee_uboot_end())
1081 		printf("Close optee client failed!\n");
1082 #endif
1083 
1084 #ifdef CONFIG_AMP
1085 	return android_bootloader_boot_kernel(load_address);
1086 #else
1087 	android_bootloader_boot_kernel(load_address);
1088 
1089 	/* TODO: If the kernel doesn't boot mark the selected slot as bad. */
1090 	return -1;
1091 #endif
1092 }
1093 
1094 int android_avb_boot_flow(unsigned long kernel_address)
1095 {
1096 	struct blk_desc *dev_desc;
1097 	disk_partition_t boot_part_info;
1098 	int ret;
1099 
1100 	dev_desc = rockchip_get_bootdev();
1101 	if (!dev_desc) {
1102 		printf("%s: dev_desc is NULL!\n", __func__);
1103 		return -1;
1104 	}
1105 
1106 	/* Load the kernel from the desired "boot" partition. */
1107 	ret = part_get_info_by_name(dev_desc, ANDROID_PARTITION_BOOT,
1108 				    &boot_part_info);
1109 	if (ret < 0) {
1110 		printf("%s: failed to get boot part\n", __func__);
1111 		return ret;
1112 	}
1113 
1114 	ret = android_image_load(dev_desc, &boot_part_info,
1115 				 kernel_address, -1UL);
1116 	if (ret < 0) {
1117 		printf("Android avb boot failed, error %d.\n", ret);
1118 		return ret;
1119 	}
1120 
1121 	android_bootloader_boot_kernel(kernel_address);
1122 
1123 	/* TODO: If the kernel doesn't boot mark the selected slot as bad. */
1124 	return -1;
1125 }
1126 
1127 int android_boot_flow(unsigned long kernel_address)
1128 {
1129 	struct blk_desc *dev_desc;
1130 	disk_partition_t boot_part_info;
1131 	int ret;
1132 
1133 	dev_desc = rockchip_get_bootdev();
1134 	if (!dev_desc) {
1135 		printf("%s: dev_desc is NULL!\n", __func__);
1136 		return -1;
1137 	}
1138 	/* Load the kernel from the desired "boot" partition. */
1139 	ret = part_get_info_by_name(dev_desc, ANDROID_PARTITION_BOOT,
1140 				    &boot_part_info);
1141 	if (ret < 0) {
1142 		printf("%s: failed to get boot part\n", __func__);
1143 		return ret;
1144 	}
1145 
1146 	ret = android_image_load(dev_desc, &boot_part_info, kernel_address,
1147 				 -1UL);
1148 	if (ret < 0)
1149 		return ret;
1150 
1151 	android_bootloader_boot_kernel(kernel_address);
1152 
1153 	/* TODO: If the kernel doesn't boot mark the selected slot as bad. */
1154 	return -1;
1155 }
1156