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