xref: /rk3399_rockchip-uboot/common/android_bootloader.c (revision d0df954bf3d4978ee3feb94b80ec863063c704cc)
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 
578 		/* ... and decrement tries remaining, if applicable. */
579 		if (!ab_data.slots[slot_index_to_boot].successful_boot &&
580 		    ab_data.slots[slot_index_to_boot].tries_remaining > 0) {
581 			ab_data.slots[slot_index_to_boot].tries_remaining -= 1;
582 		}
583 	} else {
584 		slot_set_unbootable(&ab_data.slots[slot_index_to_boot]);
585 	}
586 
587 out:
588 	env_update("bootargs", verify_state);
589 	if (save_metadata_if_changed(ops->ab_ops, &ab_data, &ab_data_orig)) {
590 		printf("Can not save metadata\n");
591 		verify_result = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
592 	}
593 
594 	if (slot_data[0] != NULL)
595 		avb_slot_verify_data_free(slot_data[0]);
596 
597 	if ((unlocked & LOCK_MASK) && can_boot)
598 		return 0;
599 	else
600 		return verify_result;
601 }
602 #endif
603 
604 #if defined(CONFIG_CMD_DTIMG) && defined(CONFIG_OF_LIBFDT_OVERLAY)
605 
606 /*
607  * Default return index 0.
608  */
609 __weak int board_select_fdt_index(ulong dt_table_hdr)
610 {
611 /*
612  * User can use "dt_for_each_entry(entry, hdr, idx)" to iterate
613  * over all dt entry of DT image and pick up which they want.
614  *
615  * Example:
616  *	struct dt_table_entry *entry;
617  *	int index;
618  *
619  *	dt_for_each_entry(entry, dt_table_hdr, index) {
620  *
621  *		.... (use entry)
622  *	}
623  *
624  *	return index;
625  */
626 	return 0;
627 }
628 
629 static int android_get_dtbo(ulong *fdt_dtbo,
630 			    const struct andr_img_hdr *hdr,
631 			    int *index)
632 {
633 	struct dt_table_header *dt_hdr = NULL;
634 	struct blk_desc *dev_desc;
635 	const char *part_name;
636 	disk_partition_t part_info;
637 	u32 blk_offset, blk_cnt;
638 	void *buf;
639 	ulong e_addr;
640 	u32 e_size;
641 	int e_idx;
642 	int ret;
643 
644 	/* Get partition according to boot mode */
645 	if (rockchip_get_boot_mode() == BOOT_MODE_RECOVERY)
646 		part_name = PART_RECOVERY;
647 	else
648 		part_name = PART_DTBO;
649 
650 	/* Get partition info */
651 	dev_desc = rockchip_get_bootdev();
652 	if (!dev_desc) {
653 		printf("%s: dev_desc is NULL!\n", __func__);
654 		return -ENODEV;
655 	}
656 
657 	ret = part_get_info_by_name(dev_desc, part_name, &part_info);
658 	if (ret < 0) {
659 		printf("%s: failed to get %s part info, ret=%d\n",
660 		       __func__, part_name, ret);
661 		return ret;
662 	}
663 
664 	/* Check dt table header */
665 	if (!strcmp(part_name, PART_RECOVERY))
666 		blk_offset = part_info.start +
667 			     (hdr->recovery_dtbo_offset / part_info.blksz);
668 	else
669 		blk_offset = part_info.start;
670 
671 	dt_hdr = memalign(ARCH_DMA_MINALIGN, part_info.blksz);
672 	if (!dt_hdr) {
673 		printf("%s: out of memory for dt header!\n", __func__);
674 		return -ENOMEM;
675 	}
676 
677 	ret = blk_dread(dev_desc, blk_offset, 1, dt_hdr);
678 	if (ret != 1) {
679 		printf("%s: failed to read dt table header\n",
680 		       __func__);
681 		goto out1;
682 	}
683 
684 	if (!android_dt_check_header((ulong)dt_hdr)) {
685 		printf("%s: Error: invalid dt table header: 0x%x\n",
686 		       __func__, dt_hdr->magic);
687 		ret = -EINVAL;
688 		goto out1;
689 	}
690 
691 #ifdef DEBUG
692 	android_dt_print_contents((ulong)dt_hdr);
693 #endif
694 
695 	blk_cnt = DIV_ROUND_UP(fdt32_to_cpu(dt_hdr->total_size),
696 			       part_info.blksz);
697 	/* Read all DT Image */
698 	buf = memalign(ARCH_DMA_MINALIGN, part_info.blksz * blk_cnt);
699 	if (!buf) {
700 		printf("%s: out of memory for %s part!\n", __func__, part_name);
701 		ret = -ENOMEM;
702 		goto out1;
703 	}
704 
705 	ret = blk_dread(dev_desc, blk_offset, blk_cnt, buf);
706 	if (ret != blk_cnt) {
707 		printf("%s: failed to read dtbo, blk_cnt=%d, ret=%d\n",
708 		       __func__, blk_cnt, ret);
709 		goto out2;
710 	}
711 
712 	e_idx = board_select_fdt_index((ulong)buf);
713 	if (e_idx < 0) {
714 		printf("%s: failed to select board fdt index\n", __func__);
715 		ret = -EINVAL;
716 		goto out2;
717 	}
718 
719 	ret = android_dt_get_fdt_by_index((ulong)buf, e_idx, &e_addr, &e_size);
720 	if (!ret) {
721 		printf("%s: failed to get fdt, index=%d\n", __func__, e_idx);
722 		ret = -EINVAL;
723 		goto out2;
724 	}
725 
726 	if (fdt_dtbo)
727 		*fdt_dtbo = e_addr;
728 	if (index)
729 		*index = e_idx;
730 
731 	free(dt_hdr);
732 	debug("ANDROID: Loading dt entry to 0x%lx size 0x%x idx %d from \"%s\" part\n",
733 	      e_addr, e_size, e_idx, part_name);
734 
735 	return 0;
736 
737 out2:
738 	free(buf);
739 out1:
740 	free(dt_hdr);
741 
742 	return ret;
743 }
744 
745 int android_fdt_overlay_apply(void *fdt_addr)
746 {
747 	struct andr_img_hdr *hdr;
748 	struct blk_desc *dev_desc;
749 	const char *part_name;
750 	disk_partition_t part_info;
751 	char buf[32] = {0};
752 	u32 blk_cnt;
753 	ulong fdt_dtbo = -1;
754 	int index = -1;
755 	int ret;
756 
757 	/* Get partition according to boot mode */
758 	if (rockchip_get_boot_mode() == BOOT_MODE_RECOVERY)
759 		part_name = PART_RECOVERY;
760 	else
761 		part_name = PART_BOOT;
762 
763 	/* Get partition info */
764 	dev_desc = rockchip_get_bootdev();
765 	if (!dev_desc) {
766 		printf("%s: dev_desc is NULL!\n", __func__);
767 		return -ENODEV;
768 	}
769 
770 	ret = part_get_info_by_name(dev_desc, part_name, &part_info);
771 	if (ret < 0) {
772 		printf("%s: failed to get %s part info, ret=%d\n",
773 		       __func__, part_name, ret);
774 		return ret;
775 	}
776 
777 	blk_cnt = DIV_ROUND_UP(sizeof(*hdr), part_info.blksz);
778 	hdr = memalign(ARCH_DMA_MINALIGN, part_info.blksz * blk_cnt);
779 	if (!hdr) {
780 		printf("%s: out of memory!\n", __func__);
781 		return -ENOMEM;
782 	}
783 
784 	ret = blk_dread(dev_desc, part_info.start, blk_cnt, hdr);
785 	if (ret != blk_cnt) {
786 		printf("%s: failed to read %s hdr!\n", __func__, part_name);
787 		goto out;
788 	}
789 
790 #ifdef DEBUG
791 	android_print_contents(hdr);
792 #endif
793 
794 	if (android_image_check_header(hdr)) {
795 		printf("%s: Invalid Android header %s\n", __func__, hdr->magic);
796 		return -EINVAL;
797 	}
798 
799 	/* Check header version */
800 	if (!hdr->header_version) {
801 		printf("Android header version 0\n");
802 		ret = -EINVAL;
803 		goto out;
804 	}
805 
806 	ret = android_get_dtbo(&fdt_dtbo, (void *)hdr, &index);
807 	if (!ret) {
808 		phys_size_t fdt_size;
809 		/* Must incease size before overlay */
810 		fdt_size = fdt_totalsize((void *)fdt_addr) +
811 				fdt_totalsize((void *)fdt_dtbo);
812 		if (sysmem_free((phys_addr_t)fdt_addr))
813 			goto out;
814 		if (!sysmem_alloc_base("fdt(dtbo)",
815 				       (phys_addr_t)fdt_addr,
816 					fdt_size))
817 			goto out;
818 		fdt_increase_size(fdt_addr, fdt_totalsize((void *)fdt_dtbo));
819 		ret = fdt_overlay_apply(fdt_addr, (void *)fdt_dtbo);
820 		if (!ret) {
821 			snprintf(buf, 32, "%s%d", "androidboot.dtbo_idx=", index);
822 			env_update("bootargs", buf);
823 			printf("ANDROID: fdt overlay OK\n");
824 		} else {
825 			printf("ANDROID: fdt overlay failed, ret=%d\n", ret);
826 		}
827 	}
828 
829 out:
830 	free(hdr);
831 
832 	return 0;
833 }
834 #endif
835 
836 static int load_android_image(struct blk_desc *dev_desc,
837 			      char *boot_partname,
838 			      char *slot_suffix,
839 			      unsigned long *load_address)
840 {
841 	disk_partition_t boot_part;
842 	int ret, part_num;
843 
844 	part_num = android_part_get_info_by_name_suffix(dev_desc,
845 							boot_partname,
846 							slot_suffix,
847 							&boot_part);
848 	if (part_num < 0) {
849 		printf("%s: Can't find part: %s\n", __func__, boot_partname);
850 		return -1;
851 	}
852 	debug("ANDROID: Loading kernel from \"%s\", partition %d.\n",
853 	      boot_part.name, part_num);
854 
855 	ret = android_image_load(dev_desc, &boot_part, *load_address, -1UL);
856 	if (ret < 0) {
857 		debug("%s: %s part load fail, ret=%d\n",
858 		      __func__, boot_part.name, ret);
859 		return ret;
860 	}
861 	*load_address = ret;
862 
863 	return 0;
864 }
865 
866 static bool avb_enabled;
867 void android_avb_set_enabled(bool enable)
868 {
869 	avb_enabled = enable;
870 }
871 
872 bool android_avb_is_enabled(void)
873 {
874 	return avb_enabled;
875 }
876 
877 int android_bootloader_boot_flow(struct blk_desc *dev_desc,
878 				 unsigned long load_address)
879 {
880 	enum android_boot_mode mode;
881 	disk_partition_t misc_part_info;
882 	int part_num;
883 	int ret;
884 	char *command_line;
885 	char slot_suffix[3] = {0};
886 	const char *mode_cmdline = NULL;
887 	char *boot_partname = ANDROID_PARTITION_BOOT;
888 	ulong fdt_addr;
889 
890 	/*
891 	 * 1. Load MISC partition and determine the boot mode
892 	 *   clear its value for the next boot if needed.
893 	 */
894 	part_num = part_get_info_by_name(dev_desc, ANDROID_PARTITION_MISC,
895 					 &misc_part_info);
896 	if (part_num < 0)
897 		printf("%s Could not find misc partition\n", __func__);
898 
899 #ifdef CONFIG_ANDROID_KEYMASTER_CA
900 	/* load attestation key from misc partition. */
901 	load_attestation_key(dev_desc, &misc_part_info);
902 #endif
903 
904 	mode = android_bootloader_load_and_clear_mode(dev_desc, &misc_part_info);
905 #ifdef CONFIG_RKIMG_BOOTLOADER
906 	if (mode == ANDROID_BOOT_MODE_NORMAL) {
907 		if (rockchip_get_boot_mode() == BOOT_MODE_RECOVERY)
908 			mode = ANDROID_BOOT_MODE_RECOVERY;
909 	}
910 #endif
911 	printf("ANDROID: reboot reason: \"%s\"\n", android_boot_mode_str(mode));
912 
913 #ifdef CONFIG_ANDROID_AB
914 	/*TODO: get from pre-loader or misc partition*/
915 	if (rk_avb_get_current_slot(slot_suffix))
916 		return -1;
917 
918 	if (slot_suffix[0] != '_') {
919 		printf("There is no bootable slot!\n");
920 		return -1;
921 	}
922 #endif
923 
924 	switch (mode) {
925 	case ANDROID_BOOT_MODE_NORMAL:
926 		/* In normal mode, we load the kernel from "boot" but append
927 		 * "skip_initramfs" to the cmdline to make it ignore the
928 		 * recovery initramfs in the boot partition.
929 		 */
930 #if defined(CONFIG_ANDROID_AB) && !defined(CONFIG_ANDROID_AVB)
931 		char root_partition[20] = {0};
932 		char guid_buf[UUID_SIZE] = {0};
933 		char root_partuuid[70] = "root=PARTUUID=";
934 
935 		strcat(root_partition, ANDROID_PARTITION_SYSTEM);
936 		strcat(root_partition, slot_suffix);
937 		get_partition_unique_uuid(root_partition, guid_buf, UUID_SIZE);
938 		strcat(root_partuuid, guid_buf);
939 		env_update("bootargs", root_partuuid);
940 #endif
941 
942 #ifdef CONFIG_ANDROID_AB
943 		mode_cmdline = "skip_initramfs";
944 #endif
945 		break;
946 	case ANDROID_BOOT_MODE_RECOVERY:
947 		/* In recovery mode we still boot the kernel from "boot" but
948 		 * don't skip the initramfs so it boots to recovery.
949 		 */
950 #ifndef CONFIG_ANDROID_AB
951 		boot_partname = ANDROID_PARTITION_RECOVERY;
952 #endif
953 		break;
954 	case ANDROID_BOOT_MODE_BOOTLOADER:
955 		/* Bootloader mode enters fastboot. If this operation fails we
956 		 * simply return since we can't recover from this situation by
957 		 * switching to another slot.
958 		 */
959 		return android_bootloader_boot_bootloader();
960 	}
961 
962 #ifdef CONFIG_ANDROID_AVB
963 	uint8_t vboot_flag = 0;
964 	char vbmeta_partition[9] = {0};
965 	disk_partition_t vbmeta_part_info;
966 
967 	if (trusty_read_vbootkey_enable_flag(&vboot_flag))
968 		return -1;
969 
970 	if (vboot_flag) {
971 		printf("SecureBoot enabled, AVB verify\n");
972 		android_avb_set_enabled(true);
973 		if (android_slot_verify(boot_partname, &load_address,
974 					slot_suffix))
975 			return -1;
976 	} else {
977 		strcat(vbmeta_partition, ANDROID_PARTITION_VBMETA);
978 		strcat(vbmeta_partition, slot_suffix);
979 		part_num = part_get_info_by_name(dev_desc, vbmeta_partition,
980 						 &vbmeta_part_info);
981 		if (part_num < 0) {
982 			printf("SecureBoot disabled, AVB skip\n");
983 			env_update("bootargs",
984 				   "androidboot.verifiedbootstate=orange");
985 			android_avb_set_enabled(false);
986 			if (load_android_image(dev_desc, boot_partname,
987 					       slot_suffix, &load_address))
988 				return -1;
989 		} else {
990 			printf("SecureBoot enabled, AVB verify\n");
991 			android_avb_set_enabled(true);
992 			if (android_slot_verify(boot_partname, &load_address,
993 						slot_suffix))
994 				return -1;
995 		}
996 	}
997 #else
998 	/*
999 	 * 2. Load the boot/recovery from the desired "boot" partition.
1000 	 * Determine if this is an AOSP image.
1001 	 */
1002 	if (load_android_image(dev_desc, boot_partname,
1003 			       slot_suffix, &load_address))
1004 		return -1;
1005 #endif
1006 
1007 	/* Set Android root variables. */
1008 	env_set_ulong("android_root_devnum", dev_desc->devnum);
1009 	env_set("android_slotsufix", slot_suffix);
1010 
1011 #ifdef CONFIG_FASTBOOT_OEM_UNLOCK
1012 	/* read oem unlock status and attach to bootargs */
1013 	uint8_t unlock = 0;
1014 	TEEC_Result result;
1015 	char oem_unlock[OEM_UNLOCK_ARG_SIZE] = {0};
1016 	result = trusty_read_oem_unlock(&unlock);
1017 	if (result) {
1018 		printf("read oem unlock status with error : 0x%x\n", result);
1019 	} else {
1020 		snprintf(oem_unlock, OEM_UNLOCK_ARG_SIZE, "androidboot.oem_unlocked=%d", unlock);
1021 		env_update("bootargs", oem_unlock);
1022 	}
1023 #endif
1024 
1025 	/* Assemble the command line */
1026 	command_line = android_assemble_cmdline(slot_suffix, mode_cmdline);
1027 	env_update("bootargs", command_line);
1028 
1029 	debug("ANDROID: bootargs: \"%s\"\n", command_line);
1030 
1031 #ifdef CONFIG_SUPPORT_OEM_DTB
1032 	if (android_bootloader_get_fdt(ANDROID_PARTITION_OEM,
1033 				       ANDROID_ARG_FDT_FILENAME)) {
1034 		printf("Can not get the fdt data from oem!\n");
1035 	}
1036 #else
1037 	ret = android_image_get_fdt((void *)load_address, &fdt_addr);
1038 	if (!ret)
1039 		env_set_hex("fdt_addr", fdt_addr);
1040 #endif
1041 	android_bootloader_boot_kernel(load_address);
1042 
1043 	/* TODO: If the kernel doesn't boot mark the selected slot as bad. */
1044 	return -1;
1045 }
1046 
1047 int android_avb_boot_flow(char *slot_suffix, unsigned long kernel_address)
1048 {
1049 	struct blk_desc *dev_desc;
1050 	disk_partition_t boot_part_info;
1051 	int ret;
1052 	dev_desc = rockchip_get_bootdev();
1053 	if (!dev_desc) {
1054 		printf("%s: dev_desc is NULL!\n", __func__);
1055 		return -1;
1056 	}
1057 	/* Load the kernel from the desired "boot" partition. */
1058 	android_part_get_info_by_name_suffix(dev_desc,
1059 					     ANDROID_PARTITION_BOOT,
1060 					     slot_suffix, &boot_part_info);
1061 	ret = android_image_load(dev_desc, &boot_part_info, kernel_address,
1062 				 -1UL);
1063 	if (ret < 0)
1064 		return ret;
1065 	android_bootloader_boot_kernel(kernel_address);
1066 
1067 	/* TODO: If the kernel doesn't boot mark the selected slot as bad. */
1068 	return -1;
1069 }
1070 
1071 int android_boot_flow(unsigned long kernel_address)
1072 {
1073 	struct blk_desc *dev_desc;
1074 	disk_partition_t boot_part_info;
1075 	int ret;
1076 	dev_desc = rockchip_get_bootdev();
1077 	if (!dev_desc) {
1078 		printf("%s: dev_desc is NULL!\n", __func__);
1079 		return -1;
1080 	}
1081 	/* Load the kernel from the desired "boot" partition. */
1082 	part_get_info_by_name(dev_desc, ANDROID_PARTITION_BOOT, &boot_part_info);
1083 	ret = android_image_load(dev_desc, &boot_part_info, kernel_address,
1084 				 -1UL);
1085 	if (ret < 0)
1086 		return ret;
1087 	android_bootloader_boot_kernel(kernel_address);
1088 
1089 	/* TODO: If the kernel doesn't boot mark the selected slot as bad. */
1090 	return -1;
1091 }
1092