xref: /rk3399_rockchip-uboot/common/android_bootloader.c (revision 39d40ad54eb2274a86419000e0e087673f86508a)
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 <mp_boot.h>
22 #include <fdt_support.h>
23 #include <fs.h>
24 #include <boot_rkimg.h>
25 #include <attestation_key.h>
26 #include <keymaster.h>
27 #include <linux/libfdt_env.h>
28 #include <optee_include/OpteeClientInterface.h>
29 #include <bidram.h>
30 #include <console.h>
31 #include <sysmem.h>
32 
33 DECLARE_GLOBAL_DATA_PTR;
34 
35 int android_bootloader_message_load(
36 	struct blk_desc *dev_desc,
37 	const disk_partition_t *part_info,
38 	struct android_bootloader_message *message)
39 {
40 	ulong message_blocks = sizeof(struct android_bootloader_message) /
41 	    part_info->blksz;
42 	if (message_blocks > part_info->size) {
43 		printf("misc partition too small.\n");
44 		return -1;
45 	}
46 
47 	if (blk_dread(dev_desc, part_info->start + android_bcb_msg_sector_offset(),
48 	     message_blocks, message) !=
49 	    message_blocks) {
50 		printf("Could not read from misc partition\n");
51 		return -1;
52 	}
53 	debug("ANDROID: Loaded BCB, %lu blocks.\n", message_blocks);
54 	return 0;
55 }
56 
57 static int android_bootloader_message_write(
58 	struct blk_desc *dev_desc,
59 	const disk_partition_t *part_info,
60 	struct android_bootloader_message *message)
61 {
62 	ulong message_blocks = sizeof(struct android_bootloader_message) /
63 	    part_info->blksz + android_bcb_msg_sector_offset();
64 
65 	if (message_blocks > part_info->size) {
66 		printf("misc partition too small.\n");
67 		return -1;
68 	}
69 
70 	if (blk_dwrite(dev_desc, part_info->start, message_blocks, message) !=
71 	    message_blocks) {
72 		printf("Could not write to misc partition\n");
73 		return -1;
74 	}
75 	debug("ANDROID: Wrote new BCB, %lu blocks.\n", message_blocks);
76 	return 0;
77 }
78 
79 static enum android_boot_mode android_bootloader_load_and_clear_mode(
80 	struct blk_desc *dev_desc,
81 	const disk_partition_t *misc_part_info)
82 {
83 	struct android_bootloader_message bcb;
84 
85 #ifdef CONFIG_FASTBOOT
86 	char *bootloader_str;
87 
88 	/* Check for message from bootloader stored in RAM from a previous boot.
89 	 */
90 	bootloader_str = (char *)CONFIG_FASTBOOT_BUF_ADDR;
91 	if (!strcmp("reboot-bootloader", bootloader_str)) {
92 		bootloader_str[0] = '\0';
93 		return ANDROID_BOOT_MODE_BOOTLOADER;
94 	}
95 #endif
96 
97 	/* Check and update the BCB message if needed. */
98 	if (android_bootloader_message_load(dev_desc, misc_part_info, &bcb) <
99 	    0) {
100 		printf("WARNING: Unable to load the BCB.\n");
101 		return ANDROID_BOOT_MODE_NORMAL;
102 	}
103 
104 	if (!strcmp("bootonce-bootloader", bcb.command)) {
105 		/* Erase the message in the BCB since this value should be used
106 		 * only once.
107 		 */
108 		memset(bcb.command, 0, sizeof(bcb.command));
109 		android_bootloader_message_write(dev_desc, misc_part_info,
110 						 &bcb);
111 		return ANDROID_BOOT_MODE_BOOTLOADER;
112 	}
113 
114 	if (!strcmp("boot-recovery", bcb.command))
115 		return ANDROID_BOOT_MODE_RECOVERY;
116 
117 	if (!strcmp("boot-fastboot", bcb.command))
118 		return ANDROID_BOOT_MODE_RECOVERY;
119 
120 	return ANDROID_BOOT_MODE_NORMAL;
121 }
122 
123 int android_bcb_write(char *cmd)
124 {
125 	struct android_bootloader_message message = {0};
126 	disk_partition_t part_info;
127 	struct blk_desc *dev_desc;
128 	int ret;
129 
130 	if (!cmd)
131 		return -ENOMEM;
132 
133 	if (strlen(cmd) >= 32)
134 		return -ENOMEM;
135 
136 	dev_desc = rockchip_get_bootdev();
137 	if (!dev_desc) {
138 		printf("%s: dev_desc is NULL!\n", __func__);
139 		return -ENODEV;
140 	}
141 
142 	ret = part_get_info_by_name(dev_desc, ANDROID_PARTITION_MISC, &part_info);
143 	if (ret < 0) {
144 		printf("%s: Could not found misc partition, just run recovery\n",
145 		       __func__);
146 		return -ENODEV;
147 	}
148 
149 	strcpy(message.command, cmd);
150 	return android_bootloader_message_write(dev_desc, &part_info, &message);
151 }
152 
153 /**
154  * Return the reboot reason string for the passed boot mode.
155  *
156  * @param mode	The Android Boot mode.
157  * @return a pointer to the reboot reason string for mode.
158  */
159 static const char *android_boot_mode_str(enum android_boot_mode mode)
160 {
161 	switch (mode) {
162 	case ANDROID_BOOT_MODE_NORMAL:
163 		return "(none)";
164 	case ANDROID_BOOT_MODE_RECOVERY:
165 		return "recovery";
166 	case ANDROID_BOOT_MODE_BOOTLOADER:
167 		return "bootloader";
168 	}
169 	return NULL;
170 }
171 
172 static int android_bootloader_boot_bootloader(void)
173 {
174 	const char *fastboot_cmd = env_get("fastbootcmd");
175 
176 	if (fastboot_cmd == NULL) {
177 		printf("fastboot_cmd is null, run default fastboot_cmd!\n");
178 		fastboot_cmd = "fastboot usb 0";
179 	}
180 
181 	return run_command(fastboot_cmd, CMD_FLAG_ENV);
182 }
183 
184 #ifdef CONFIG_SUPPORT_OEM_DTB
185 static int android_bootloader_get_fdt(const char *part_name,
186 		const char *load_file_name)
187 {
188 	struct blk_desc *dev_desc;
189 	disk_partition_t part_info;
190 	char *fdt_addr = NULL;
191 	char dev_part[3] = {0};
192 	loff_t bytes = 0;
193 	loff_t pos = 0;
194 	loff_t len_read;
195 	unsigned long addr = 0;
196 	int part_num = -1;
197 	int ret;
198 
199 	dev_desc = rockchip_get_bootdev();
200 	if (!dev_desc) {
201 		printf("%s: dev_desc is NULL!\n", __func__);
202 		return -1;
203 	}
204 
205 	part_num = part_get_info_by_name(dev_desc, part_name, &part_info);
206 	if (part_num < 0) {
207 		printf("ANDROID: Could not find partition \"%s\"\n", part_name);
208 		return -1;
209 	}
210 
211 	snprintf(dev_part, ARRAY_SIZE(dev_part), ":%x", part_num);
212 	if (fs_set_blk_dev_with_part(dev_desc, part_num))
213 		return -1;
214 
215 	fdt_addr = env_get("fdt_addr_r");
216 	if (!fdt_addr) {
217 		printf("ANDROID: No Found FDT Load Address.\n");
218 		return -1;
219 	}
220 	addr = simple_strtoul(fdt_addr, NULL, 16);
221 
222 	ret = fs_read(load_file_name, addr, pos, bytes, &len_read);
223 	if (ret < 0)
224 		return -1;
225 
226 	return 0;
227 }
228 #endif
229 
230 /*
231  *   Test on RK3308 AARCH64 mode (Cortex A35 816 MHZ) boot with eMMC:
232  *
233  *   |-------------------------------------------------------------------|
234  *   | Format    |  Size(Byte) | Ratio | Decomp time(ms) | Boot time(ms) |
235  *   |-------------------------------------------------------------------|
236  *   | Image     | 7720968     |       |                 |     488       |
237  *   |-------------------------------------------------------------------|
238  *   | Image.lz4 | 4119448     | 53%   |       59        |     455       |
239  *   |-------------------------------------------------------------------|
240  *   | Image.lzo | 3858322     | 49%   |       141       |     536       |
241  *   |-------------------------------------------------------------------|
242  *   | Image.gz  | 3529108     | 45%   |       222       |     609       |
243  *   |-------------------------------------------------------------------|
244  *   | Image.bz2 | 3295914     | 42%   |       2940      |               |
245  *   |-------------------------------------------------------------------|
246  *   | Image.lzma| 2683750     | 34%   |                 |               |
247  *   |-------------------------------------------------------------------|
248  */
249 static int sysmem_alloc_uncomp_kernel(ulong andr_hdr,
250 				      ulong uncomp_kaddr, u32 comp)
251 {
252 	struct andr_img_hdr *hdr = (struct andr_img_hdr *)andr_hdr;
253 	ulong ksize, kaddr;
254 
255 	if (comp != IH_COMP_NONE) {
256 		/* Release compressed sysmem */
257 		kaddr = env_get_hex("kernel_addr_c", 0);
258 		if (!kaddr)
259 			kaddr = env_get_hex("kernel_addr_r", 0);
260 		kaddr -= hdr->page_size;
261 		if (sysmem_free((phys_addr_t)kaddr))
262 			return -EINVAL;
263 #ifdef CONFIG_SKIP_RELOCATE_UBOOT
264 		sysmem_free(CONFIG_SYS_TEXT_BASE);
265 #endif
266 		/*
267 		 * Use smaller Ratio to get larger estimated uncompress
268 		 * kernel size.
269 		 */
270 		if (comp == IH_COMP_ZIMAGE)
271 			ksize = hdr->kernel_size * 100 / 45;
272 		else if (comp == IH_COMP_LZ4)
273 			ksize = hdr->kernel_size * 100 / 50;
274 		else if (comp == IH_COMP_LZO)
275 			ksize = hdr->kernel_size * 100 / 45;
276 		else if (comp == IH_COMP_GZIP)
277 			ksize = hdr->kernel_size * 100 / 40;
278 		else if (comp == IH_COMP_BZIP2)
279 			ksize = hdr->kernel_size * 100 / 40;
280 		else if (comp == IH_COMP_LZMA)
281 			ksize = hdr->kernel_size * 100 / 30;
282 		else
283 			ksize = hdr->kernel_size;
284 
285 		kaddr = uncomp_kaddr;
286 		ksize = ALIGN(ksize, 512);
287 		if (!sysmem_alloc_base(MEM_UNCOMP_KERNEL,
288 				       (phys_addr_t)kaddr, ksize))
289 			return -ENOMEM;
290 	}
291 
292 	return 0;
293 }
294 
295 int android_bootloader_boot_kernel(unsigned long kernel_address)
296 {
297 	char *kernel_addr_r = env_get("kernel_addr_r");
298 	char *kernel_addr_c = env_get("kernel_addr_c");
299 	char *fdt_addr = env_get("fdt_addr_r");
300 	char kernel_addr_str[12];
301 	char comp_str[32] = {0};
302 	ulong comp_type;
303 	const char *comp_name[] = {
304 		[IH_COMP_NONE]  = "IMAGE",
305 		[IH_COMP_GZIP]  = "GZIP",
306 		[IH_COMP_BZIP2] = "BZIP2",
307 		[IH_COMP_LZMA]  = "LZMA",
308 		[IH_COMP_LZO]   = "LZO",
309 		[IH_COMP_LZ4]   = "LZ4",
310 		[IH_COMP_ZIMAGE]= "ZIMAGE",
311 	};
312 	char *bootm_args[] = {
313 		kernel_addr_str, kernel_addr_str, fdt_addr, NULL };
314 
315 	comp_type = env_get_ulong("os_comp", 10, 0);
316 	sprintf(kernel_addr_str, "0x%08lx", kernel_address);
317 
318 	if (comp_type != IH_COMP_NONE) {
319 		if (comp_type == IH_COMP_ZIMAGE &&
320 		    kernel_addr_r && !kernel_addr_c) {
321 			kernel_addr_c = kernel_addr_r;
322 			kernel_addr_r = __stringify(CONFIG_SYS_SDRAM_BASE);
323 		}
324 		snprintf(comp_str, 32, "%s%s%s",
325 			 "(Uncompress to ", kernel_addr_r, ")");
326 	}
327 
328 	printf("Booting %s kernel at %s%s with fdt at %s...\n\n\n",
329 	       comp_name[comp_type],
330 	       comp_type != IH_COMP_NONE ? kernel_addr_c : kernel_addr_r,
331 	       comp_str, fdt_addr);
332 
333 	hotkey_run(HK_SYSMEM);
334 
335 	/*
336 	 * Check whether there is enough space for uncompress kernel,
337 	 * Actually, here only gives a sysmem warning message when failed
338 	 * but never return -1.
339 	 */
340 	if (sysmem_alloc_uncomp_kernel(kernel_address,
341 				       simple_strtoul(kernel_addr_r, NULL, 16),
342 				       comp_type))
343 		return -1;
344 
345 	return do_bootm_states(NULL, 0, ARRAY_SIZE(bootm_args), bootm_args,
346 		BOOTM_STATE_START |
347 		BOOTM_STATE_FINDOS | BOOTM_STATE_FINDOTHER |
348 		BOOTM_STATE_LOADOS |
349 #ifdef CONFIG_SYS_BOOT_RAMDISK_HIGH
350 		BOOTM_STATE_RAMDISK |
351 #endif
352 		BOOTM_STATE_OS_PREP | BOOTM_STATE_OS_FAKE_GO |
353 		BOOTM_STATE_OS_GO, &images, 1);
354 }
355 
356 static char *strjoin(const char **chunks, char separator)
357 {
358 	int len, joined_len = 0;
359 	char *ret, *current;
360 	const char **p;
361 
362 	for (p = chunks; *p; p++)
363 		joined_len += strlen(*p) + 1;
364 
365 	if (!joined_len) {
366 		ret = malloc(1);
367 		if (ret)
368 			ret[0] = '\0';
369 		return ret;
370 	}
371 
372 	ret = malloc(joined_len);
373 	current = ret;
374 	if (!ret)
375 		return ret;
376 
377 	for (p = chunks; *p; p++) {
378 		len = strlen(*p);
379 		memcpy(current, *p, len);
380 		current += len;
381 		*current = separator;
382 		current++;
383 	}
384 	/* Replace the last separator by a \0. */
385 	current[-1] = '\0';
386 	return ret;
387 }
388 
389 /** android_assemble_cmdline - Assemble the command line to pass to the kernel
390  * @return a newly allocated string
391  */
392 char *android_assemble_cmdline(const char *slot_suffix,
393 				      const char *extra_args)
394 {
395 	const char *cmdline_chunks[16];
396 	const char **current_chunk = cmdline_chunks;
397 	char *env_cmdline, *cmdline, *rootdev_input, *serialno;
398 	char *allocated_suffix = NULL;
399 	char *allocated_serialno = NULL;
400 	char *allocated_rootdev = NULL;
401 	unsigned long rootdev_len;
402 
403 	env_cmdline = env_get("bootargs");
404 	if (env_cmdline)
405 		*(current_chunk++) = env_cmdline;
406 
407 	/* The |slot_suffix| needs to be passed to the kernel to know what
408 	 * slot to boot from.
409 	 */
410 #ifdef CONFIG_ANDROID_AB
411 	if (slot_suffix) {
412 		allocated_suffix = malloc(strlen(ANDROID_ARG_SLOT_SUFFIX) +
413 					  strlen(slot_suffix) + 1);
414 		memset(allocated_suffix, 0, strlen(ANDROID_ARG_SLOT_SUFFIX)
415 		       + strlen(slot_suffix) + 1);
416 		strcpy(allocated_suffix, ANDROID_ARG_SLOT_SUFFIX);
417 		strcat(allocated_suffix, slot_suffix);
418 		*(current_chunk++) = allocated_suffix;
419 	}
420 #endif
421 	serialno = env_get("serial#");
422 	if (serialno) {
423 		allocated_serialno = malloc(strlen(ANDROID_ARG_SERIALNO) +
424 					  strlen(serialno) + 1);
425 		memset(allocated_serialno, 0, strlen(ANDROID_ARG_SERIALNO) +
426 				strlen(serialno) + 1);
427 		strcpy(allocated_serialno, ANDROID_ARG_SERIALNO);
428 		strcat(allocated_serialno, serialno);
429 		*(current_chunk++) = allocated_serialno;
430 	}
431 
432 	rootdev_input = env_get("android_rootdev");
433 	if (rootdev_input) {
434 		rootdev_len = strlen(ANDROID_ARG_ROOT) + CONFIG_SYS_CBSIZE + 1;
435 		allocated_rootdev = malloc(rootdev_len);
436 		strcpy(allocated_rootdev, ANDROID_ARG_ROOT);
437 		cli_simple_process_macros(rootdev_input,
438 					  allocated_rootdev +
439 					  strlen(ANDROID_ARG_ROOT));
440 		/* Make sure that the string is null-terminated since the
441 		 * previous could not copy to the end of the input string if it
442 		 * is too big.
443 		 */
444 		allocated_rootdev[rootdev_len - 1] = '\0';
445 		*(current_chunk++) = allocated_rootdev;
446 	}
447 
448 	if (extra_args)
449 		*(current_chunk++) = extra_args;
450 
451 	*(current_chunk++) = NULL;
452 	cmdline = strjoin(cmdline_chunks, ' ');
453 	free(allocated_suffix);
454 	free(allocated_rootdev);
455 	return cmdline;
456 }
457 
458 #ifdef CONFIG_ANDROID_AVB
459 static void slot_set_unbootable(AvbABSlotData* slot)
460 {
461 	slot->priority = 0;
462 	slot->tries_remaining = 0;
463 	slot->successful_boot = 0;
464 }
465 
466 static char *join_str(const char *a, const char *b)
467 {
468 	size_t len = strlen(a) + strlen(b) + 1 /* null term */;
469 	char *ret = (char *)malloc(len);
470 
471 	if (!ret) {
472 		debug("failed to alloc %zu\n", len);
473 		return NULL;
474 	}
475 	strcpy(ret, a);
476 	strcat(ret, b);
477 
478 	return ret;
479 }
480 
481 static size_t get_partition_size(AvbOps *ops, char *name,
482 				 const char *slot_suffix)
483 {
484 	char *partition_name = join_str(name, slot_suffix);
485 	uint64_t size = 0;
486 	AvbIOResult res;
487 
488 	if (partition_name == NULL)
489 		goto bail;
490 
491 	res = ops->get_size_of_partition(ops, partition_name, &size);
492 	if (res != AVB_IO_RESULT_OK && res != AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION)
493 		size = 0;
494 bail:
495 	if (partition_name)
496 		free(partition_name);
497 
498 	return size;
499 }
500 
501 static struct AvbOpsData preload_user_data;
502 
503 static int avb_image_distribute_prepare(AvbSlotVerifyData *slot_data,
504 					AvbOps *ops, char *slot_suffix)
505 {
506 	struct AvbOpsData *data = (struct AvbOpsData *)(ops->user_data);
507 	size_t vendor_boot_size;
508 	size_t init_boot_size;
509 	size_t resource_size;
510 	size_t boot_size;
511 	void *image_buf;
512 
513 	boot_size = max(get_partition_size(ops, ANDROID_PARTITION_BOOT, slot_suffix),
514 		get_partition_size(ops, ANDROID_PARTITION_RECOVERY, slot_suffix));
515 	init_boot_size = get_partition_size(ops,
516 				ANDROID_PARTITION_INIT_BOOT, slot_suffix);
517 	vendor_boot_size = get_partition_size(ops,
518 				ANDROID_PARTITION_VENDOR_BOOT, slot_suffix);
519 	resource_size = get_partition_size(ops,
520 				ANDROID_PARTITION_RESOURCE, slot_suffix);
521 	image_buf = sysmem_alloc(MEM_AVB_ANDROID,
522 				 boot_size + init_boot_size +
523 				 vendor_boot_size + resource_size);
524 	if (!image_buf) {
525 		printf("avb: sysmem alloc failed\n");
526 		return -ENOMEM;
527 	}
528 
529 	/* layout: | boot/recovery | vendor_boot | init_boot | resource | */
530 	data->slot_suffix = slot_suffix;
531 	data->boot.addr = image_buf;
532 	data->boot.size = 0;
533 	data->vendor_boot.addr = data->boot.addr + boot_size;
534 	data->vendor_boot.size = 0;
535 	data->init_boot.addr = data->vendor_boot.addr + vendor_boot_size;
536 	data->init_boot.size = 0;
537 	data->resource.addr = data->init_boot.addr + init_boot_size;
538 	data->resource.size = 0;
539 
540 	return 0;
541 }
542 
543 static int avb_image_distribute_finish(AvbSlotVerifyData *slot_data,
544 				       AvbSlotVerifyFlags flags,
545 				       ulong *load_address)
546 {
547 	struct andr_img_hdr *hdr;
548 	ulong load_addr = *load_address;
549 	void *vendor_boot_hdr = NULL;
550 	void *init_boot_hdr = NULL;
551 	void *boot_hdr = NULL;
552 	char *part_name;
553 	int i, ret;
554 
555 	for (i = 0; i < slot_data->num_loaded_partitions; i++) {
556 		part_name = slot_data->loaded_partitions[i].partition_name;
557 		if (!strncmp(ANDROID_PARTITION_BOOT, part_name, 4) ||
558 		    !strncmp(ANDROID_PARTITION_RECOVERY, part_name, 8)) {
559 			boot_hdr = slot_data->loaded_partitions[i].data;
560 		} else if (!strncmp(ANDROID_PARTITION_INIT_BOOT, part_name, 9)) {
561 			init_boot_hdr = slot_data->loaded_partitions[i].data;
562 		} else if (!strncmp(ANDROID_PARTITION_VENDOR_BOOT, part_name, 11)) {
563 			vendor_boot_hdr = slot_data->loaded_partitions[i].data;
564 		}
565 	}
566 
567 	/*
568 	 *		populate boot_img_hdr_v34
569 	 *
570 	 * If allow verification error: the images are loaded by
571 	 * ops->get_preloaded_partition() which auto populates
572 	 * boot_img_hdr_v34.
573 	 *
574 	 * If not allow verification error: the images are full loaded
575 	 * by ops->read_from_partition() which doesn't populate
576 	 * boot_img_hdr_v34, we need to fix it here for bootm and
577 	 */
578 
579 	hdr = boot_hdr;
580 	if (hdr->header_version >= 3 &&
581 	    !(flags & AVB_SLOT_VERIFY_FLAGS_ALLOW_VERIFICATION_ERROR)) {
582 		hdr = malloc(sizeof(struct andr_img_hdr));
583 		if (!hdr)
584 			return -ENOMEM;
585 
586 		ret = populate_boot_info(boot_hdr, vendor_boot_hdr,
587 					 init_boot_hdr, hdr, true);
588 		if (ret < 0) {
589 			printf("avb: populate boot info failed, ret=%d\n", ret);
590 			return ret;
591 		}
592 		memcpy(boot_hdr, hdr, sizeof(*hdr));
593 	}
594 
595 	/* distribute ! */
596 	load_addr -= hdr->page_size;
597 	if (android_image_memcpy_separate(boot_hdr, &load_addr)) {
598 		printf("Failed to separate copy android image\n");
599 		return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
600 	}
601 
602 	*load_address = load_addr;
603 
604 	return 0;
605 }
606 
607 int android_image_verify_resource(const char *boot_part, ulong *resc_buf)
608 {
609 	const char *requested_partitions[] = {
610 		NULL,
611 		NULL,
612 	};
613 	struct AvbOpsData *data;
614 	uint8_t unlocked = true;
615 	AvbOps *ops;
616 	AvbSlotVerifyFlags flags;
617 	AvbSlotVerifyData *slot_data = {NULL};
618 	AvbSlotVerifyResult verify_result;
619 	char slot_suffix[3] = {0};
620 	char *part_name;
621 	void *image_buf = NULL;
622 	int retry_no_vbmeta_partition = 1;
623 	int i, ret;
624 
625 	ops = avb_ops_user_new();
626 	if (ops == NULL) {
627 		printf("avb_ops_user_new() failed!\n");
628 		return -AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
629 	}
630 
631 	if (ops->read_is_device_unlocked(ops, (bool *)&unlocked) != AVB_IO_RESULT_OK)
632 		printf("Error determining whether device is unlocked.\n");
633 
634 	printf("Device is: %s\n", (unlocked & LOCK_MASK)? "UNLOCKED" : "LOCKED");
635 
636 	if (unlocked & LOCK_MASK) {
637 		*resc_buf = 0;
638 		return 0;
639 	}
640 
641 	flags = AVB_SLOT_VERIFY_FLAGS_NONE;
642 	if (strcmp(boot_part, ANDROID_PARTITION_RECOVERY) == 0)
643 		flags |= AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION;
644 
645 #ifdef CONFIG_ANDROID_AB
646 	part_name = strdup(boot_part);
647 	*(part_name + strlen(boot_part) - 2) = '\0';
648 	requested_partitions[0] = part_name;
649 
650 	ret = rk_avb_get_current_slot(slot_suffix);
651 	if (ret) {
652 		printf("Failed to get slot suffix, ret=%d\n", ret);
653 		return ret;
654 	}
655 #else
656 	requested_partitions[0] = boot_part;
657 #endif
658 	data = (struct AvbOpsData *)(ops->user_data);
659 	ret = avb_image_distribute_prepare(slot_data, ops, slot_suffix);
660 	if (ret) {
661 		printf("avb image distribute prepare failed %d\n", ret);
662 		return ret;
663 	}
664 
665 retry_verify:
666 	verify_result =
667 	avb_slot_verify(ops,
668 			requested_partitions,
669 			slot_suffix,
670 			flags,
671 			AVB_HASHTREE_ERROR_MODE_RESTART,
672 			&slot_data);
673 	if (verify_result != AVB_SLOT_VERIFY_RESULT_OK &&
674 	    verify_result != AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED) {
675 		if (retry_no_vbmeta_partition && strcmp(boot_part, ANDROID_PARTITION_RECOVERY) == 0) {
676 			printf("Verify recovery with vbmeta.\n");
677 			flags &= ~AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION;
678 			retry_no_vbmeta_partition = 0;
679 			goto retry_verify;
680 		}
681 	}
682 
683 	if (verify_result != AVB_SLOT_VERIFY_RESULT_OK || !slot_data) {
684 		sysmem_free((ulong)data->boot.addr);
685 		return verify_result;
686 	}
687 
688 	for (i = 0; i < slot_data->num_loaded_partitions; i++) {
689 		part_name = slot_data->loaded_partitions[i].partition_name;
690 		if (!strncmp(ANDROID_PARTITION_RESOURCE, part_name, 8)) {
691 			image_buf = slot_data->loaded_partitions[i].data;
692 			break;
693 		} else if (!strncmp(ANDROID_PARTITION_BOOT, part_name, 4) ||
694 			   !strncmp(ANDROID_PARTITION_RECOVERY, part_name, 8)) {
695 			struct andr_img_hdr *hdr;
696 
697 			hdr = (void *)slot_data->loaded_partitions[i].data;
698 			if (android_image_check_header(hdr))
699 				continue;
700 
701 			if (hdr->header_version <= 2) {
702 				image_buf = (void *)hdr + hdr->page_size +
703 					ALIGN(hdr->kernel_size, hdr->page_size) +
704 					ALIGN(hdr->ramdisk_size, hdr->page_size);
705 				break;
706 			}
707 		}
708 	}
709 
710 	if (image_buf) {
711 		memcpy((char *)&preload_user_data, (char *)data, sizeof(*data));
712 		*resc_buf = (ulong)image_buf;
713 	}
714 
715 	return 0;
716 }
717 
718 /*
719  *		AVB Policy.
720  *
721  * == avb with unlock:
722  * Don't process hash verify.
723  * Go pre-loaded path: Loading vendor_boot and init_boot
724  * directly to where they should be, while loading the
725  * boot/recovery. The boot message tells like:
726  * ···
727  * preloaded: distribute image from 'boot_a'
728  * preloaded: distribute image from 'init_boot_a'
729  * preloaded: distribute image from 'vendor_boot_a'
730  * ···
731  *
732  * == avb with lock:
733  * Process hash verify.
734  * Go pre-loaded path: Loading full vendor_boot, init_boot and
735  * boot/recovery one by one to verify, and distributing them to
736  * where they should be by memcpy at last.
737  *
738  * The three images share a large memory buffer that allocated
739  * by sysmem_alloc(), it locate at high memory address that
740  * just lower than SP bottom. The boot message tells like:
741  * ···
742  * preloaded: full image from 'boot_a' at 0xe47f90c0 - 0xe7a4b0c0
743  * preloaded: full image from 'init_boot_a' at 0xeaff90c0 - 0xeb2950c0
744  * preloaded: full image from 'vendor_boot_a' at 0xe87f90c0 - 0xe9f6e0c0
745  * ···
746  */
747 static AvbSlotVerifyResult android_slot_verify(char *boot_partname,
748 			       unsigned long *android_load_address,
749 			       char *slot_suffix)
750 {
751 	const char *requested_partitions[] = {
752 		boot_partname,
753 		NULL,
754 		NULL,
755 		NULL,
756 	};
757 	struct AvbOpsData *data;
758 	struct blk_desc *dev_desc;
759 	struct andr_img_hdr *hdr;
760 	disk_partition_t part_info;
761 	uint8_t unlocked = true;
762 	AvbOps *ops;
763 	AvbSlotVerifyFlags flags;
764 	AvbSlotVerifyData *slot_data = {NULL};
765 	AvbSlotVerifyResult verify_result;
766 	AvbABData ab_data, ab_data_orig;
767 	size_t slot_index_to_boot = 0;
768 	char verify_state[38] = {0};
769 	char can_boot = 1;
770 	char retry_no_vbmeta_partition = 1;
771 	unsigned long load_address = *android_load_address;
772 	int ret;
773 
774 	dev_desc = rockchip_get_bootdev();
775 	if (!dev_desc)
776 		return AVB_IO_RESULT_ERROR_IO;
777 
778 	if (part_get_info_by_name(dev_desc, boot_partname, &part_info) < 0) {
779 		printf("Could not find \"%s\" partition\n", boot_partname);
780 		return AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION;
781 	}
782 
783 	hdr = populate_andr_img_hdr(dev_desc, &part_info);
784 	if (!hdr) {
785 		printf("No valid android hdr\n");
786 		return AVB_IO_RESULT_ERROR_NO_SUCH_VALUE;
787 	}
788 
789 	if (hdr->header_version >= 4) {
790 		requested_partitions[1] = ANDROID_PARTITION_VENDOR_BOOT;
791 		if (((hdr->os_version >> 25) & 0x7f) >= 13)
792 			requested_partitions[2] = ANDROID_PARTITION_INIT_BOOT;
793 	}
794 
795 	ops = avb_ops_user_new();
796 	if (ops == NULL) {
797 		printf("avb_ops_user_new() failed!\n");
798 		return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
799 	}
800 
801 	if (ops->read_is_device_unlocked(ops, (bool *)&unlocked) != AVB_IO_RESULT_OK)
802 		printf("Error determining whether device is unlocked.\n");
803 
804 	printf("read_is_device_unlocked() ops returned that device is %s\n",
805 	       (unlocked & LOCK_MASK)? "UNLOCKED" : "LOCKED");
806 
807 	flags = AVB_SLOT_VERIFY_FLAGS_NONE;
808 	if (unlocked & LOCK_MASK)
809 		flags |= AVB_SLOT_VERIFY_FLAGS_ALLOW_VERIFICATION_ERROR;
810 
811 	if (load_metadata(ops->ab_ops, &ab_data, &ab_data_orig)) {
812 		printf("Can not load metadata\n");
813 		return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
814 	}
815 
816 	if (!strncmp(slot_suffix, "_a", 2))
817 		slot_index_to_boot = 0;
818 	else if (!strncmp(slot_suffix, "_b", 2))
819 		slot_index_to_boot = 1;
820 	else
821 		slot_index_to_boot = 0;
822 
823 	if (strcmp(boot_partname, ANDROID_PARTITION_RECOVERY) == 0)
824 		flags |= AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION;
825 
826 #ifdef CONFIG_MP_BOOT
827 	preload_user_data.boot.addr = (void *)mpb_post(1);
828 	preload_user_data.boot.size = (size_t)mpb_post(2);
829 #endif
830 
831 	/*
832 	 * Handle the case: "avb lock + (vbus = 0) + recovery key pressed".
833 	 * Check whether required boot_partname is same as preload boot_partition.
834 	 */
835 	if (preload_user_data.boot_partition && strcmp(preload_user_data.boot_partition, boot_partname))
836 		preload_user_data.boot.addr = NULL;
837 
838 	/* use preload one if available */
839 	if (preload_user_data.boot.addr) {
840 		data = (struct AvbOpsData *)(ops->user_data);
841 
842 		data->slot_suffix = slot_suffix;
843 		data->boot = preload_user_data.boot;
844 		data->vendor_boot = preload_user_data.vendor_boot;
845 		data->init_boot = preload_user_data.init_boot;
846 		data->resource = preload_user_data.resource;
847 	} else {
848 		ret = avb_image_distribute_prepare(slot_data, ops, slot_suffix);
849 		if (ret < 0) {
850 			printf("avb image distribute prepare failed %d\n", ret);
851 			return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
852 		}
853 	}
854 
855 retry_verify:
856 	verify_result =
857 	avb_slot_verify(ops,
858 			requested_partitions,
859 			slot_suffix,
860 			flags,
861 			AVB_HASHTREE_ERROR_MODE_RESTART,
862 			&slot_data);
863 	if (verify_result != AVB_SLOT_VERIFY_RESULT_OK &&
864 	    verify_result != AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED) {
865 		if (retry_no_vbmeta_partition && strcmp(boot_partname, ANDROID_PARTITION_RECOVERY) == 0) {
866 			printf("Verify recovery with vbmeta.\n");
867 			flags &= ~AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION;
868 			retry_no_vbmeta_partition = 0;
869 			goto retry_verify;
870 		}
871 	}
872 
873 	strcat(verify_state, ANDROID_VERIFY_STATE);
874 	switch (verify_result) {
875 	case AVB_SLOT_VERIFY_RESULT_OK:
876 		if (unlocked & LOCK_MASK)
877 			strcat(verify_state, "orange");
878 		else
879 			strcat(verify_state, "green");
880 		break;
881 	case AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED:
882 		if (unlocked & LOCK_MASK)
883 			strcat(verify_state, "orange");
884 		else
885 			strcat(verify_state, "yellow");
886 		break;
887 	case AVB_SLOT_VERIFY_RESULT_ERROR_OOM:
888 	case AVB_SLOT_VERIFY_RESULT_ERROR_IO:
889 	case AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA:
890 	case AVB_SLOT_VERIFY_RESULT_ERROR_UNSUPPORTED_VERSION:
891 	case AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION:
892 	case AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX:
893 	default:
894 		if (unlocked & LOCK_MASK)
895 			strcat(verify_state, "orange");
896 		else
897 			strcat(verify_state, "red");
898 		break;
899 	}
900 
901 	if (!slot_data) {
902 		can_boot = 0;
903 		goto out;
904 	}
905 
906 	if (verify_result == AVB_SLOT_VERIFY_RESULT_OK ||
907 	    verify_result == AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED ||
908 	    (unlocked & LOCK_MASK)) {
909 		int len = 0;
910 		char *bootargs, *newbootargs;
911 #ifdef CONFIG_ANDROID_AVB_ROLLBACK_INDEX
912 		if (rk_avb_update_stored_rollback_indexes_for_slot(ops, slot_data))
913 			printf("Fail to update the rollback indexes.\n");
914 #endif
915 		if (slot_data->cmdline) {
916 			debug("Kernel command line: %s\n", slot_data->cmdline);
917 			len += strlen(slot_data->cmdline);
918 		}
919 
920 		bootargs = env_get("bootargs");
921 		if (bootargs)
922 			len += strlen(bootargs);
923 
924 		newbootargs = malloc(len + 2);
925 
926 		if (!newbootargs) {
927 			puts("Error: malloc in android_slot_verify failed!\n");
928 			return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
929 		}
930 		*newbootargs = '\0';
931 
932 		if (bootargs) {
933 			strcpy(newbootargs, bootargs);
934 			strcat(newbootargs, " ");
935 		}
936 		if (slot_data->cmdline)
937 			strcat(newbootargs, slot_data->cmdline);
938 		env_set("bootargs", newbootargs);
939 
940 		/* if need, distribute full image to where they should be */
941 		ret = avb_image_distribute_finish(slot_data, flags, &load_address);
942 		if (ret) {
943 			printf("avb image distribute finish failed %d\n", ret);
944 			return ret;
945 		}
946 		*android_load_address = load_address;
947 	} else {
948 		slot_set_unbootable(&ab_data.slots[slot_index_to_boot]);
949 	}
950 
951 out:
952 	env_update("bootargs", verify_state);
953 	if (save_metadata_if_changed(ops->ab_ops, &ab_data, &ab_data_orig)) {
954 		printf("Can not save metadata\n");
955 		verify_result = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
956 	}
957 
958 	if (slot_data != NULL)
959 		avb_slot_verify_data_free(slot_data);
960 
961 	if ((unlocked & LOCK_MASK) && can_boot)
962 		return 0;
963 	else
964 		return verify_result;
965 }
966 #endif
967 
968 #if defined(CONFIG_OF_LIBFDT_OVERLAY)
969 
970 /*
971  * Default return index 0.
972  */
973 __weak int board_select_fdt_index(ulong dt_table_hdr)
974 {
975 /*
976  * User can use "dt_for_each_entry(entry, hdr, idx)" to iterate
977  * over all dt entry of DT image and pick up which they want.
978  *
979  * Example:
980  *	struct dt_table_entry *entry;
981  *	int index;
982  *
983  *	dt_for_each_entry(entry, dt_table_hdr, index) {
984  *
985  *		.... (use entry)
986  *	}
987  *
988  *	return index;
989  */
990 	return 0;
991 }
992 
993 static int android_get_dtbo(ulong *fdt_dtbo,
994 			    const struct andr_img_hdr *hdr,
995 			    int *index, const char *part_dtbo)
996 {
997 	struct dt_table_header *dt_hdr = NULL;
998 	struct blk_desc *dev_desc;
999 	disk_partition_t part_info;
1000 	u32 blk_offset, blk_cnt;
1001 	void *buf;
1002 	ulong e_addr;
1003 	u32 e_size;
1004 	int e_idx;
1005 	int ret;
1006 
1007 	/* Get partition info */
1008 	dev_desc = rockchip_get_bootdev();
1009 	if (!dev_desc)
1010 		return -ENODEV;
1011 
1012 	ret = part_get_info_by_name(dev_desc, part_dtbo, &part_info);
1013 	if (ret < 0) {
1014 		printf("No %s partition, ret=%d\n", part_dtbo, ret);
1015 		return ret;
1016 	}
1017 
1018 	/* Check dt table header */
1019 	if (!strcmp(part_dtbo, PART_RECOVERY))
1020 		blk_offset = part_info.start +
1021 			     (hdr->recovery_dtbo_offset / part_info.blksz);
1022 	else
1023 		blk_offset = part_info.start;
1024 
1025 	dt_hdr = memalign(ARCH_DMA_MINALIGN, part_info.blksz);
1026 	if (!dt_hdr)
1027 		return -ENOMEM;
1028 
1029 	ret = blk_dread(dev_desc, blk_offset, 1, dt_hdr);
1030 	if (ret != 1)
1031 		goto out1;
1032 
1033 	if (!android_dt_check_header((ulong)dt_hdr)) {
1034 		printf("DTBO: invalid dt table header: 0x%x\n", dt_hdr->magic);
1035 		ret = -EINVAL;
1036 		goto out1;
1037 	}
1038 
1039 #ifdef DEBUG
1040 	android_dt_print_contents((ulong)dt_hdr);
1041 #endif
1042 
1043 	blk_cnt = DIV_ROUND_UP(fdt32_to_cpu(dt_hdr->total_size),
1044 			       part_info.blksz);
1045 	/* Read all DT Image */
1046 	buf = memalign(ARCH_DMA_MINALIGN, part_info.blksz * blk_cnt);
1047 	if (!buf) {
1048 		ret = -ENOMEM;
1049 		goto out1;
1050 	}
1051 
1052 	ret = blk_dread(dev_desc, blk_offset, blk_cnt, buf);
1053 	if (ret != blk_cnt)
1054 		goto out2;
1055 
1056 	e_idx = board_select_fdt_index((ulong)buf);
1057 	if (e_idx < 0) {
1058 		printf("%s: failed to select board fdt index\n", __func__);
1059 		ret = -EINVAL;
1060 		goto out2;
1061 	}
1062 
1063 	ret = android_dt_get_fdt_by_index((ulong)buf, e_idx, &e_addr, &e_size);
1064 	if (!ret) {
1065 		printf("%s: failed to get fdt, index=%d\n", __func__, e_idx);
1066 		ret = -EINVAL;
1067 		goto out2;
1068 	}
1069 
1070 	if (fdt_dtbo)
1071 		*fdt_dtbo = e_addr;
1072 	if (index)
1073 		*index = e_idx;
1074 
1075 	free(dt_hdr);
1076 	debug("ANDROID: Loading dt entry to 0x%lx size 0x%x idx %d from \"%s\" part\n",
1077 	      e_addr, e_size, e_idx, part_dtbo);
1078 
1079 	return 0;
1080 
1081 out2:
1082 	free(buf);
1083 out1:
1084 	free(dt_hdr);
1085 
1086 	return ret;
1087 }
1088 
1089 int android_fdt_overlay_apply(void *fdt_addr)
1090 {
1091 	struct andr_img_hdr *hdr;
1092 	struct blk_desc *dev_desc;
1093 	const char *part_boot = PART_BOOT;
1094 	disk_partition_t part_info;
1095 	char *fdt_backup;
1096 	char *part_dtbo = PART_DTBO;
1097 	char buf[32] = {0};
1098 	ulong fdt_dtbo = -1;
1099 	u32 totalsize;
1100 	int index = -1;
1101 	int ret;
1102 
1103 	if (rockchip_get_boot_mode() == BOOT_MODE_RECOVERY) {
1104 #ifdef CONFIG_ANDROID_AB
1105 		bool can_find_recovery;
1106 
1107 		can_find_recovery = ab_can_find_recovery_part();
1108 		part_boot = can_find_recovery ? PART_RECOVERY : PART_BOOT;
1109 		part_dtbo = can_find_recovery ? PART_RECOVERY : PART_DTBO;
1110 #else
1111 		part_boot = PART_RECOVERY;
1112 		part_dtbo = PART_RECOVERY;
1113 #endif
1114 	}
1115 
1116 	dev_desc = rockchip_get_bootdev();
1117 	if (!dev_desc)
1118 		return -ENODEV;
1119 
1120 	ret = part_get_info_by_name(dev_desc, part_boot, &part_info);
1121 	if (ret < 0)
1122 		return ret;
1123 
1124 	hdr = populate_andr_img_hdr(dev_desc, &part_info);
1125 	if (!hdr)
1126 		return -EINVAL;
1127 #ifdef DEBUG
1128 	android_print_contents(hdr);
1129 #endif
1130 
1131 	/*
1132 	 * Google requires a/b system mandory from Android Header v3 for
1133 	 * google authentication, that means there is not recovery.
1134 	 *
1135 	 * But for the products that don't care about google authentication,
1136 	 * it's not mandory to use a/b system. So that we use the solution:
1137 	 * boot.img(v3+) with recovery(v2).
1138 	 *
1139 	 * [recovery_dtbo fields]
1140 	 *	recovery.img with boot_img_hdr_v1,2:  supported
1141 	 *	recovery.img with boot_img_hdr_v0,3+: illegal
1142 	 */
1143 	if ((hdr->header_version == 0) ||
1144 	    (hdr->header_version >= 3 && !strcmp(part_boot, PART_RECOVERY)))
1145 		goto out;
1146 
1147 	ret = android_get_dtbo(&fdt_dtbo, (void *)hdr, &index, part_dtbo);
1148 	if (!ret) {
1149 		phys_size_t fdt_size;
1150 
1151 		/* Must incease size before overlay */
1152 		fdt_size = fdt_totalsize((void *)fdt_addr) +
1153 				fdt_totalsize((void *)fdt_dtbo);
1154 		if (sysmem_free((phys_addr_t)fdt_addr))
1155 			goto out;
1156 
1157 		if (!sysmem_alloc_base(MEM_FDT_DTBO,
1158 				       (phys_addr_t)fdt_addr,
1159 					fdt_size + CONFIG_SYS_FDT_PAD))
1160 			goto out;
1161 		/*
1162 		 * Backup main fdt in case of being destroyed by
1163 		 * fdt_overlay_apply() when it overlys failed.
1164 		 */
1165 		totalsize = fdt_totalsize(fdt_addr);
1166 		fdt_backup = malloc(totalsize);
1167 		if (!fdt_backup)
1168 			goto out;
1169 
1170 		memcpy(fdt_backup, fdt_addr, totalsize);
1171 		fdt_increase_size(fdt_addr, fdt_totalsize((void *)fdt_dtbo));
1172 		ret = fdt_overlay_apply(fdt_addr, (void *)fdt_dtbo);
1173 		if (!ret) {
1174 			snprintf(buf, 32, "%s%d", "androidboot.dtbo_idx=", index);
1175 			env_update("bootargs", buf);
1176 			printf("ANDROID: fdt overlay OK\n");
1177 		} else {
1178 			memcpy(fdt_addr, fdt_backup, totalsize);
1179 			printf("ANDROID: fdt overlay failed, ret=%d\n", ret);
1180 		}
1181 
1182 		free(fdt_backup);
1183 	}
1184 
1185 out:
1186 	free(hdr);
1187 
1188 	return 0;
1189 }
1190 #endif
1191 
1192 int android_image_load_by_partname(struct blk_desc *dev_desc,
1193 				   const char *boot_partname,
1194 				   unsigned long *load_address)
1195 {
1196 	disk_partition_t boot_part;
1197 	int ret, part_num;
1198 
1199 	part_num = part_get_info_by_name(dev_desc, boot_partname, &boot_part);
1200 	if (part_num < 0) {
1201 		printf("%s: Can't find part: %s\n", __func__, boot_partname);
1202 		return -1;
1203 	}
1204 	debug("ANDROID: Loading kernel from \"%s\", partition %d.\n",
1205 	      boot_part.name, part_num);
1206 
1207 	ret = android_image_load(dev_desc, &boot_part, *load_address, -1UL);
1208 	if (ret < 0) {
1209 		debug("%s: %s part load fail, ret=%d\n",
1210 		      __func__, boot_part.name, ret);
1211 		return ret;
1212 	}
1213 	*load_address = ret;
1214 
1215 	return 0;
1216 }
1217 
1218 int android_bootloader_boot_flow(struct blk_desc *dev_desc,
1219 				 unsigned long load_address)
1220 {
1221 	enum android_boot_mode mode = ANDROID_BOOT_MODE_NORMAL;
1222 	disk_partition_t misc_part_info;
1223 	int part_num;
1224 	char *command_line;
1225 	char slot_suffix[3] = {0};
1226 	const char *mode_cmdline = NULL;
1227 	char *boot_partname = ANDROID_PARTITION_BOOT;
1228 
1229 	/*
1230 	 * 1. Load MISC partition and determine the boot mode
1231 	 *   clear its value for the next boot if needed.
1232 	 */
1233 	part_num = part_get_info_by_name(dev_desc, ANDROID_PARTITION_MISC,
1234 					 &misc_part_info);
1235 	if (part_num < 0) {
1236 		printf("Could not find misc partition\n");
1237 	} else {
1238 #ifdef CONFIG_ANDROID_KEYMASTER_CA
1239 		/* load attestation key from misc partition. */
1240 		load_attestation_key(dev_desc, &misc_part_info);
1241 #endif
1242 
1243 		mode = android_bootloader_load_and_clear_mode(dev_desc,
1244 							      &misc_part_info);
1245 #ifdef CONFIG_RKIMG_BOOTLOADER
1246 		if (mode == ANDROID_BOOT_MODE_NORMAL) {
1247 			if (rockchip_get_boot_mode() == BOOT_MODE_RECOVERY)
1248 				mode = ANDROID_BOOT_MODE_RECOVERY;
1249 		}
1250 #endif
1251 	}
1252 
1253 	printf("ANDROID: reboot reason: \"%s\"\n", android_boot_mode_str(mode));
1254 #ifdef CONFIG_ANDROID_AB
1255 	/* Get current slot_suffix */
1256 	if (ab_get_slot_suffix(slot_suffix))
1257 		return -1;
1258 #endif
1259 	switch (mode) {
1260 	case ANDROID_BOOT_MODE_NORMAL:
1261 		/* In normal mode, we load the kernel from "boot" but append
1262 		 * "skip_initramfs" to the cmdline to make it ignore the
1263 		 * recovery initramfs in the boot partition.
1264 		 */
1265 #ifdef CONFIG_ANDROID_AB
1266 		/*  In A/B, the recovery image is built as boot.img, containing the
1267 		* recovery's ramdisk. Previously, bootloader used the skip_initramfs
1268 		* kernel command line parameter to decide which mode to boot into.
1269 		* For Android >=10 and with dynamic partition support, the bootloader
1270 		* MUST NOT pass skip_initramfs to the kernel command-line.
1271 		* Instead, bootloader should pass androidboot.force_normal_boot=1
1272 		* and then Android's first-stage init in ramdisk
1273 		* will skip recovery and boot normal Android.
1274 		*/
1275 		if (ab_is_support_dynamic_partition(dev_desc)) {
1276 			mode_cmdline = "androidboot.force_normal_boot=1";
1277 		} else {
1278 			mode_cmdline = "skip_initramfs";
1279 		}
1280 #endif
1281 		break;
1282 	case ANDROID_BOOT_MODE_RECOVERY:
1283 		/*
1284 		 * In recovery mode, if have recovery partition, we still boot the
1285 		 * kernel from "recovery". If not, don't skip the initramfs so it
1286 		 * boots to recovery from image in partition "boot".
1287 		 */
1288 #ifdef CONFIG_ANDROID_AB
1289 		boot_partname = ab_can_find_recovery_part() ?
1290 			ANDROID_PARTITION_RECOVERY : ANDROID_PARTITION_BOOT;
1291 #else
1292 		boot_partname = ANDROID_PARTITION_RECOVERY;
1293 #endif
1294 		break;
1295 	case ANDROID_BOOT_MODE_BOOTLOADER:
1296 		/* Bootloader mode enters fastboot. If this operation fails we
1297 		 * simply return since we can't recover from this situation by
1298 		 * switching to another slot.
1299 		 */
1300 		return android_bootloader_boot_bootloader();
1301 	}
1302 
1303 #ifdef CONFIG_ANDROID_AVB
1304 	uint8_t vboot_flag = 0;
1305 	disk_partition_t vbmeta_part_info;
1306 
1307 #ifdef CONFIG_OPTEE_CLIENT
1308 	if (trusty_read_vbootkey_enable_flag(&vboot_flag)) {
1309 		printf("Can't read vboot flag\n");
1310 		return -1;
1311 	}
1312 #endif
1313 	if (vboot_flag) {
1314 		printf("Vboot=1, SecureBoot enabled, AVB verify\n");
1315 		if (android_slot_verify(boot_partname, &load_address,
1316 					slot_suffix)) {
1317 			printf("AVB verify failed\n");
1318 
1319 			return -1;
1320 		}
1321 	} else {
1322 		part_num = part_get_info_by_name(dev_desc,
1323 						 ANDROID_PARTITION_VBMETA,
1324 						 &vbmeta_part_info);
1325 		if (part_num < 0) {
1326 			printf("Not AVB images, AVB skip\n");
1327 			env_update("bootargs",
1328 				   "androidboot.verifiedbootstate=orange");
1329 			if (android_image_load_by_partname(dev_desc,
1330 							   boot_partname,
1331 							   &load_address)) {
1332 				printf("Android image load failed\n");
1333 				return -1;
1334 			}
1335 		} else {
1336 			printf("Vboot=0, AVB images, AVB verify\n");
1337 			if (android_slot_verify(boot_partname, &load_address,
1338 						slot_suffix)) {
1339 				printf("AVB verify failed\n");
1340 
1341 				return -1;
1342 			}
1343 		}
1344 	}
1345 #else
1346 	/*
1347 	 * 2. Load the boot/recovery from the desired "boot" partition.
1348 	 * Determine if this is an AOSP image.
1349 	 */
1350 	if (android_image_load_by_partname(dev_desc,
1351 					   boot_partname,
1352 					   &load_address)) {
1353 		printf("Android image load failed\n");
1354 		return -1;
1355 	}
1356 #endif
1357 
1358 	/* Set Android root variables. */
1359 	env_set_ulong("android_root_devnum", dev_desc->devnum);
1360 	env_set("android_slotsufix", slot_suffix);
1361 
1362 #ifdef CONFIG_FASTBOOT_OEM_UNLOCK
1363 	/* read oem unlock status and attach to bootargs */
1364 	uint8_t unlock = 0;
1365 	TEEC_Result result;
1366 	char oem_unlock[OEM_UNLOCK_ARG_SIZE] = {0};
1367 	result = trusty_read_oem_unlock(&unlock);
1368 	if (result) {
1369 		printf("read oem unlock status with error : 0x%x\n", result);
1370 	} else {
1371 		snprintf(oem_unlock, OEM_UNLOCK_ARG_SIZE, "androidboot.oem_unlocked=%d", unlock);
1372 		env_update("bootargs", oem_unlock);
1373 	}
1374 #endif
1375 
1376 	/* Assemble the command line */
1377 	command_line = android_assemble_cmdline(slot_suffix, mode_cmdline);
1378 	env_update("bootargs", command_line);
1379 
1380 	debug("ANDROID: bootargs: \"%s\"\n", command_line);
1381 
1382 #ifdef CONFIG_SUPPORT_OEM_DTB
1383 	if (android_bootloader_get_fdt(ANDROID_PARTITION_OEM,
1384 				       ANDROID_ARG_FDT_FILENAME)) {
1385 		printf("Can not get the fdt data from oem!\n");
1386 	}
1387 #endif
1388 #ifdef CONFIG_OPTEE_CLIENT
1389 	if (trusty_notify_optee_uboot_end())
1390 		printf("Close optee client failed!\n");
1391 #endif
1392 
1393 #ifdef CONFIG_AMP
1394 	return android_bootloader_boot_kernel(load_address);
1395 #else
1396 	android_bootloader_boot_kernel(load_address);
1397 
1398 	/* TODO: If the kernel doesn't boot mark the selected slot as bad. */
1399 	return -1;
1400 #endif
1401 }
1402 
1403 int android_avb_boot_flow(unsigned long kernel_address)
1404 {
1405 	struct blk_desc *dev_desc;
1406 	disk_partition_t boot_part_info;
1407 	int ret;
1408 
1409 	dev_desc = rockchip_get_bootdev();
1410 	if (!dev_desc) {
1411 		printf("%s: dev_desc is NULL!\n", __func__);
1412 		return -1;
1413 	}
1414 
1415 	/* Load the kernel from the desired "boot" partition. */
1416 	ret = part_get_info_by_name(dev_desc, ANDROID_PARTITION_BOOT,
1417 				    &boot_part_info);
1418 	if (ret < 0) {
1419 		printf("%s: failed to get boot part\n", __func__);
1420 		return ret;
1421 	}
1422 
1423 	ret = android_image_load(dev_desc, &boot_part_info,
1424 				 kernel_address, -1UL);
1425 	if (ret < 0) {
1426 		printf("Android avb boot failed, error %d.\n", ret);
1427 		return ret;
1428 	}
1429 
1430 	android_bootloader_boot_kernel(kernel_address);
1431 
1432 	/* TODO: If the kernel doesn't boot mark the selected slot as bad. */
1433 	return -1;
1434 }
1435 
1436 int android_boot_flow(unsigned long kernel_address)
1437 {
1438 	struct blk_desc *dev_desc;
1439 	disk_partition_t boot_part_info;
1440 	int ret;
1441 
1442 	dev_desc = rockchip_get_bootdev();
1443 	if (!dev_desc) {
1444 		printf("%s: dev_desc is NULL!\n", __func__);
1445 		return -1;
1446 	}
1447 	/* Load the kernel from the desired "boot" partition. */
1448 	ret = part_get_info_by_name(dev_desc, ANDROID_PARTITION_BOOT,
1449 				    &boot_part_info);
1450 	if (ret < 0) {
1451 		printf("%s: failed to get boot part\n", __func__);
1452 		return ret;
1453 	}
1454 
1455 	ret = android_image_load(dev_desc, &boot_part_info, kernel_address,
1456 				 -1UL);
1457 	if (ret < 0)
1458 		return ret;
1459 
1460 	android_bootloader_boot_kernel(kernel_address);
1461 
1462 	/* TODO: If the kernel doesn't boot mark the selected slot as bad. */
1463 	return -1;
1464 }
1465