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