xref: /OK3568_Linux_fs/u-boot/common/android_bootloader.c (revision 4882a59341e53eb6f0b4789bf948001014eff981)
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 <android_ab.h>
14 #include <bootm.h>
15 #include <asm/arch/hotkey.h>
16 #include <cli.h>
17 #include <common.h>
18 #include <dt_table.h>
19 #include <image-android-dt.h>
20 #include <malloc.h>
21 #include <mp_boot.h>
22 #include <fdt_support.h>
23 #include <fs.h>
24 #include <boot_rkimg.h>
25 #include <attestation_key.h>
26 #include <keymaster.h>
27 #include <linux/libfdt_env.h>
28 #include <optee_include/OpteeClientInterface.h>
29 #include <bidram.h>
30 #include <console.h>
31 #include <sysmem.h>
32 
33 DECLARE_GLOBAL_DATA_PTR;
34 
android_bootloader_message_load(struct blk_desc * dev_desc,const disk_partition_t * part_info,struct android_bootloader_message * message)35 int android_bootloader_message_load(
36 	struct blk_desc *dev_desc,
37 	const disk_partition_t *part_info,
38 	struct android_bootloader_message *message)
39 {
40 	ulong message_blocks = sizeof(struct android_bootloader_message) /
41 	    part_info->blksz;
42 	if (message_blocks > part_info->size) {
43 		printf("misc partition too small.\n");
44 		return -1;
45 	}
46 
47 	if (blk_dread(dev_desc, part_info->start + android_bcb_msg_sector_offset(),
48 	     message_blocks, message) !=
49 	    message_blocks) {
50 		printf("Could not read from misc partition\n");
51 		return -1;
52 	}
53 	debug("ANDROID: Loaded BCB, %lu blocks.\n", message_blocks);
54 	return 0;
55 }
56 
android_bootloader_message_write(struct blk_desc * dev_desc,const disk_partition_t * part_info,struct android_bootloader_message * message)57 static int android_bootloader_message_write(
58 	struct blk_desc *dev_desc,
59 	const disk_partition_t *part_info,
60 	struct android_bootloader_message *message)
61 {
62 	ulong message_blocks = sizeof(struct android_bootloader_message) /
63 	    part_info->blksz + android_bcb_msg_sector_offset();
64 
65 	if (message_blocks > part_info->size) {
66 		printf("misc partition too small.\n");
67 		return -1;
68 	}
69 
70 	if (blk_dwrite(dev_desc, part_info->start, message_blocks, message) !=
71 	    message_blocks) {
72 		printf("Could not write to misc partition\n");
73 		return -1;
74 	}
75 	debug("ANDROID: Wrote new BCB, %lu blocks.\n", message_blocks);
76 	return 0;
77 }
78 
android_bootloader_load_and_clear_mode(struct blk_desc * dev_desc,const disk_partition_t * misc_part_info)79 static enum android_boot_mode android_bootloader_load_and_clear_mode(
80 	struct blk_desc *dev_desc,
81 	const disk_partition_t *misc_part_info)
82 {
83 	struct android_bootloader_message bcb;
84 
85 #ifdef CONFIG_FASTBOOT
86 	char *bootloader_str;
87 
88 	/* Check for message from bootloader stored in RAM from a previous boot.
89 	 */
90 	bootloader_str = (char *)CONFIG_FASTBOOT_BUF_ADDR;
91 	if (!strcmp("reboot-bootloader", bootloader_str)) {
92 		bootloader_str[0] = '\0';
93 		return ANDROID_BOOT_MODE_BOOTLOADER;
94 	}
95 #endif
96 
97 	/* Check and update the BCB message if needed. */
98 	if (android_bootloader_message_load(dev_desc, misc_part_info, &bcb) <
99 	    0) {
100 		printf("WARNING: Unable to load the BCB.\n");
101 		return ANDROID_BOOT_MODE_NORMAL;
102 	}
103 
104 	if (!strcmp("bootonce-bootloader", bcb.command)) {
105 		/* Erase the message in the BCB since this value should be used
106 		 * only once.
107 		 */
108 		memset(bcb.command, 0, sizeof(bcb.command));
109 		android_bootloader_message_write(dev_desc, misc_part_info,
110 						 &bcb);
111 		return ANDROID_BOOT_MODE_BOOTLOADER;
112 	}
113 
114 	if (!strcmp("boot-recovery", bcb.command))
115 		return ANDROID_BOOT_MODE_RECOVERY;
116 
117 	if (!strcmp("boot-fastboot", bcb.command))
118 		return ANDROID_BOOT_MODE_RECOVERY;
119 
120 	return ANDROID_BOOT_MODE_NORMAL;
121 }
122 
android_bcb_write(char * cmd)123 int android_bcb_write(char *cmd)
124 {
125 	struct android_bootloader_message message = {0};
126 	disk_partition_t part_info;
127 	struct blk_desc *dev_desc;
128 	int ret;
129 
130 	if (!cmd)
131 		return -ENOMEM;
132 
133 	if (strlen(cmd) >= 32)
134 		return -ENOMEM;
135 
136 	dev_desc = rockchip_get_bootdev();
137 	if (!dev_desc) {
138 		printf("%s: dev_desc is NULL!\n", __func__);
139 		return -ENODEV;
140 	}
141 
142 	ret = part_get_info_by_name(dev_desc, ANDROID_PARTITION_MISC, &part_info);
143 	if (ret < 0) {
144 		printf("%s: Could not found misc partition, just run recovery\n",
145 		       __func__);
146 		return -ENODEV;
147 	}
148 
149 	strcpy(message.command, cmd);
150 	return android_bootloader_message_write(dev_desc, &part_info, &message);
151 }
152 
153 /**
154  * Return the reboot reason string for the passed boot mode.
155  *
156  * @param mode	The Android Boot mode.
157  * @return a pointer to the reboot reason string for mode.
158  */
android_boot_mode_str(enum android_boot_mode mode)159 static const char *android_boot_mode_str(enum android_boot_mode mode)
160 {
161 	switch (mode) {
162 	case ANDROID_BOOT_MODE_NORMAL:
163 		return "(none)";
164 	case ANDROID_BOOT_MODE_RECOVERY:
165 		return "recovery";
166 	case ANDROID_BOOT_MODE_BOOTLOADER:
167 		return "bootloader";
168 	}
169 	return NULL;
170 }
171 
android_bootloader_boot_bootloader(void)172 static int android_bootloader_boot_bootloader(void)
173 {
174 	const char *fastboot_cmd = env_get("fastbootcmd");
175 
176 	if (fastboot_cmd == NULL) {
177 		printf("fastboot_cmd is null, run default fastboot_cmd!\n");
178 		fastboot_cmd = "fastboot usb 0";
179 	}
180 
181 	return run_command(fastboot_cmd, CMD_FLAG_ENV);
182 }
183 
184 #ifdef CONFIG_SUPPORT_OEM_DTB
android_bootloader_get_fdt(const char * part_name,const char * load_file_name)185 static int android_bootloader_get_fdt(const char *part_name,
186 		const char *load_file_name)
187 {
188 	struct blk_desc *dev_desc;
189 	disk_partition_t part_info;
190 	char *fdt_addr = NULL;
191 	char dev_part[3] = {0};
192 	loff_t bytes = 0;
193 	loff_t pos = 0;
194 	loff_t len_read;
195 	unsigned long addr = 0;
196 	int part_num = -1;
197 	int ret;
198 
199 	dev_desc = rockchip_get_bootdev();
200 	if (!dev_desc) {
201 		printf("%s: dev_desc is NULL!\n", __func__);
202 		return -1;
203 	}
204 
205 	part_num = part_get_info_by_name(dev_desc, part_name, &part_info);
206 	if (part_num < 0) {
207 		printf("ANDROID: Could not find partition \"%s\"\n", part_name);
208 		return -1;
209 	}
210 
211 	snprintf(dev_part, ARRAY_SIZE(dev_part), ":%x", part_num);
212 	if (fs_set_blk_dev_with_part(dev_desc, part_num))
213 		return -1;
214 
215 	fdt_addr = env_get("fdt_addr_r");
216 	if (!fdt_addr) {
217 		printf("ANDROID: No Found FDT Load Address.\n");
218 		return -1;
219 	}
220 	addr = simple_strtoul(fdt_addr, NULL, 16);
221 
222 	ret = fs_read(load_file_name, addr, pos, bytes, &len_read);
223 	if (ret < 0)
224 		return -1;
225 
226 	return 0;
227 }
228 #endif
229 
230 /*
231  *   Test on RK3308 AARCH64 mode (Cortex A35 816 MHZ) boot with eMMC:
232  *
233  *   |-------------------------------------------------------------------|
234  *   | Format    |  Size(Byte) | Ratio | Decomp time(ms) | Boot time(ms) |
235  *   |-------------------------------------------------------------------|
236  *   | Image     | 7720968     |       |                 |     488       |
237  *   |-------------------------------------------------------------------|
238  *   | Image.lz4 | 4119448     | 53%   |       59        |     455       |
239  *   |-------------------------------------------------------------------|
240  *   | Image.lzo | 3858322     | 49%   |       141       |     536       |
241  *   |-------------------------------------------------------------------|
242  *   | Image.gz  | 3529108     | 45%   |       222       |     609       |
243  *   |-------------------------------------------------------------------|
244  *   | Image.bz2 | 3295914     | 42%   |       2940      |               |
245  *   |-------------------------------------------------------------------|
246  *   | Image.lzma| 2683750     | 34%   |                 |               |
247  *   |-------------------------------------------------------------------|
248  */
sysmem_alloc_uncomp_kernel(ulong andr_hdr,ulong uncomp_kaddr,u32 comp)249 static int sysmem_alloc_uncomp_kernel(ulong andr_hdr,
250 				      ulong uncomp_kaddr, u32 comp)
251 {
252 	struct andr_img_hdr *hdr = (struct andr_img_hdr *)andr_hdr;
253 	ulong ksize, kaddr;
254 
255 	if (comp != IH_COMP_NONE) {
256 		/* Release compressed sysmem */
257 		kaddr = env_get_hex("kernel_addr_c", 0);
258 		if (!kaddr)
259 			kaddr = env_get_hex("kernel_addr_r", 0);
260 		kaddr -= hdr->page_size;
261 		if (sysmem_free((phys_addr_t)kaddr))
262 			return -EINVAL;
263 #ifdef CONFIG_SKIP_RELOCATE_UBOOT
264 		sysmem_free(CONFIG_SYS_TEXT_BASE);
265 #endif
266 		/*
267 		 * Use smaller Ratio to get larger estimated uncompress
268 		 * kernel size.
269 		 */
270 		if (comp == IH_COMP_ZIMAGE)
271 			ksize = hdr->kernel_size * 100 / 45;
272 		else if (comp == IH_COMP_LZ4)
273 			ksize = hdr->kernel_size * 100 / 50;
274 		else if (comp == IH_COMP_LZO)
275 			ksize = hdr->kernel_size * 100 / 45;
276 		else if (comp == IH_COMP_GZIP)
277 			ksize = hdr->kernel_size * 100 / 40;
278 		else if (comp == IH_COMP_BZIP2)
279 			ksize = hdr->kernel_size * 100 / 40;
280 		else if (comp == IH_COMP_LZMA)
281 			ksize = hdr->kernel_size * 100 / 30;
282 		else
283 			ksize = hdr->kernel_size;
284 
285 		kaddr = uncomp_kaddr;
286 		ksize = ALIGN(ksize, 512);
287 		if (!sysmem_alloc_base(MEM_UNCOMP_KERNEL,
288 				       (phys_addr_t)kaddr, ksize))
289 			return -ENOMEM;
290 	}
291 
292 	return 0;
293 }
294 
android_bootloader_boot_kernel(unsigned long kernel_address)295 int android_bootloader_boot_kernel(unsigned long kernel_address)
296 {
297 	char *kernel_addr_r = env_get("kernel_addr_r");
298 	char *kernel_addr_c = env_get("kernel_addr_c");
299 	char *fdt_addr = env_get("fdt_addr_r");
300 	char kernel_addr_str[12];
301 	char comp_str[32] = {0};
302 	ulong comp_type;
303 	const char *comp_name[] = {
304 		[IH_COMP_NONE]  = "IMAGE",
305 		[IH_COMP_GZIP]  = "GZIP",
306 		[IH_COMP_BZIP2] = "BZIP2",
307 		[IH_COMP_LZMA]  = "LZMA",
308 		[IH_COMP_LZO]   = "LZO",
309 		[IH_COMP_LZ4]   = "LZ4",
310 		[IH_COMP_ZIMAGE]= "ZIMAGE",
311 	};
312 	char *bootm_args[] = {
313 		kernel_addr_str, kernel_addr_str, fdt_addr, NULL };
314 
315 	comp_type = env_get_ulong("os_comp", 10, 0);
316 	sprintf(kernel_addr_str, "0x%08lx", kernel_address);
317 
318 	if (comp_type != IH_COMP_NONE) {
319 		if (comp_type == IH_COMP_ZIMAGE &&
320 		    kernel_addr_r && !kernel_addr_c) {
321 			kernel_addr_c = kernel_addr_r;
322 			kernel_addr_r = __stringify(CONFIG_SYS_SDRAM_BASE);
323 		}
324 		snprintf(comp_str, 32, "%s%s%s",
325 			 "(Uncompress to ", kernel_addr_r, ")");
326 	}
327 
328 	printf("Booting %s kernel at %s%s with fdt at %s...\n\n\n",
329 	       comp_name[comp_type],
330 	       comp_type != IH_COMP_NONE ? kernel_addr_c : kernel_addr_r,
331 	       comp_str, fdt_addr);
332 
333 	hotkey_run(HK_SYSMEM);
334 
335 	/*
336 	 * Check whether there is enough space for uncompress kernel,
337 	 * Actually, here only gives a sysmem warning message when failed
338 	 * but never return -1.
339 	 */
340 	if (sysmem_alloc_uncomp_kernel(kernel_address,
341 				       simple_strtoul(kernel_addr_r, NULL, 16),
342 				       comp_type))
343 		return -1;
344 
345 	return do_bootm_states(NULL, 0, ARRAY_SIZE(bootm_args), bootm_args,
346 		BOOTM_STATE_START |
347 		BOOTM_STATE_FINDOS | BOOTM_STATE_FINDOTHER |
348 		BOOTM_STATE_LOADOS |
349 #ifdef CONFIG_SYS_BOOT_RAMDISK_HIGH
350 		BOOTM_STATE_RAMDISK |
351 #endif
352 		BOOTM_STATE_OS_PREP | BOOTM_STATE_OS_FAKE_GO |
353 		BOOTM_STATE_OS_GO, &images, 1);
354 }
355 
strjoin(const char ** chunks,char separator)356 static char *strjoin(const char **chunks, char separator)
357 {
358 	int len, joined_len = 0;
359 	char *ret, *current;
360 	const char **p;
361 
362 	for (p = chunks; *p; p++)
363 		joined_len += strlen(*p) + 1;
364 
365 	if (!joined_len) {
366 		ret = malloc(1);
367 		if (ret)
368 			ret[0] = '\0';
369 		return ret;
370 	}
371 
372 	ret = malloc(joined_len);
373 	current = ret;
374 	if (!ret)
375 		return ret;
376 
377 	for (p = chunks; *p; p++) {
378 		len = strlen(*p);
379 		memcpy(current, *p, len);
380 		current += len;
381 		*current = separator;
382 		current++;
383 	}
384 	/* Replace the last separator by a \0. */
385 	current[-1] = '\0';
386 	return ret;
387 }
388 
389 /** android_assemble_cmdline - Assemble the command line to pass to the kernel
390  * @return a newly allocated string
391  */
android_assemble_cmdline(const char * slot_suffix,const char * extra_args)392 char *android_assemble_cmdline(const char *slot_suffix,
393 				      const char *extra_args)
394 {
395 	const char *cmdline_chunks[16];
396 	const char **current_chunk = cmdline_chunks;
397 	char *env_cmdline, *cmdline, *rootdev_input, *serialno;
398 	char *allocated_suffix = NULL;
399 	char *allocated_serialno = NULL;
400 	char *allocated_rootdev = NULL;
401 	unsigned long rootdev_len;
402 
403 	env_cmdline = env_get("bootargs");
404 	if (env_cmdline)
405 		*(current_chunk++) = env_cmdline;
406 
407 	/* The |slot_suffix| needs to be passed to the kernel to know what
408 	 * slot to boot from.
409 	 */
410 #ifdef CONFIG_ANDROID_AB
411 	if (slot_suffix) {
412 		allocated_suffix = malloc(strlen(ANDROID_ARG_SLOT_SUFFIX) +
413 					  strlen(slot_suffix) + 1);
414 		memset(allocated_suffix, 0, strlen(ANDROID_ARG_SLOT_SUFFIX)
415 		       + strlen(slot_suffix) + 1);
416 		strcpy(allocated_suffix, ANDROID_ARG_SLOT_SUFFIX);
417 		strcat(allocated_suffix, slot_suffix);
418 		*(current_chunk++) = allocated_suffix;
419 	}
420 #endif
421 	serialno = env_get("serial#");
422 	if (serialno) {
423 		allocated_serialno = malloc(strlen(ANDROID_ARG_SERIALNO) +
424 					  strlen(serialno) + 1);
425 		memset(allocated_serialno, 0, strlen(ANDROID_ARG_SERIALNO) +
426 				strlen(serialno) + 1);
427 		strcpy(allocated_serialno, ANDROID_ARG_SERIALNO);
428 		strcat(allocated_serialno, serialno);
429 		*(current_chunk++) = allocated_serialno;
430 	}
431 
432 	rootdev_input = env_get("android_rootdev");
433 	if (rootdev_input) {
434 		rootdev_len = strlen(ANDROID_ARG_ROOT) + CONFIG_SYS_CBSIZE + 1;
435 		allocated_rootdev = malloc(rootdev_len);
436 		strcpy(allocated_rootdev, ANDROID_ARG_ROOT);
437 		cli_simple_process_macros(rootdev_input,
438 					  allocated_rootdev +
439 					  strlen(ANDROID_ARG_ROOT));
440 		/* Make sure that the string is null-terminated since the
441 		 * previous could not copy to the end of the input string if it
442 		 * is too big.
443 		 */
444 		allocated_rootdev[rootdev_len - 1] = '\0';
445 		*(current_chunk++) = allocated_rootdev;
446 	}
447 
448 	if (extra_args)
449 		*(current_chunk++) = extra_args;
450 
451 	*(current_chunk++) = NULL;
452 	cmdline = strjoin(cmdline_chunks, ' ');
453 	free(allocated_suffix);
454 	free(allocated_rootdev);
455 	return cmdline;
456 }
457 
458 #ifdef CONFIG_ANDROID_AVB
slot_set_unbootable(AvbABSlotData * slot)459 static void slot_set_unbootable(AvbABSlotData* slot)
460 {
461 	slot->priority = 0;
462 	slot->tries_remaining = 0;
463 	slot->successful_boot = 0;
464 }
465 
join_str(const char * a,const char * b)466 static char *join_str(const char *a, const char *b)
467 {
468 	size_t len = strlen(a) + strlen(b) + 1 /* null term */;
469 	char *ret = (char *)malloc(len);
470 
471 	if (!ret) {
472 		debug("failed to alloc %zu\n", len);
473 		return NULL;
474 	}
475 	strcpy(ret, a);
476 	strcat(ret, b);
477 
478 	return ret;
479 }
480 
get_partition_size(AvbOps * ops,char * name,const char * slot_suffix)481 static size_t get_partition_size(AvbOps *ops, char *name,
482 				 const char *slot_suffix)
483 {
484 	char *partition_name = join_str(name, slot_suffix);
485 	uint64_t size = 0;
486 	AvbIOResult res;
487 
488 	if (partition_name == NULL)
489 		goto bail;
490 
491 	res = ops->get_size_of_partition(ops, partition_name, &size);
492 	if (res != AVB_IO_RESULT_OK && res != AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION)
493 		size = 0;
494 bail:
495 	if (partition_name)
496 		free(partition_name);
497 
498 	return size;
499 }
500 
501 static struct AvbOpsData preload_user_data;
502 
avb_image_distribute_prepare(AvbSlotVerifyData * slot_data,AvbOps * ops,char * slot_suffix)503 static int avb_image_distribute_prepare(AvbSlotVerifyData *slot_data,
504 					AvbOps *ops, char *slot_suffix)
505 {
506 	struct AvbOpsData *data = (struct AvbOpsData *)(ops->user_data);
507 	size_t vendor_boot_size;
508 	size_t init_boot_size;
509 	size_t resource_size;
510 	size_t boot_size;
511 	void *image_buf;
512 
513 	boot_size = max(get_partition_size(ops, ANDROID_PARTITION_BOOT, slot_suffix),
514 		get_partition_size(ops, ANDROID_PARTITION_RECOVERY, slot_suffix));
515 	init_boot_size = get_partition_size(ops,
516 				ANDROID_PARTITION_INIT_BOOT, slot_suffix);
517 	vendor_boot_size = get_partition_size(ops,
518 				ANDROID_PARTITION_VENDOR_BOOT, slot_suffix);
519 	resource_size = get_partition_size(ops,
520 				ANDROID_PARTITION_RESOURCE, slot_suffix);
521 	image_buf = sysmem_alloc(MEM_AVB_ANDROID,
522 				 boot_size + init_boot_size +
523 				 vendor_boot_size + resource_size);
524 	if (!image_buf) {
525 		printf("avb: sysmem alloc failed\n");
526 		return -ENOMEM;
527 	}
528 
529 	/* layout: | boot/recovery | vendor_boot | init_boot | resource | */
530 	data->slot_suffix = slot_suffix;
531 	data->boot.addr = image_buf;
532 	data->boot.size = 0;
533 	data->vendor_boot.addr = data->boot.addr + boot_size;
534 	data->vendor_boot.size = 0;
535 	data->init_boot.addr = data->vendor_boot.addr + vendor_boot_size;
536 	data->init_boot.size = 0;
537 	data->resource.addr = data->init_boot.addr + init_boot_size;
538 	data->resource.size = 0;
539 
540 	return 0;
541 }
542 
avb_image_distribute_finish(AvbSlotVerifyData * slot_data,AvbSlotVerifyFlags flags,ulong * load_address)543 static int avb_image_distribute_finish(AvbSlotVerifyData *slot_data,
544 				       AvbSlotVerifyFlags flags,
545 				       ulong *load_address)
546 {
547 	struct andr_img_hdr *hdr;
548 	ulong load_addr = *load_address;
549 	void *vendor_boot_hdr = NULL;
550 	void *init_boot_hdr = NULL;
551 	void *boot_hdr = NULL;
552 	char *part_name;
553 	int i, ret;
554 
555 	for (i = 0; i < slot_data->num_loaded_partitions; i++) {
556 		part_name = slot_data->loaded_partitions[i].partition_name;
557 		if (!strncmp(ANDROID_PARTITION_BOOT, part_name, 4) ||
558 		    !strncmp(ANDROID_PARTITION_RECOVERY, part_name, 8)) {
559 			boot_hdr = slot_data->loaded_partitions[i].data;
560 		} else if (!strncmp(ANDROID_PARTITION_INIT_BOOT, part_name, 9)) {
561 			init_boot_hdr = slot_data->loaded_partitions[i].data;
562 		} else if (!strncmp(ANDROID_PARTITION_VENDOR_BOOT, part_name, 11)) {
563 			vendor_boot_hdr = slot_data->loaded_partitions[i].data;
564 		}
565 	}
566 
567 	/*
568 	 *		populate boot_img_hdr_v34
569 	 *
570 	 * If allow verification error: the images are loaded by
571 	 * ops->get_preloaded_partition() which auto populates
572 	 * boot_img_hdr_v34.
573 	 *
574 	 * If not allow verification error: the images are full loaded
575 	 * by ops->read_from_partition() which doesn't populate
576 	 * boot_img_hdr_v34, we need to fix it here for bootm and
577 	 */
578 
579 	hdr = boot_hdr;
580 	if (hdr->header_version >= 3 &&
581 	    !(flags & AVB_SLOT_VERIFY_FLAGS_ALLOW_VERIFICATION_ERROR)) {
582 		hdr = malloc(sizeof(struct andr_img_hdr));
583 		if (!hdr)
584 			return -ENOMEM;
585 
586 		ret = populate_boot_info(boot_hdr, vendor_boot_hdr,
587 					 init_boot_hdr, hdr, true);
588 		if (ret < 0) {
589 			printf("avb: populate boot info failed, ret=%d\n", ret);
590 			return ret;
591 		}
592 		memcpy(boot_hdr, hdr, sizeof(*hdr));
593 	}
594 
595 	/* distribute ! */
596 	load_addr -= hdr->page_size;
597 	if (android_image_memcpy_separate(boot_hdr, &load_addr)) {
598 		printf("Failed to separate copy android image\n");
599 		return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
600 	}
601 
602 	*load_address = load_addr;
603 
604 	return 0;
605 }
606 
android_image_verify_resource(const char * boot_part,ulong * resc_buf)607 int android_image_verify_resource(const char *boot_part, ulong *resc_buf)
608 {
609 	const char *requested_partitions[] = {
610 		NULL,
611 		NULL,
612 	};
613 	struct AvbOpsData *data;
614 	uint8_t unlocked = true;
615 	AvbOps *ops;
616 	AvbSlotVerifyFlags flags;
617 	AvbSlotVerifyData *slot_data = {NULL};
618 	AvbSlotVerifyResult verify_result;
619 	char slot_suffix[3] = {0};
620 	char *part_name;
621 	void *image_buf = NULL;
622 	int retry_no_vbmeta_partition = 1;
623 	int i, ret;
624 
625 	ops = avb_ops_user_new();
626 	if (ops == NULL) {
627 		printf("avb_ops_user_new() failed!\n");
628 		return -AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
629 	}
630 
631 	if (ops->read_is_device_unlocked(ops, (bool *)&unlocked) != AVB_IO_RESULT_OK)
632 		printf("Error determining whether device is unlocked.\n");
633 
634 	printf("Device is: %s\n", (unlocked & LOCK_MASK)? "UNLOCKED" : "LOCKED");
635 
636 	if (unlocked & LOCK_MASK) {
637 		*resc_buf = 0;
638 		return 0;
639 	}
640 
641 	flags = AVB_SLOT_VERIFY_FLAGS_NONE;
642 	if (strcmp(boot_part, ANDROID_PARTITION_RECOVERY) == 0)
643 		flags |= AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION;
644 
645 #ifdef CONFIG_ANDROID_AB
646 	part_name = strdup(boot_part);
647 	*(part_name + strlen(boot_part) - 2) = '\0';
648 	requested_partitions[0] = part_name;
649 
650 	ret = rk_avb_get_current_slot(slot_suffix);
651 	if (ret) {
652 		printf("Failed to get slot suffix, ret=%d\n", ret);
653 		return ret;
654 	}
655 #else
656 	requested_partitions[0] = boot_part;
657 #endif
658 	data = (struct AvbOpsData *)(ops->user_data);
659 	ret = avb_image_distribute_prepare(slot_data, ops, slot_suffix);
660 	if (ret) {
661 		printf("avb image distribute prepare failed %d\n", ret);
662 		return ret;
663 	}
664 
665 retry_verify:
666 	verify_result =
667 	avb_slot_verify(ops,
668 			requested_partitions,
669 			slot_suffix,
670 			flags,
671 			AVB_HASHTREE_ERROR_MODE_RESTART,
672 			&slot_data);
673 	if (verify_result != AVB_SLOT_VERIFY_RESULT_OK &&
674 	    verify_result != AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED) {
675 		if (retry_no_vbmeta_partition && strcmp(boot_part, ANDROID_PARTITION_RECOVERY) == 0) {
676 			printf("Verify recovery with vbmeta.\n");
677 			flags &= ~AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION;
678 			retry_no_vbmeta_partition = 0;
679 			goto retry_verify;
680 		}
681 	}
682 
683 	if (verify_result != AVB_SLOT_VERIFY_RESULT_OK || !slot_data) {
684 		sysmem_free((ulong)data->boot.addr);
685 		return verify_result;
686 	}
687 
688 	for (i = 0; i < slot_data->num_loaded_partitions; i++) {
689 		part_name = slot_data->loaded_partitions[i].partition_name;
690 		if (!strncmp(ANDROID_PARTITION_RESOURCE, part_name, 8)) {
691 			image_buf = slot_data->loaded_partitions[i].data;
692 			break;
693 		} else if (!strncmp(ANDROID_PARTITION_BOOT, part_name, 4) ||
694 			   !strncmp(ANDROID_PARTITION_RECOVERY, part_name, 8)) {
695 			struct andr_img_hdr *hdr;
696 
697 			hdr = (void *)slot_data->loaded_partitions[i].data;
698 			if (android_image_check_header(hdr))
699 				continue;
700 
701 			if (hdr->header_version <= 2) {
702 				image_buf = (void *)hdr + hdr->page_size +
703 					ALIGN(hdr->kernel_size, hdr->page_size) +
704 					ALIGN(hdr->ramdisk_size, hdr->page_size);
705 				break;
706 			}
707 		}
708 	}
709 
710 	if (image_buf) {
711 		memcpy((char *)&preload_user_data, (char *)data, sizeof(*data));
712 		*resc_buf = (ulong)image_buf;
713 	}
714 
715 	return 0;
716 }
717 
718 /*
719  *		AVB Policy.
720  *
721  * == avb with unlock:
722  * Don't process hash verify.
723  * Go pre-loaded path: Loading vendor_boot and init_boot
724  * directly to where they should be, while loading the
725  * boot/recovery. The boot message tells like:
726  * ···
727  * preloaded: distribute image from 'boot_a'
728  * preloaded: distribute image from 'init_boot_a'
729  * preloaded: distribute image from 'vendor_boot_a'
730  * ···
731  *
732  * == avb with lock:
733  * Process hash verify.
734  * Go pre-loaded path: Loading full vendor_boot, init_boot and
735  * boot/recovery one by one to verify, and distributing them to
736  * where they should be by memcpy at last.
737  *
738  * The three images share a large memory buffer that allocated
739  * by sysmem_alloc(), it locate at high memory address that
740  * just lower than SP bottom. The boot message tells like:
741  * ···
742  * preloaded: full image from 'boot_a' at 0xe47f90c0 - 0xe7a4b0c0
743  * preloaded: full image from 'init_boot_a' at 0xeaff90c0 - 0xeb2950c0
744  * preloaded: full image from 'vendor_boot_a' at 0xe87f90c0 - 0xe9f6e0c0
745  * ···
746  */
android_slot_verify(char * boot_partname,unsigned long * android_load_address,char * slot_suffix)747 static AvbSlotVerifyResult android_slot_verify(char *boot_partname,
748 			       unsigned long *android_load_address,
749 			       char *slot_suffix)
750 {
751 	const char *requested_partitions[] = {
752 		boot_partname,
753 		NULL,
754 		NULL,
755 		NULL,
756 	};
757 	struct AvbOpsData *data;
758 	struct blk_desc *dev_desc;
759 	struct andr_img_hdr *hdr;
760 	disk_partition_t part_info;
761 	uint8_t unlocked = true;
762 	AvbOps *ops;
763 	AvbSlotVerifyFlags flags;
764 	AvbSlotVerifyData *slot_data = {NULL};
765 	AvbSlotVerifyResult verify_result;
766 	AvbABData ab_data, ab_data_orig;
767 	size_t slot_index_to_boot = 0;
768 	char verify_state[38] = {0};
769 	char can_boot = 1;
770 	char retry_no_vbmeta_partition = 1;
771 	unsigned long load_address = *android_load_address;
772 	int ret;
773 
774 	dev_desc = rockchip_get_bootdev();
775 	if (!dev_desc)
776 		return AVB_IO_RESULT_ERROR_IO;
777 
778 	if (part_get_info_by_name(dev_desc, boot_partname, &part_info) < 0) {
779 		printf("Could not find \"%s\" partition\n", boot_partname);
780 		return AVB_IO_RESULT_ERROR_NO_SUCH_PARTITION;
781 	}
782 
783 	hdr = populate_andr_img_hdr(dev_desc, &part_info);
784 	if (!hdr) {
785 		printf("No valid android hdr\n");
786 		return AVB_IO_RESULT_ERROR_NO_SUCH_VALUE;
787 	}
788 
789 	if (hdr->header_version >= 4) {
790 		requested_partitions[1] = ANDROID_PARTITION_VENDOR_BOOT;
791 		if (((hdr->os_version >> 25) & 0x7f) >= 13)
792 			requested_partitions[2] = ANDROID_PARTITION_INIT_BOOT;
793 	}
794 
795 	ops = avb_ops_user_new();
796 	if (ops == NULL) {
797 		printf("avb_ops_user_new() failed!\n");
798 		return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
799 	}
800 
801 	if (ops->read_is_device_unlocked(ops, (bool *)&unlocked) != AVB_IO_RESULT_OK)
802 		printf("Error determining whether device is unlocked.\n");
803 
804 	printf("read_is_device_unlocked() ops returned that device is %s\n",
805 	       (unlocked & LOCK_MASK)? "UNLOCKED" : "LOCKED");
806 
807 	flags = AVB_SLOT_VERIFY_FLAGS_NONE;
808 	if (unlocked & LOCK_MASK)
809 		flags |= AVB_SLOT_VERIFY_FLAGS_ALLOW_VERIFICATION_ERROR;
810 
811 	if (load_metadata(ops->ab_ops, &ab_data, &ab_data_orig)) {
812 		printf("Can not load metadata\n");
813 		return AVB_SLOT_VERIFY_RESULT_ERROR_IO;
814 	}
815 
816 	if (!strncmp(slot_suffix, "_a", 2))
817 		slot_index_to_boot = 0;
818 	else if (!strncmp(slot_suffix, "_b", 2))
819 		slot_index_to_boot = 1;
820 	else
821 		slot_index_to_boot = 0;
822 
823 	if (strcmp(boot_partname, ANDROID_PARTITION_RECOVERY) == 0)
824 		flags |= AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION;
825 
826 #ifdef CONFIG_MP_BOOT
827 	preload_user_data.boot.addr = (void *)mpb_post(1);
828 	preload_user_data.boot.size = (size_t)mpb_post(2);
829 #endif
830 
831 	/* use preload one if available */
832 	if (preload_user_data.boot.addr) {
833 		data = (struct AvbOpsData *)(ops->user_data);
834 
835 		data->slot_suffix = slot_suffix;
836 		data->boot = preload_user_data.boot;
837 		data->vendor_boot = preload_user_data.vendor_boot;
838 		data->init_boot = preload_user_data.init_boot;
839 		data->resource = preload_user_data.resource;
840 	} else {
841 		ret = avb_image_distribute_prepare(slot_data, ops, slot_suffix);
842 		if (ret < 0) {
843 			printf("avb image distribute prepare failed %d\n", ret);
844 			return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
845 		}
846 	}
847 
848 retry_verify:
849 	verify_result =
850 	avb_slot_verify(ops,
851 			requested_partitions,
852 			slot_suffix,
853 			flags,
854 			AVB_HASHTREE_ERROR_MODE_RESTART,
855 			&slot_data);
856 	if (verify_result != AVB_SLOT_VERIFY_RESULT_OK &&
857 	    verify_result != AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED) {
858 		if (retry_no_vbmeta_partition && strcmp(boot_partname, ANDROID_PARTITION_RECOVERY) == 0) {
859 			printf("Verify recovery with vbmeta.\n");
860 			flags &= ~AVB_SLOT_VERIFY_FLAGS_NO_VBMETA_PARTITION;
861 			retry_no_vbmeta_partition = 0;
862 			goto retry_verify;
863 		}
864 	}
865 
866 	strcat(verify_state, ANDROID_VERIFY_STATE);
867 	switch (verify_result) {
868 	case AVB_SLOT_VERIFY_RESULT_OK:
869 		if (unlocked & LOCK_MASK)
870 			strcat(verify_state, "orange");
871 		else
872 			strcat(verify_state, "green");
873 		break;
874 	case AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED:
875 		if (unlocked & LOCK_MASK)
876 			strcat(verify_state, "orange");
877 		else
878 			strcat(verify_state, "yellow");
879 		break;
880 	case AVB_SLOT_VERIFY_RESULT_ERROR_OOM:
881 	case AVB_SLOT_VERIFY_RESULT_ERROR_IO:
882 	case AVB_SLOT_VERIFY_RESULT_ERROR_INVALID_METADATA:
883 	case AVB_SLOT_VERIFY_RESULT_ERROR_UNSUPPORTED_VERSION:
884 	case AVB_SLOT_VERIFY_RESULT_ERROR_VERIFICATION:
885 	case AVB_SLOT_VERIFY_RESULT_ERROR_ROLLBACK_INDEX:
886 	default:
887 		if (unlocked & LOCK_MASK)
888 			strcat(verify_state, "orange");
889 		else
890 			strcat(verify_state, "red");
891 		break;
892 	}
893 
894 	if (!slot_data) {
895 		can_boot = 0;
896 		goto out;
897 	}
898 
899 	if (verify_result == AVB_SLOT_VERIFY_RESULT_OK ||
900 	    verify_result == AVB_SLOT_VERIFY_RESULT_ERROR_PUBLIC_KEY_REJECTED ||
901 	    (unlocked & LOCK_MASK)) {
902 		int len = 0;
903 		char *bootargs, *newbootargs;
904 #ifdef CONFIG_ANDROID_AVB_ROLLBACK_INDEX
905 		if (rk_avb_update_stored_rollback_indexes_for_slot(ops, slot_data))
906 			printf("Fail to update the rollback indexes.\n");
907 #endif
908 		if (slot_data->cmdline) {
909 			debug("Kernel command line: %s\n", slot_data->cmdline);
910 			len += strlen(slot_data->cmdline);
911 		}
912 
913 		bootargs = env_get("bootargs");
914 		if (bootargs)
915 			len += strlen(bootargs);
916 
917 		newbootargs = malloc(len + 2);
918 
919 		if (!newbootargs) {
920 			puts("Error: malloc in android_slot_verify failed!\n");
921 			return AVB_SLOT_VERIFY_RESULT_ERROR_OOM;
922 		}
923 		*newbootargs = '\0';
924 
925 		if (bootargs) {
926 			strcpy(newbootargs, bootargs);
927 			strcat(newbootargs, " ");
928 		}
929 		if (slot_data->cmdline)
930 			strcat(newbootargs, slot_data->cmdline);
931 		env_set("bootargs", newbootargs);
932 
933 		/* if need, distribute full image to where they should be */
934 		ret = avb_image_distribute_finish(slot_data, flags, &load_address);
935 		if (ret) {
936 			printf("avb image distribute finish failed %d\n", ret);
937 			return ret;
938 		}
939 		*android_load_address = load_address;
940 	} else {
941 		slot_set_unbootable(&ab_data.slots[slot_index_to_boot]);
942 	}
943 
944 out:
945 	env_update("bootargs", verify_state);
946 	if (save_metadata_if_changed(ops->ab_ops, &ab_data, &ab_data_orig)) {
947 		printf("Can not save metadata\n");
948 		verify_result = AVB_SLOT_VERIFY_RESULT_ERROR_IO;
949 	}
950 
951 	if (slot_data != NULL)
952 		avb_slot_verify_data_free(slot_data);
953 
954 	if ((unlocked & LOCK_MASK) && can_boot)
955 		return 0;
956 	else
957 		return verify_result;
958 }
959 #endif
960 
961 #if defined(CONFIG_CMD_DTIMG) && defined(CONFIG_OF_LIBFDT_OVERLAY)
962 
963 /*
964  * Default return index 0.
965  */
board_select_fdt_index(ulong dt_table_hdr)966 __weak int board_select_fdt_index(ulong dt_table_hdr)
967 {
968 /*
969  * User can use "dt_for_each_entry(entry, hdr, idx)" to iterate
970  * over all dt entry of DT image and pick up which they want.
971  *
972  * Example:
973  *	struct dt_table_entry *entry;
974  *	int index;
975  *
976  *	dt_for_each_entry(entry, dt_table_hdr, index) {
977  *
978  *		.... (use entry)
979  *	}
980  *
981  *	return index;
982  */
983 	return 0;
984 }
985 
android_get_dtbo(ulong * fdt_dtbo,const struct andr_img_hdr * hdr,int * index,const char * part_dtbo)986 static int android_get_dtbo(ulong *fdt_dtbo,
987 			    const struct andr_img_hdr *hdr,
988 			    int *index, const char *part_dtbo)
989 {
990 	struct dt_table_header *dt_hdr = NULL;
991 	struct blk_desc *dev_desc;
992 	disk_partition_t part_info;
993 	u32 blk_offset, blk_cnt;
994 	void *buf;
995 	ulong e_addr;
996 	u32 e_size;
997 	int e_idx;
998 	int ret;
999 
1000 	/* Get partition info */
1001 	dev_desc = rockchip_get_bootdev();
1002 	if (!dev_desc)
1003 		return -ENODEV;
1004 
1005 	ret = part_get_info_by_name(dev_desc, part_dtbo, &part_info);
1006 	if (ret < 0) {
1007 		printf("No %s partition, ret=%d\n", part_dtbo, ret);
1008 		return ret;
1009 	}
1010 
1011 	/* Check dt table header */
1012 	if (!strcmp(part_dtbo, PART_RECOVERY))
1013 		blk_offset = part_info.start +
1014 			     (hdr->recovery_dtbo_offset / part_info.blksz);
1015 	else
1016 		blk_offset = part_info.start;
1017 
1018 	dt_hdr = memalign(ARCH_DMA_MINALIGN, part_info.blksz);
1019 	if (!dt_hdr)
1020 		return -ENOMEM;
1021 
1022 	ret = blk_dread(dev_desc, blk_offset, 1, dt_hdr);
1023 	if (ret != 1)
1024 		goto out1;
1025 
1026 	if (!android_dt_check_header((ulong)dt_hdr)) {
1027 		printf("DTBO: invalid dt table header: 0x%x\n", dt_hdr->magic);
1028 		ret = -EINVAL;
1029 		goto out1;
1030 	}
1031 
1032 #ifdef DEBUG
1033 	android_dt_print_contents((ulong)dt_hdr);
1034 #endif
1035 
1036 	blk_cnt = DIV_ROUND_UP(fdt32_to_cpu(dt_hdr->total_size),
1037 			       part_info.blksz);
1038 	/* Read all DT Image */
1039 	buf = memalign(ARCH_DMA_MINALIGN, part_info.blksz * blk_cnt);
1040 	if (!buf) {
1041 		ret = -ENOMEM;
1042 		goto out1;
1043 	}
1044 
1045 	ret = blk_dread(dev_desc, blk_offset, blk_cnt, buf);
1046 	if (ret != blk_cnt)
1047 		goto out2;
1048 
1049 	e_idx = board_select_fdt_index((ulong)buf);
1050 	if (e_idx < 0) {
1051 		printf("%s: failed to select board fdt index\n", __func__);
1052 		ret = -EINVAL;
1053 		goto out2;
1054 	}
1055 
1056 	ret = android_dt_get_fdt_by_index((ulong)buf, e_idx, &e_addr, &e_size);
1057 	if (!ret) {
1058 		printf("%s: failed to get fdt, index=%d\n", __func__, e_idx);
1059 		ret = -EINVAL;
1060 		goto out2;
1061 	}
1062 
1063 	if (fdt_dtbo)
1064 		*fdt_dtbo = e_addr;
1065 	if (index)
1066 		*index = e_idx;
1067 
1068 	free(dt_hdr);
1069 	debug("ANDROID: Loading dt entry to 0x%lx size 0x%x idx %d from \"%s\" part\n",
1070 	      e_addr, e_size, e_idx, part_dtbo);
1071 
1072 	return 0;
1073 
1074 out2:
1075 	free(buf);
1076 out1:
1077 	free(dt_hdr);
1078 
1079 	return ret;
1080 }
1081 
android_fdt_overlay_apply(void * fdt_addr)1082 int android_fdt_overlay_apply(void *fdt_addr)
1083 {
1084 	struct andr_img_hdr *hdr;
1085 	struct blk_desc *dev_desc;
1086 	const char *part_boot = PART_BOOT;
1087 	disk_partition_t part_info;
1088 	char *fdt_backup;
1089 	char *part_dtbo = PART_DTBO;
1090 	char buf[32] = {0};
1091 	ulong fdt_dtbo = -1;
1092 	u32 totalsize;
1093 	int index = -1;
1094 	int ret;
1095 
1096 	if (rockchip_get_boot_mode() == BOOT_MODE_RECOVERY) {
1097 #ifdef CONFIG_ANDROID_AB
1098 		bool can_find_recovery;
1099 
1100 		can_find_recovery = ab_can_find_recovery_part();
1101 		part_boot = can_find_recovery ? PART_RECOVERY : PART_BOOT;
1102 		part_dtbo = can_find_recovery ? PART_RECOVERY : PART_DTBO;
1103 #else
1104 		part_boot = PART_RECOVERY;
1105 		part_dtbo = PART_RECOVERY;
1106 #endif
1107 	}
1108 
1109 	dev_desc = rockchip_get_bootdev();
1110 	if (!dev_desc)
1111 		return -ENODEV;
1112 
1113 	ret = part_get_info_by_name(dev_desc, part_boot, &part_info);
1114 	if (ret < 0)
1115 		return ret;
1116 
1117 	hdr = populate_andr_img_hdr(dev_desc, &part_info);
1118 	if (!hdr)
1119 		return -EINVAL;
1120 #ifdef DEBUG
1121 	android_print_contents(hdr);
1122 #endif
1123 
1124 	/*
1125 	 * Google requires a/b system mandory from Android Header v3 for
1126 	 * google authentication, that means there is not recovery.
1127 	 *
1128 	 * But for the products that don't care about google authentication,
1129 	 * it's not mandory to use a/b system. So that we use the solution:
1130 	 * boot.img(v3+) with recovery(v2).
1131 	 *
1132 	 * [recovery_dtbo fields]
1133 	 *	recovery.img with boot_img_hdr_v1,2:  supported
1134 	 *	recovery.img with boot_img_hdr_v0,3+: illegal
1135 	 */
1136 	if ((hdr->header_version == 0) ||
1137 	    (hdr->header_version >= 3 && !strcmp(part_boot, PART_RECOVERY)))
1138 		goto out;
1139 
1140 	ret = android_get_dtbo(&fdt_dtbo, (void *)hdr, &index, part_dtbo);
1141 	if (!ret) {
1142 		phys_size_t fdt_size;
1143 
1144 		/* Must incease size before overlay */
1145 		fdt_size = fdt_totalsize((void *)fdt_addr) +
1146 				fdt_totalsize((void *)fdt_dtbo);
1147 		if (sysmem_free((phys_addr_t)fdt_addr))
1148 			goto out;
1149 
1150 		if (!sysmem_alloc_base(MEM_FDT_DTBO,
1151 				       (phys_addr_t)fdt_addr,
1152 					fdt_size + CONFIG_SYS_FDT_PAD))
1153 			goto out;
1154 		/*
1155 		 * Backup main fdt in case of being destroyed by
1156 		 * fdt_overlay_apply() when it overlys failed.
1157 		 */
1158 		totalsize = fdt_totalsize(fdt_addr);
1159 		fdt_backup = malloc(totalsize);
1160 		if (!fdt_backup)
1161 			goto out;
1162 
1163 		memcpy(fdt_backup, fdt_addr, totalsize);
1164 		fdt_increase_size(fdt_addr, fdt_totalsize((void *)fdt_dtbo));
1165 		ret = fdt_overlay_apply(fdt_addr, (void *)fdt_dtbo);
1166 		if (!ret) {
1167 			snprintf(buf, 32, "%s%d", "androidboot.dtbo_idx=", index);
1168 			env_update("bootargs", buf);
1169 			printf("ANDROID: fdt overlay OK\n");
1170 		} else {
1171 			memcpy(fdt_addr, fdt_backup, totalsize);
1172 			printf("ANDROID: fdt overlay failed, ret=%d\n", ret);
1173 		}
1174 
1175 		free(fdt_backup);
1176 	}
1177 
1178 out:
1179 	free(hdr);
1180 
1181 	return 0;
1182 }
1183 #endif
1184 
android_image_load_by_partname(struct blk_desc * dev_desc,const char * boot_partname,unsigned long * load_address)1185 int android_image_load_by_partname(struct blk_desc *dev_desc,
1186 				   const char *boot_partname,
1187 				   unsigned long *load_address)
1188 {
1189 	disk_partition_t boot_part;
1190 	int ret, part_num;
1191 
1192 	part_num = part_get_info_by_name(dev_desc, boot_partname, &boot_part);
1193 	if (part_num < 0) {
1194 		printf("%s: Can't find part: %s\n", __func__, boot_partname);
1195 		return -1;
1196 	}
1197 	debug("ANDROID: Loading kernel from \"%s\", partition %d.\n",
1198 	      boot_part.name, part_num);
1199 
1200 	ret = android_image_load(dev_desc, &boot_part, *load_address, -1UL);
1201 	if (ret < 0) {
1202 		debug("%s: %s part load fail, ret=%d\n",
1203 		      __func__, boot_part.name, ret);
1204 		return ret;
1205 	}
1206 	*load_address = ret;
1207 
1208 	return 0;
1209 }
1210 
android_bootloader_boot_flow(struct blk_desc * dev_desc,unsigned long load_address)1211 int android_bootloader_boot_flow(struct blk_desc *dev_desc,
1212 				 unsigned long load_address)
1213 {
1214 	enum android_boot_mode mode = ANDROID_BOOT_MODE_NORMAL;
1215 	disk_partition_t misc_part_info;
1216 	int part_num;
1217 	char *command_line;
1218 	char slot_suffix[3] = {0};
1219 	const char *mode_cmdline = NULL;
1220 	char *boot_partname = ANDROID_PARTITION_BOOT;
1221 
1222 	/*
1223 	 * 1. Load MISC partition and determine the boot mode
1224 	 *   clear its value for the next boot if needed.
1225 	 */
1226 	part_num = part_get_info_by_name(dev_desc, ANDROID_PARTITION_MISC,
1227 					 &misc_part_info);
1228 	if (part_num < 0) {
1229 		printf("Could not find misc partition\n");
1230 	} else {
1231 #ifdef CONFIG_ANDROID_KEYMASTER_CA
1232 		/* load attestation key from misc partition. */
1233 		load_attestation_key(dev_desc, &misc_part_info);
1234 #endif
1235 
1236 		mode = android_bootloader_load_and_clear_mode(dev_desc,
1237 							      &misc_part_info);
1238 #ifdef CONFIG_RKIMG_BOOTLOADER
1239 		if (mode == ANDROID_BOOT_MODE_NORMAL) {
1240 			if (rockchip_get_boot_mode() == BOOT_MODE_RECOVERY)
1241 				mode = ANDROID_BOOT_MODE_RECOVERY;
1242 		}
1243 #endif
1244 	}
1245 
1246 	printf("ANDROID: reboot reason: \"%s\"\n", android_boot_mode_str(mode));
1247 #ifdef CONFIG_ANDROID_AB
1248 	/* Get current slot_suffix */
1249 	if (ab_get_slot_suffix(slot_suffix))
1250 		return -1;
1251 #endif
1252 	switch (mode) {
1253 	case ANDROID_BOOT_MODE_NORMAL:
1254 		/* In normal mode, we load the kernel from "boot" but append
1255 		 * "skip_initramfs" to the cmdline to make it ignore the
1256 		 * recovery initramfs in the boot partition.
1257 		 */
1258 #ifdef CONFIG_ANDROID_AB
1259 		/*  In A/B, the recovery image is built as boot.img, containing the
1260 		* recovery's ramdisk. Previously, bootloader used the skip_initramfs
1261 		* kernel command line parameter to decide which mode to boot into.
1262 		* For Android >=10 and with dynamic partition support, the bootloader
1263 		* MUST NOT pass skip_initramfs to the kernel command-line.
1264 		* Instead, bootloader should pass androidboot.force_normal_boot=1
1265 		* and then Android's first-stage init in ramdisk
1266 		* will skip recovery and boot normal Android.
1267 		*/
1268 		if (ab_is_support_dynamic_partition(dev_desc)) {
1269 			mode_cmdline = "androidboot.force_normal_boot=1";
1270 		} else {
1271 			mode_cmdline = "skip_initramfs";
1272 		}
1273 #endif
1274 		break;
1275 	case ANDROID_BOOT_MODE_RECOVERY:
1276 		/*
1277 		 * In recovery mode, if have recovery partition, we still boot the
1278 		 * kernel from "recovery". If not, don't skip the initramfs so it
1279 		 * boots to recovery from image in partition "boot".
1280 		 */
1281 #ifdef CONFIG_ANDROID_AB
1282 		boot_partname = ab_can_find_recovery_part() ?
1283 			ANDROID_PARTITION_RECOVERY : ANDROID_PARTITION_BOOT;
1284 #else
1285 		boot_partname = ANDROID_PARTITION_RECOVERY;
1286 #endif
1287 		break;
1288 	case ANDROID_BOOT_MODE_BOOTLOADER:
1289 		/* Bootloader mode enters fastboot. If this operation fails we
1290 		 * simply return since we can't recover from this situation by
1291 		 * switching to another slot.
1292 		 */
1293 		return android_bootloader_boot_bootloader();
1294 	}
1295 
1296 #ifdef CONFIG_ANDROID_AVB
1297 	uint8_t vboot_flag = 0;
1298 	disk_partition_t vbmeta_part_info;
1299 
1300 #ifdef CONFIG_OPTEE_CLIENT
1301 	if (trusty_read_vbootkey_enable_flag(&vboot_flag)) {
1302 		printf("Can't read vboot flag\n");
1303 		return -1;
1304 	}
1305 #endif
1306 	if (vboot_flag) {
1307 		printf("Vboot=1, SecureBoot enabled, AVB verify\n");
1308 		if (android_slot_verify(boot_partname, &load_address,
1309 					slot_suffix)) {
1310 			printf("AVB verify failed\n");
1311 
1312 			return -1;
1313 		}
1314 	} else {
1315 		part_num = part_get_info_by_name(dev_desc,
1316 						 ANDROID_PARTITION_VBMETA,
1317 						 &vbmeta_part_info);
1318 		if (part_num < 0) {
1319 			printf("Not AVB images, AVB skip\n");
1320 			env_update("bootargs",
1321 				   "androidboot.verifiedbootstate=orange");
1322 			if (android_image_load_by_partname(dev_desc,
1323 							   boot_partname,
1324 							   &load_address)) {
1325 				printf("Android image load failed\n");
1326 				return -1;
1327 			}
1328 		} else {
1329 			printf("Vboot=0, AVB images, AVB verify\n");
1330 			if (android_slot_verify(boot_partname, &load_address,
1331 						slot_suffix)) {
1332 				printf("AVB verify failed\n");
1333 
1334 				return -1;
1335 			}
1336 		}
1337 	}
1338 #else
1339 	/*
1340 	 * 2. Load the boot/recovery from the desired "boot" partition.
1341 	 * Determine if this is an AOSP image.
1342 	 */
1343 	if (android_image_load_by_partname(dev_desc,
1344 					   boot_partname,
1345 					   &load_address)) {
1346 		printf("Android image load failed\n");
1347 		return -1;
1348 	}
1349 #endif
1350 
1351 	/* Set Android root variables. */
1352 	env_set_ulong("android_root_devnum", dev_desc->devnum);
1353 	env_set("android_slotsufix", slot_suffix);
1354 
1355 #ifdef CONFIG_FASTBOOT_OEM_UNLOCK
1356 	/* read oem unlock status and attach to bootargs */
1357 	uint8_t unlock = 0;
1358 	TEEC_Result result;
1359 	char oem_unlock[OEM_UNLOCK_ARG_SIZE] = {0};
1360 	result = trusty_read_oem_unlock(&unlock);
1361 	if (result) {
1362 		printf("read oem unlock status with error : 0x%x\n", result);
1363 	} else {
1364 		snprintf(oem_unlock, OEM_UNLOCK_ARG_SIZE, "androidboot.oem_unlocked=%d", unlock);
1365 		env_update("bootargs", oem_unlock);
1366 	}
1367 #endif
1368 
1369 	/* Assemble the command line */
1370 	command_line = android_assemble_cmdline(slot_suffix, mode_cmdline);
1371 	env_update("bootargs", command_line);
1372 
1373 	debug("ANDROID: bootargs: \"%s\"\n", command_line);
1374 
1375 #ifdef CONFIG_SUPPORT_OEM_DTB
1376 	if (android_bootloader_get_fdt(ANDROID_PARTITION_OEM,
1377 				       ANDROID_ARG_FDT_FILENAME)) {
1378 		printf("Can not get the fdt data from oem!\n");
1379 	}
1380 #endif
1381 #ifdef CONFIG_OPTEE_CLIENT
1382 	if (trusty_notify_optee_uboot_end())
1383 		printf("Close optee client failed!\n");
1384 #endif
1385 
1386 #ifdef CONFIG_AMP
1387 	return android_bootloader_boot_kernel(load_address);
1388 #else
1389 	android_bootloader_boot_kernel(load_address);
1390 
1391 	/* TODO: If the kernel doesn't boot mark the selected slot as bad. */
1392 	return -1;
1393 #endif
1394 }
1395 
android_avb_boot_flow(unsigned long kernel_address)1396 int android_avb_boot_flow(unsigned long kernel_address)
1397 {
1398 	struct blk_desc *dev_desc;
1399 	disk_partition_t boot_part_info;
1400 	int ret;
1401 
1402 	dev_desc = rockchip_get_bootdev();
1403 	if (!dev_desc) {
1404 		printf("%s: dev_desc is NULL!\n", __func__);
1405 		return -1;
1406 	}
1407 
1408 	/* Load the kernel from the desired "boot" partition. */
1409 	ret = part_get_info_by_name(dev_desc, ANDROID_PARTITION_BOOT,
1410 				    &boot_part_info);
1411 	if (ret < 0) {
1412 		printf("%s: failed to get boot part\n", __func__);
1413 		return ret;
1414 	}
1415 
1416 	ret = android_image_load(dev_desc, &boot_part_info,
1417 				 kernel_address, -1UL);
1418 	if (ret < 0) {
1419 		printf("Android avb boot failed, error %d.\n", ret);
1420 		return ret;
1421 	}
1422 
1423 	android_bootloader_boot_kernel(kernel_address);
1424 
1425 	/* TODO: If the kernel doesn't boot mark the selected slot as bad. */
1426 	return -1;
1427 }
1428 
android_boot_flow(unsigned long kernel_address)1429 int android_boot_flow(unsigned long kernel_address)
1430 {
1431 	struct blk_desc *dev_desc;
1432 	disk_partition_t boot_part_info;
1433 	int ret;
1434 
1435 	dev_desc = rockchip_get_bootdev();
1436 	if (!dev_desc) {
1437 		printf("%s: dev_desc is NULL!\n", __func__);
1438 		return -1;
1439 	}
1440 	/* Load the kernel from the desired "boot" partition. */
1441 	ret = part_get_info_by_name(dev_desc, ANDROID_PARTITION_BOOT,
1442 				    &boot_part_info);
1443 	if (ret < 0) {
1444 		printf("%s: failed to get boot part\n", __func__);
1445 		return ret;
1446 	}
1447 
1448 	ret = android_image_load(dev_desc, &boot_part_info, kernel_address,
1449 				 -1UL);
1450 	if (ret < 0)
1451 		return ret;
1452 
1453 	android_bootloader_boot_kernel(kernel_address);
1454 
1455 	/* TODO: If the kernel doesn't boot mark the selected slot as bad. */
1456 	return -1;
1457 }
1458