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