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