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