xref: /rk3399_rockchip-uboot/common/android_bootloader.c (revision 2c6a058b7ea25398013cb25b4e3bb96fe40da1a5)
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 	char kernel_addr_str[12];
304 	char *fdt_addr = env_get("fdt_addr");
305 	char *bootm_args[] = {
306 		"bootm", kernel_addr_str, kernel_addr_str, fdt_addr, NULL };
307 
308 	sprintf(kernel_addr_str, "0x%lx", kernel_address);
309 
310 	printf("Booting kernel at %s with fdt at %s...\n\n\n",
311 	       kernel_addr_str, fdt_addr);
312 	do_bootm(NULL, 0, 4, bootm_args);
313 
314 	return -1;
315 }
316 
317 static char *strjoin(const char **chunks, char separator)
318 {
319 	int len, joined_len = 0;
320 	char *ret, *current;
321 	const char **p;
322 
323 	for (p = chunks; *p; p++)
324 		joined_len += strlen(*p) + 1;
325 
326 	if (!joined_len) {
327 		ret = malloc(1);
328 		if (ret)
329 			ret[0] = '\0';
330 		return ret;
331 	}
332 
333 	ret = malloc(joined_len);
334 	current = ret;
335 	if (!ret)
336 		return ret;
337 
338 	for (p = chunks; *p; p++) {
339 		len = strlen(*p);
340 		memcpy(current, *p, len);
341 		current += len;
342 		*current = separator;
343 		current++;
344 	}
345 	/* Replace the last separator by a \0. */
346 	current[-1] = '\0';
347 	return ret;
348 }
349 
350 /** android_assemble_cmdline - Assemble the command line to pass to the kernel
351  * @return a newly allocated string
352  */
353 char *android_assemble_cmdline(const char *slot_suffix,
354 				      const char *extra_args)
355 {
356 	const char *cmdline_chunks[16];
357 	const char **current_chunk = cmdline_chunks;
358 	char *env_cmdline, *cmdline, *rootdev_input, *serialno;
359 	char *allocated_suffix = NULL;
360 	char *allocated_serialno = NULL;
361 	char *allocated_rootdev = NULL;
362 	unsigned long rootdev_len;
363 
364 	env_cmdline = env_get("bootargs");
365 	if (env_cmdline)
366 		*(current_chunk++) = env_cmdline;
367 
368 	/* The |slot_suffix| needs to be passed to the kernel to know what
369 	 * slot to boot from.
370 	 */
371 	if (slot_suffix) {
372 		allocated_suffix = malloc(strlen(ANDROID_ARG_SLOT_SUFFIX) +
373 					  strlen(slot_suffix) + 1);
374 		memset(allocated_suffix, 0, strlen(ANDROID_ARG_SLOT_SUFFIX)
375 		       + strlen(slot_suffix) + 1);
376 		strcpy(allocated_suffix, ANDROID_ARG_SLOT_SUFFIX);
377 		strcat(allocated_suffix, slot_suffix);
378 		*(current_chunk++) = allocated_suffix;
379 	}
380 
381 	serialno = env_get("serial#");
382 	if (serialno) {
383 		allocated_serialno = malloc(strlen(ANDROID_ARG_SERIALNO) +
384 					  strlen(serialno) + 1);
385 		memset(allocated_serialno, 0, strlen(ANDROID_ARG_SERIALNO) +
386 				strlen(serialno) + 1);
387 		strcpy(allocated_serialno, ANDROID_ARG_SERIALNO);
388 		strcat(allocated_serialno, serialno);
389 		*(current_chunk++) = allocated_serialno;
390 	}
391 
392 	rootdev_input = env_get("android_rootdev");
393 	if (rootdev_input) {
394 		rootdev_len = strlen(ANDROID_ARG_ROOT) + CONFIG_SYS_CBSIZE + 1;
395 		allocated_rootdev = malloc(rootdev_len);
396 		strcpy(allocated_rootdev, ANDROID_ARG_ROOT);
397 		cli_simple_process_macros(rootdev_input,
398 					  allocated_rootdev +
399 					  strlen(ANDROID_ARG_ROOT));
400 		/* Make sure that the string is null-terminated since the
401 		 * previous could not copy to the end of the input string if it
402 		 * is too big.
403 		 */
404 		allocated_rootdev[rootdev_len - 1] = '\0';
405 		*(current_chunk++) = allocated_rootdev;
406 	}
407 
408 	if (extra_args)
409 		*(current_chunk++) = extra_args;
410 
411 	*(current_chunk++) = NULL;
412 	cmdline = strjoin(cmdline_chunks, ' ');
413 	free(allocated_suffix);
414 	free(allocated_rootdev);
415 	return cmdline;
416 }
417 
418 #ifdef CONFIG_ANDROID_AVB
419 static void slot_set_unbootable(AvbABSlotData* slot)
420 {
421 	slot->priority = 0;
422 	slot->tries_remaining = 0;
423 	slot->successful_boot = 0;
424 }
425 
426 static AvbSlotVerifyResult android_slot_verify(char *boot_partname,
427 			       unsigned long *android_load_address,
428 			       char *slot_suffix)
429 {
430 	const char *requested_partitions[1] = {NULL};
431 	uint8_t unlocked = true;
432 	AvbOps *ops;
433 	AvbSlotVerifyFlags flags;
434 	AvbSlotVerifyData *slot_data[1] = {NULL};
435 	AvbSlotVerifyResult verify_result;
436 	AvbABData ab_data, ab_data_orig;
437 	size_t slot_index_to_boot = 0;
438 	char verify_state[38] = {0};
439 	char can_boot = 1;
440 	unsigned long load_address = *android_load_address;
441 	struct andr_img_hdr *hdr;
442 
443 	requested_partitions[0] = boot_partname;
444 	ops = avb_ops_user_new();
445 	if (ops == NULL) {
446 		printf("avb_ops_user_new() failed!\n");
447 		return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
448 	}
449 
450 	if (ops->read_is_device_unlocked(ops, (bool *)&unlocked) != AVB_IO_RESULT_OK)
451 		printf("Error determining whether device is unlocked.\n");
452 
453 	printf("read_is_device_unlocked() ops returned that device is %s\n",
454 	       (unlocked & LOCK_MASK)? "UNLOCKED" : "LOCKED");
455 
456 	flags = AVB_SLOT_VERIFY_FLAGS_NONE;
457 	if (unlocked & LOCK_MASK)
458 		flags |= AVB_SLOT_VERIFY_FLAGS_ALLOW_VERIFICATION_ERROR;
459 
460 	if(load_metadata(ops->ab_ops, &ab_data, &ab_data_orig)) {
461 		printf("Can not load metadata\n");
462 		return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
463 	}
464 
465 	if (strncmp(slot_suffix, "_a", 2))
466 		slot_index_to_boot = 0;
467 	else if(strncmp(slot_suffix, "_b", 2))
468 		slot_index_to_boot = 1;
469 	else
470 		slot_index_to_boot = 0;
471 
472 	verify_result =
473 	avb_slot_verify(ops,
474 			requested_partitions,
475 			slot_suffix,
476 			flags,
477 			AVB_HASHTREE_ERROR_MODE_RESTART_AND_INVALIDATE,
478 			&slot_data[0]);
479 
480 	strcat(verify_state, ANDROID_VERIFY_STATE);
481 	switch (verify_result) {
482 	case AVB_SLOT_VERIFY_RESULT_OK:
483 		if (unlocked & LOCK_MASK)
484 			strcat(verify_state, "orange");
485 		else
486 			strcat(verify_state, "green");
487 		break;
488 	case AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED:
489 		if (unlocked & LOCK_MASK)
490 			strcat(verify_state, "orange");
491 		else
492 			strcat(verify_state, "yellow");
493 		break;
494 	case AVB_SLOT_VERIFY_RESULT_ERROR_OOM:
495 	case AVB_SLOT_VERIFY_RESULT_ERROR_IO:
496 	case AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA:
497 	case AVB_SLOT_VERIFY_RESULT_ERROR_UNSUPPORTED_VERSION:
498 	case AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION:
499 	case AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX:
500 	default:
501 		if (unlocked & LOCK_MASK)
502 			strcat(verify_state, "orange");
503 		else
504 			strcat(verify_state, "red");
505 		break;
506 	}
507 
508 	if (!slot_data[0]) {
509 		can_boot = 0;
510 		goto out;
511 	}
512 
513 	if (verify_result == AVB_SLOT_VERIFY_RESULT_OK ||
514 	    verify_result == AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED ||
515 	    (unlocked & LOCK_MASK)) {
516 		int len = 0;
517 		char *bootargs, *newbootargs;
518 
519 		if (*slot_data[0]->cmdline) {
520 			debug("Kernel command line: %s\n", slot_data[0]->cmdline);
521 			len += strlen(slot_data[0]->cmdline);
522 		}
523 
524 		bootargs = env_get("bootargs");
525 		if (bootargs)
526 			len += strlen(bootargs);
527 
528 		newbootargs = malloc(len + 2);
529 
530 		if (!newbootargs) {
531 			puts("Error: malloc in android_slot_verify failed!\n");
532 			return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
533 		}
534 		*newbootargs = '\0';
535 
536 		if (bootargs) {
537 			strcpy(newbootargs, bootargs);
538 			strcat(newbootargs, " ");
539 		}
540 		if (*slot_data[0]->cmdline)
541 			strcat(newbootargs, slot_data[0]->cmdline);
542 		env_set("bootargs", newbootargs);
543 
544 		/* Reserve page_size */
545 		hdr = (void *)slot_data[0]->loaded_partitions->data;
546 		load_address -= hdr->page_size;
547 		*android_load_address = load_address;
548 
549 		memcpy((uint8_t *)load_address,
550 		       slot_data[0]->loaded_partitions->data,
551 		       slot_data[0]->loaded_partitions->data_size);
552 
553 		/* ... and decrement tries remaining, if applicable. */
554 		if (!ab_data.slots[slot_index_to_boot].successful_boot &&
555 		    ab_data.slots[slot_index_to_boot].tries_remaining > 0) {
556 			ab_data.slots[slot_index_to_boot].tries_remaining -= 1;
557 		}
558 	} else {
559 		slot_set_unbootable(&ab_data.slots[slot_index_to_boot]);
560 	}
561 
562 out:
563 	env_update("bootargs", verify_state);
564 	if (save_metadata_if_changed(ops->ab_ops, &ab_data, &ab_data_orig)) {
565 		printf("Can not save metadata\n");
566 		verify_result = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
567 	}
568 
569 	if (slot_data[0] != NULL)
570 		avb_slot_verify_data_free(slot_data[0]);
571 
572 	if ((unlocked & LOCK_MASK) && can_boot)
573 		return 0;
574 	else
575 		return verify_result;
576 }
577 #endif
578 
579 #if defined(CONFIG_CMD_DTIMG) && defined(CONFIG_OF_LIBFDT_OVERLAY)
580 
581 /*
582  * Default return index 0.
583  */
584 __weak int board_select_fdt_index(ulong dt_table_hdr)
585 {
586 /*
587  * User can use "dt_for_each_entry(entry, hdr, idx)" to iterate
588  * over all dt entry of DT image and pick up which they want.
589  *
590  * Example:
591  *	struct dt_table_entry *entry;
592  *	int index;
593  *
594  *	dt_for_each_entry(entry, dt_table_hdr, index) {
595  *
596  *		.... (use entry)
597  *	}
598  *
599  *	return index;
600  */
601 	return 0;
602 }
603 
604 static int android_get_dtbo(ulong *fdt_dtbo,
605 			    const struct andr_img_hdr *hdr,
606 			    int *index)
607 {
608 	struct dt_table_header *dt_hdr = NULL;
609 	struct blk_desc *dev_desc;
610 	const char *part_name;
611 	disk_partition_t part_info;
612 	u32 blk_offset, blk_cnt;
613 	void *buf;
614 	ulong e_addr;
615 	u32 e_size;
616 	int e_idx;
617 	int ret;
618 
619 	/* Get partition according to boot mode */
620 	if (rockchip_get_boot_mode() == BOOT_MODE_RECOVERY)
621 		part_name = PART_RECOVERY;
622 	else
623 		part_name = PART_DTBO;
624 
625 	/* Get partition info */
626 	dev_desc = rockchip_get_bootdev();
627 	if (!dev_desc) {
628 		printf("%s: dev_desc is NULL!\n", __func__);
629 		return -ENODEV;
630 	}
631 
632 	ret = part_get_info_by_name(dev_desc, part_name, &part_info);
633 	if (ret < 0) {
634 		printf("%s: failed to get %s part info, ret=%d\n",
635 		       __func__, part_name, ret);
636 		return ret;
637 	}
638 
639 	/* Check dt table header */
640 	if (!strcmp(part_name, PART_RECOVERY))
641 		blk_offset = part_info.start +
642 			     (hdr->recovery_dtbo_offset / part_info.blksz);
643 	else
644 		blk_offset = part_info.start;
645 
646 	dt_hdr = memalign(ARCH_DMA_MINALIGN, part_info.blksz);
647 	if (!dt_hdr) {
648 		printf("%s: out of memory for dt header!\n", __func__);
649 		return -ENOMEM;
650 	}
651 
652 	ret = blk_dread(dev_desc, blk_offset, 1, dt_hdr);
653 	if (ret != 1) {
654 		printf("%s: failed to read dt table header\n",
655 		       __func__);
656 		goto out1;
657 	}
658 
659 	if (!android_dt_check_header((ulong)dt_hdr)) {
660 		printf("%s: Error: invalid dt table header: 0x%x\n",
661 		       __func__, dt_hdr->magic);
662 		ret = -EINVAL;
663 		goto out1;
664 	}
665 
666 #ifdef DEBUG
667 	android_dt_print_contents((ulong)dt_hdr);
668 #endif
669 
670 	blk_cnt = DIV_ROUND_UP(fdt32_to_cpu(dt_hdr->total_size),
671 			       part_info.blksz);
672 	/* Read all DT Image */
673 	buf = memalign(ARCH_DMA_MINALIGN, part_info.blksz * blk_cnt);
674 	if (!buf) {
675 		printf("%s: out of memory for %s part!\n", __func__, part_name);
676 		ret = -ENOMEM;
677 		goto out1;
678 	}
679 
680 	ret = blk_dread(dev_desc, blk_offset, blk_cnt, buf);
681 	if (ret != blk_cnt) {
682 		printf("%s: failed to read dtbo, blk_cnt=%d, ret=%d\n",
683 		       __func__, blk_cnt, ret);
684 		goto out2;
685 	}
686 
687 	e_idx = board_select_fdt_index((ulong)buf);
688 	if (e_idx < 0) {
689 		printf("%s: failed to select board fdt index\n", __func__);
690 		ret = -EINVAL;
691 		goto out2;
692 	}
693 
694 	ret = android_dt_get_fdt_by_index((ulong)buf, e_idx, &e_addr, &e_size);
695 	if (!ret) {
696 		printf("%s: failed to get fdt, index=%d\n", __func__, e_idx);
697 		ret = -EINVAL;
698 		goto out2;
699 	}
700 
701 	if (fdt_dtbo)
702 		*fdt_dtbo = e_addr;
703 	if (index)
704 		*index = e_idx;
705 
706 	free(dt_hdr);
707 	debug("ANDROID: Loading dt entry to 0x%lx size 0x%x idx %d from \"%s\" part\n",
708 	      e_addr, e_size, e_idx, part_name);
709 
710 	return 0;
711 
712 out2:
713 	free(buf);
714 out1:
715 	free(dt_hdr);
716 
717 	return ret;
718 }
719 
720 int android_fdt_overlay_apply(void *fdt_addr)
721 {
722 	struct andr_img_hdr *hdr;
723 	struct blk_desc *dev_desc;
724 	const char *part_name;
725 	disk_partition_t part_info;
726 	char buf[32] = {0};
727 	u32 blk_cnt;
728 	ulong fdt_dtbo = -1;
729 	int index = -1;
730 	int ret;
731 
732 	/* Get partition according to boot mode */
733 	if (rockchip_get_boot_mode() == BOOT_MODE_RECOVERY)
734 		part_name = PART_RECOVERY;
735 	else
736 		part_name = PART_BOOT;
737 
738 	/* Get partition info */
739 	dev_desc = rockchip_get_bootdev();
740 	if (!dev_desc) {
741 		printf("%s: dev_desc is NULL!\n", __func__);
742 		return -ENODEV;
743 	}
744 
745 	ret = part_get_info_by_name(dev_desc, part_name, &part_info);
746 	if (ret < 0) {
747 		printf("%s: failed to get %s part info, ret=%d\n",
748 		       __func__, part_name, ret);
749 		return ret;
750 	}
751 
752 	blk_cnt = DIV_ROUND_UP(sizeof(*hdr), part_info.blksz);
753 	hdr = memalign(ARCH_DMA_MINALIGN, part_info.blksz * blk_cnt);
754 	if (!hdr) {
755 		printf("%s: out of memory!\n", __func__);
756 		return -ENOMEM;
757 	}
758 
759 	ret = blk_dread(dev_desc, part_info.start, blk_cnt, hdr);
760 	if (ret != blk_cnt) {
761 		printf("%s: failed to read %s hdr!\n", __func__, part_name);
762 		goto out;
763 	}
764 
765 #ifdef DEBUG
766 	android_print_contents(hdr);
767 #endif
768 
769 	if (android_image_check_header(hdr)) {
770 		printf("%s: Invalid Android header %s\n", __func__, hdr->magic);
771 		return -EINVAL;
772 	}
773 
774 	/* Check header version */
775 	if (!hdr->header_version) {
776 		printf("Android header version 0\n");
777 		ret = -EINVAL;
778 		goto out;
779 	}
780 
781 	ret = android_get_dtbo(&fdt_dtbo, (void *)hdr, &index);
782 	if (!ret) {
783 		/* Must incease size before overlay */
784 		fdt_increase_size(fdt_addr, fdt_totalsize((void *)fdt_dtbo));
785 		ret = fdt_overlay_apply(fdt_addr, (void *)fdt_dtbo);
786 		if (!ret) {
787 			snprintf(buf, 32, "%s%d", "androidboot.dtbo_idx=", index);
788 			env_update("bootargs", buf);
789 			printf("ANDROID: fdt overlay OK\n");
790 		} else {
791 			printf("ANDROID: fdt overlay failed, ret=%d\n", ret);
792 		}
793 	}
794 
795 out:
796 	free(hdr);
797 
798 	return 0;
799 }
800 #endif
801 
802 int android_bootloader_boot_flow(struct blk_desc *dev_desc,
803 				 unsigned long load_address)
804 {
805 	enum android_boot_mode mode;
806 	disk_partition_t misc_part_info;
807 	int part_num;
808 	int ret;
809 	char *command_line;
810 	char slot_suffix[3] = {0};
811 	const char *mode_cmdline = NULL;
812 	char *boot_partname = ANDROID_PARTITION_BOOT;
813 	ulong fdt_addr;
814 
815 	/*
816 	 * 1. Load MISC partition and determine the boot mode
817 	 *   clear its value for the next boot if needed.
818 	 */
819 	part_num = part_get_info_by_name(dev_desc, ANDROID_PARTITION_MISC,
820 					 &misc_part_info);
821 	if (part_num < 0)
822 		printf("%s Could not find misc partition\n", __func__);
823 
824 #ifdef CONFIG_OPTEE_CLIENT
825 	/* load attestation key from misc partition. */
826 	load_attestation_key(dev_desc, &misc_part_info);
827 #endif
828 
829 	mode = android_bootloader_load_and_clear_mode(dev_desc, &misc_part_info);
830 #ifdef CONFIG_RKIMG_BOOTLOADER
831 	if (mode == ANDROID_BOOT_MODE_NORMAL) {
832 		if (rockchip_get_boot_mode() == BOOT_MODE_RECOVERY)
833 			mode = ANDROID_BOOT_MODE_RECOVERY;
834 	}
835 #endif
836 	printf("ANDROID: reboot reason: \"%s\"\n", android_boot_mode_str(mode));
837 
838 #ifdef CONFIG_ANDROID_AB
839 	/*TODO: get from pre-loader or misc partition*/
840 	if (rk_avb_get_current_slot(slot_suffix))
841 		return -1;
842 
843 	if (slot_suffix[0] != '_') {
844 		printf("There is no bootable slot!\n");
845 		return -1;
846 	}
847 #endif
848 
849 	switch (mode) {
850 	case ANDROID_BOOT_MODE_NORMAL:
851 		/* In normal mode, we load the kernel from "boot" but append
852 		 * "skip_initramfs" to the cmdline to make it ignore the
853 		 * recovery initramfs in the boot partition.
854 		 */
855 #if defined(CONFIG_ANDROID_AB) && !defined(CONFIG_ANDROID_AVB)
856 		char root_partition[20] = {0};
857 		char guid_buf[UUID_SIZE] = {0};
858 		char root_partuuid[70] = "root=PARTUUID=";
859 
860 		strcat(root_partition, ANDROID_PARTITION_SYSTEM);
861 		strcat(root_partition, slot_suffix);
862 		get_partition_unique_uuid(root_partition, guid_buf, UUID_SIZE);
863 		strcat(root_partuuid, guid_buf);
864 		env_update("bootargs", root_partuuid);
865 #endif
866 
867 #ifdef CONFIG_ANDROID_AB
868 		mode_cmdline = "skip_initramfs";
869 #endif
870 		break;
871 	case ANDROID_BOOT_MODE_RECOVERY:
872 		/* In recovery mode we still boot the kernel from "boot" but
873 		 * don't skip the initramfs so it boots to recovery.
874 		 */
875 #ifndef CONFIG_ANDROID_AB
876 		boot_partname = ANDROID_PARTITION_RECOVERY;
877 #endif
878 		break;
879 	case ANDROID_BOOT_MODE_BOOTLOADER:
880 		/* Bootloader mode enters fastboot. If this operation fails we
881 		 * simply return since we can't recover from this situation by
882 		 * switching to another slot.
883 		 */
884 		return android_bootloader_boot_bootloader();
885 	}
886 
887 #ifdef CONFIG_ANDROID_AVB
888 	if (android_slot_verify(boot_partname, &load_address, slot_suffix))
889 		return -1;
890 #else
891 	/*
892 	 * 2. Load the boot/recovery from the desired "boot" partition.
893 	 * Determine if this is an AOSP image.
894 	 */
895 	disk_partition_t boot_part_info;
896 	part_num =
897 	    android_part_get_info_by_name_suffix(dev_desc,
898 						 boot_partname,
899 						 slot_suffix, &boot_part_info);
900 	if (part_num < 0) {
901 		printf("%s Could not found bootable partition %s\n", __func__,
902 		       boot_partname);
903 		return -1;
904 	}
905 	debug("ANDROID: Loading kernel from \"%s\", partition %d.\n",
906 	      boot_part_info.name, part_num);
907 
908 	ret = android_image_load(dev_desc, &boot_part_info, load_address,
909 				 -1UL);
910 	if (ret < 0) {
911 		printf("%s %s part load fail\n", __func__, boot_part_info.name);
912 		return ret;
913 	}
914 	load_address = ret;
915 #endif
916 
917 	/* Set Android root variables. */
918 	env_set_ulong("android_root_devnum", dev_desc->devnum);
919 	env_set("android_slotsufix", slot_suffix);
920 
921 #ifdef CONFIG_FASTBOOT_OEM_UNLOCK
922 	/* read oem unlock status and attach to bootargs */
923 	uint8_t unlock = 0;
924 	TEEC_Result result;
925 	char oem_unlock[OEM_UNLOCK_ARG_SIZE] = {0};
926 	result = trusty_read_oem_unlock(&unlock);
927 	if (result) {
928 		printf("read oem unlock status with error : 0x%x\n", result);
929 	} else {
930 		snprintf(oem_unlock, OEM_UNLOCK_ARG_SIZE, "androidboot.oem_unlocked=%d", unlock);
931 		env_update("bootargs", oem_unlock);
932 	}
933 #endif
934 
935 	/* Assemble the command line */
936 	command_line = android_assemble_cmdline(slot_suffix, mode_cmdline);
937 	env_update("bootargs", command_line);
938 
939 	debug("ANDROID: bootargs: \"%s\"\n", command_line);
940 
941 #ifdef CONFIG_SUPPORT_OEM_DTB
942 	if (android_bootloader_get_fdt(ANDROID_PARTITION_OEM,
943 				       ANDROID_ARG_FDT_FILENAME)) {
944 		printf("Can not get the fdt data from oem!\n");
945 	}
946 #else
947 	ret = android_image_get_fdt((void *)load_address, &fdt_addr);
948 	if (!ret)
949 		env_set_hex("fdt_addr", fdt_addr);
950 #endif
951 	android_bootloader_boot_kernel(load_address);
952 
953 	/* TODO: If the kernel doesn't boot mark the selected slot as bad. */
954 	return -1;
955 }
956 
957 int android_avb_boot_flow(char *slot_suffix, unsigned long kernel_address)
958 {
959 	struct blk_desc *dev_desc;
960 	disk_partition_t boot_part_info;
961 	int ret;
962 	dev_desc = rockchip_get_bootdev();
963 	if (!dev_desc) {
964 		printf("%s: dev_desc is NULL!\n", __func__);
965 		return -1;
966 	}
967 	/* Load the kernel from the desired "boot" partition. */
968 	android_part_get_info_by_name_suffix(dev_desc,
969 					     ANDROID_PARTITION_BOOT,
970 					     slot_suffix, &boot_part_info);
971 	ret = android_image_load(dev_desc, &boot_part_info, kernel_address,
972 				 -1UL);
973 	if (ret < 0)
974 		return ret;
975 	android_bootloader_boot_kernel(kernel_address);
976 
977 	/* TODO: If the kernel doesn't boot mark the selected slot as bad. */
978 	return -1;
979 }
980 
981 int android_boot_flow(unsigned long kernel_address)
982 {
983 	struct blk_desc *dev_desc;
984 	disk_partition_t boot_part_info;
985 	int ret;
986 	dev_desc = rockchip_get_bootdev();
987 	if (!dev_desc) {
988 		printf("%s: dev_desc is NULL!\n", __func__);
989 		return -1;
990 	}
991 	/* Load the kernel from the desired "boot" partition. */
992 	part_get_info_by_name(dev_desc, ANDROID_PARTITION_BOOT, &boot_part_info);
993 	ret = android_image_load(dev_desc, &boot_part_info, kernel_address,
994 				 -1UL);
995 	if (ret < 0)
996 		return ret;
997 	android_bootloader_boot_kernel(kernel_address);
998 
999 	/* TODO: If the kernel doesn't boot mark the selected slot as bad. */
1000 	return -1;
1001 }
1002