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