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