xref: /rk3399_rockchip-uboot/common/image-android.c (revision eb4b0e9c673773f1cf9f84d2d2912df8a8df1adc)
1 /*
2  * Copyright (c) 2011 Sebastian Andrzej Siewior <bigeasy@linutronix.de>
3  *
4  * SPDX-License-Identifier:	GPL-2.0+
5  */
6 
7 #include <common.h>
8 #include <image.h>
9 #include <android_image.h>
10 #include <android_bootloader.h>
11 #include <malloc.h>
12 #include <mapmem.h>
13 #include <errno.h>
14 #include <boot_rkimg.h>
15 #include <crypto.h>
16 #include <sysmem.h>
17 #include <u-boot/sha1.h>
18 #ifdef CONFIG_RKIMG_BOOTLOADER
19 #include <asm/arch/resource_img.h>
20 #endif
21 #ifdef CONFIG_RK_AVB_LIBAVB_USER
22 #include <android_avb/avb_slot_verify.h>
23 #include <android_avb/avb_ops_user.h>
24 #include <android_avb/rk_avb_ops_user.h>
25 #endif
26 #include <optee_include/OpteeClientInterface.h>
27 
28 DECLARE_GLOBAL_DATA_PTR;
29 
30 #define ANDROID_IMAGE_DEFAULT_KERNEL_ADDR	0x10008000
31 #define ANDROID_ARG_FDT_FILENAME		"rk-kernel.dtb"
32 #define ANDROID_Q_VER				10
33 #define ANDROID_PARTITION_VENDOR_BOOT		"vendor_boot"
34 
35 #define BLK_CNT(_num_bytes, _block_size)	\
36 		((_num_bytes + _block_size - 1) / _block_size)
37 
38 static char andr_tmp_str[ANDR_BOOT_ARGS_SIZE + 1];
39 static u32 android_kernel_comp_type = IH_COMP_NONE;
40 
41 u32 android_image_major_version(void)
42 {
43 	/* MSB 7-bits */
44 	return gd->bd->bi_andr_version >> 25;
45 }
46 
47 u32 android_bcb_msg_sector_offset(void)
48 {
49 	/*
50 	 * Rockchip platforms defines BCB message at the 16KB offset of
51 	 * misc partition while the Google defines it at 0x00 offset.
52 	 *
53 	 * From Android-Q, the 0x00 offset is mandary on Google VTS, so that
54 	 * this is a compatibility according to android image 'os_version'.
55 	 */
56 #ifdef CONFIG_RKIMG_BOOTLOADER
57 	return (android_image_major_version() >= ANDROID_Q_VER) ? 0x00 : 0x20;
58 #else
59 	return 0x00;
60 #endif
61 }
62 
63 static ulong android_image_get_kernel_addr(const struct andr_img_hdr *hdr)
64 {
65 	/*
66 	 * All the Android tools that generate a boot.img use this
67 	 * address as the default.
68 	 *
69 	 * Even though it doesn't really make a lot of sense, and it
70 	 * might be valid on some platforms, we treat that address as
71 	 * the default value for this field, and try to execute the
72 	 * kernel in place in such a case.
73 	 *
74 	 * Otherwise, we will return the actual value set by the user.
75 	 */
76 	if (hdr->kernel_addr == ANDROID_IMAGE_DEFAULT_KERNEL_ADDR)
77 		return (ulong)hdr + hdr->page_size;
78 
79 #ifdef CONFIG_ARCH_ROCKCHIP
80 	/*
81 	 * If kernel is compressed, kernel_addr is set as decompressed address
82 	 * after compressed being loaded to ram, so let's use it.
83 	 */
84 	if (android_kernel_comp_type != IH_COMP_NONE &&
85 	    android_kernel_comp_type != IH_COMP_ZIMAGE)
86 		return hdr->kernel_addr;
87 
88 	/*
89 	 * Compatble with rockchip legacy packing with kernel/ramdisk/second
90 	 * address base from 0x60000000(SDK versiont < 8.1), these are invalid
91 	 * address, so we calc it by real size.
92 	 */
93 	return (ulong)hdr + hdr->page_size;
94 #else
95 	return hdr->kernel_addr;
96 #endif
97 
98 }
99 
100 void android_image_set_comp(struct andr_img_hdr *hdr, u32 comp)
101 {
102 	android_kernel_comp_type = comp;
103 }
104 
105 u32 android_image_get_comp(const struct andr_img_hdr *hdr)
106 {
107 	return android_kernel_comp_type;
108 }
109 
110 int android_image_parse_kernel_comp(const struct andr_img_hdr *hdr)
111 {
112 	ulong kaddr = android_image_get_kernel_addr(hdr);
113 	return bootm_parse_comp((const unsigned char *)kaddr);
114 }
115 
116 /**
117  * android_image_get_kernel() - processes kernel part of Android boot images
118  * @hdr:	Pointer to image header, which is at the start
119  *			of the image.
120  * @verify:	Checksum verification flag. Currently unimplemented.
121  * @os_data:	Pointer to a ulong variable, will hold os data start
122  *			address.
123  * @os_len:	Pointer to a ulong variable, will hold os data length.
124  *
125  * This function returns the os image's start address and length. Also,
126  * it appends the kernel command line to the bootargs env variable.
127  *
128  * Return: Zero, os start address and length on success,
129  *		otherwise on failure.
130  */
131 int android_image_get_kernel(const struct andr_img_hdr *hdr, int verify,
132 			     ulong *os_data, ulong *os_len)
133 {
134 	u32 kernel_addr = android_image_get_kernel_addr(hdr);
135 	const char *cmdline = hdr->header_version < 3 ?
136 			      hdr->cmdline : hdr->total_cmdline;
137 	/*
138 	 * Not all Android tools use the id field for signing the image with
139 	 * sha1 (or anything) so we don't check it. It is not obvious that the
140 	 * string is null terminated so we take care of this.
141 	 */
142 	strncpy(andr_tmp_str, hdr->name, ANDR_BOOT_NAME_SIZE);
143 	andr_tmp_str[ANDR_BOOT_NAME_SIZE] = '\0';
144 	if (strlen(andr_tmp_str))
145 		printf("Android's image name: %s\n", andr_tmp_str);
146 
147 	printf("Kernel load addr 0x%08x size %u KiB\n",
148 	       kernel_addr, DIV_ROUND_UP(hdr->kernel_size, 1024));
149 
150 	int len = 0;
151 	if (cmdline) {
152 		debug("Kernel command line: %s\n", cmdline);
153 		len += strlen(cmdline);
154 	}
155 
156 	char *bootargs = env_get("bootargs");
157 	if (bootargs)
158 		len += strlen(bootargs);
159 
160 	char *newbootargs = malloc(len + 2);
161 	if (!newbootargs) {
162 		puts("Error: malloc in android_image_get_kernel failed!\n");
163 		return -ENOMEM;
164 	}
165 	*newbootargs = '\0';
166 
167 	if (bootargs) {
168 		strcpy(newbootargs, bootargs);
169 		strcat(newbootargs, " ");
170 	}
171 	if (cmdline)
172 		strcat(newbootargs, cmdline);
173 
174 	env_set("bootargs", newbootargs);
175 
176 	if (os_data) {
177 		*os_data = (ulong)hdr;
178 		*os_data += hdr->page_size;
179 	}
180 	if (os_len)
181 		*os_len = hdr->kernel_size;
182 	return 0;
183 }
184 
185 int android_image_check_header(const struct andr_img_hdr *hdr)
186 {
187 	return memcmp(ANDR_BOOT_MAGIC, hdr->magic, ANDR_BOOT_MAGIC_SIZE);
188 }
189 
190 ulong android_image_get_end(const struct andr_img_hdr *hdr)
191 {
192 	ulong end;
193 	/*
194 	 * The header takes a full page, the remaining components are aligned
195 	 * on page boundary
196 	 */
197 	end = (ulong)hdr;
198 	if (hdr->header_version < 3) {
199 		end += hdr->page_size;
200 		end += ALIGN(hdr->kernel_size, hdr->page_size);
201 		end += ALIGN(hdr->ramdisk_size, hdr->page_size);
202 		end += ALIGN(hdr->second_size, hdr->page_size);
203 		if (hdr->header_version == 1) {
204 			end += ALIGN(hdr->recovery_dtbo_size, hdr->page_size);
205 		} else if (hdr->header_version == 2) {
206 			end += ALIGN(hdr->recovery_dtbo_size, hdr->page_size);
207 			end += ALIGN(hdr->dtb_size, hdr->page_size);
208 		}
209 	} else {
210 		/* boot_img_hdr_v3 */
211 		end += hdr->page_size;
212 		end += ALIGN(hdr->kernel_size, hdr->page_size);
213 		end += ALIGN(hdr->ramdisk_size, hdr->page_size);
214 	}
215 
216 	return end;
217 }
218 
219 u32 android_image_get_ksize(const struct andr_img_hdr *hdr)
220 {
221 	return hdr->kernel_size;
222 }
223 
224 void android_image_set_kload(struct andr_img_hdr *hdr, u32 load_address)
225 {
226 	hdr->kernel_addr = load_address;
227 }
228 
229 ulong android_image_get_kload(const struct andr_img_hdr *hdr)
230 {
231 	return android_image_get_kernel_addr(hdr);
232 }
233 
234 int android_image_get_ramdisk(const struct andr_img_hdr *hdr,
235 			      ulong *rd_data, ulong *rd_len)
236 {
237 	ulong ramdisk_addr_r;
238 
239 	if (!hdr->ramdisk_size) {
240 		*rd_data = *rd_len = 0;
241 		return -1;
242 	}
243 
244 	/* Have been loaded by android_image_load_separate() on ramdisk_addr_r */
245 	ramdisk_addr_r = env_get_ulong("ramdisk_addr_r", 16, 0);
246 	if (!ramdisk_addr_r) {
247 		printf("No Found Ramdisk Load Address.\n");
248 		return -1;
249 	}
250 
251 	*rd_data = ramdisk_addr_r;
252 	*rd_len = hdr->ramdisk_size;
253 
254 	printf("RAM disk load addr 0x%08lx ", *rd_data);
255 
256 	if (hdr->header_version < 3)
257 		printf("size %u KiB\n", DIV_ROUND_UP(hdr->ramdisk_size, 1024));
258 	else
259 		printf("size: boot %u KiB, vendor-boot %u KiB\n",
260 		       DIV_ROUND_UP(hdr->boot_ramdisk_size, 1024),
261 		       DIV_ROUND_UP(hdr->vendor_ramdisk_size, 1024));
262 	return 0;
263 }
264 
265 int android_image_get_fdt(const struct andr_img_hdr *hdr,
266 			      ulong *rd_data)
267 {
268 	ulong fdt_addr_r;
269 
270 	if (!hdr->second_size) {
271 		*rd_data = 0;
272 		return -1;
273 	}
274 
275 	/* Have been loaded by android_image_load_separate() on fdt_addr_r */
276 	fdt_addr_r = env_get_ulong("fdt_addr_r", 16, 0);
277 	if (!fdt_addr_r) {
278 		printf("No Found FDT Load Address.\n");
279 		return -1;
280 	}
281 
282 	*rd_data = fdt_addr_r;
283 
284 	debug("FDT load addr 0x%08x size %u KiB\n",
285 	      hdr->second_addr, DIV_ROUND_UP(hdr->second_size, 1024));
286 
287 	return 0;
288 }
289 
290 #if defined(CONFIG_DM_CRYPTO) && defined(CONFIG_ANDROID_BOOT_IMAGE_HASH)
291 static void print_hash(const char *label, u8 *hash, int len)
292 {
293 	int i;
294 
295 	printf("%s:\n    0x", label ? : "Hash");
296 	for (i = 0; i < len; i++)
297 		printf("%02x", hash[i]);
298 	printf("\n");
299 }
300 #endif
301 
302 typedef enum {
303 	IMG_KERNEL,
304 	IMG_RAMDISK,
305 	IMG_SECOND,
306 	IMG_RECOVERY_DTBO,
307 	IMG_RK_DTB,	/* within resource.img in second position */
308 	IMG_DTB,
309 	IMG_VENDOR_RAMDISK,
310 	IMG_MAX,
311 } img_t;
312 
313 static int image_load(img_t img, struct andr_img_hdr *hdr,
314 		      ulong blkstart, void *ram_base,
315 		      struct udevice *crypto)
316 {
317 	struct blk_desc *desc = rockchip_get_bootdev();
318 	disk_partition_t part_vendor_boot;
319 	__maybe_unused u32 typesz;
320 	ulong pgsz = hdr->page_size;
321 	ulong blksz = desc->blksz;
322 	ulong blkcnt, blkoff;
323 	ulong memmove_dst = 0;
324 	ulong bsoffs = 0;
325 	ulong extra = 0;
326 	ulong length;
327 	void *buffer;
328 	int ret = 0;
329 
330 	switch (img) {
331 	case IMG_KERNEL:
332 		bsoffs = 0; /* include a page_size(image header) */
333 		length = hdr->kernel_size + pgsz;
334 		buffer = (void *)env_get_ulong("android_addr_r", 16, 0);
335 		blkcnt = DIV_ROUND_UP(hdr->kernel_size + pgsz, blksz);
336 		typesz = sizeof(hdr->kernel_size);
337 		if (!sysmem_alloc_base(MEM_KERNEL,
338 			(phys_addr_t)buffer, blkcnt * blksz))
339 			return -ENOMEM;
340 		break;
341 	case IMG_VENDOR_RAMDISK:
342 		if (part_get_info_by_name(desc,
343 					  ANDROID_PARTITION_VENDOR_BOOT,
344 					  &part_vendor_boot) < 0) {
345 			printf("No vendor boot partition\n");
346 			return -ENOENT;
347 		}
348 		/* Always load vendor boot from storage: avb full load boot/recovery */
349 		blkstart = part_vendor_boot.start;
350 		pgsz = hdr->vendor_page_size;
351 		ram_base = 0;
352 
353 		bsoffs = ALIGN(VENDOR_BOOT_HDR_SIZE, pgsz);
354 		length = hdr->vendor_ramdisk_size;
355 		buffer = (void *)env_get_ulong("ramdisk_addr_r", 16, 0);
356 		blkcnt = DIV_ROUND_UP(hdr->vendor_ramdisk_size, blksz);
357 		typesz = sizeof(hdr->vendor_ramdisk_size);
358 		/*
359 		 * Add extra memory for generic ramdisk space.
360 		 *
361 		 * In case of unaligned vendor ramdisk size, reserve
362 		 * 1 more blksz.
363 		 */
364 		if (hdr->header_version == 3)
365 			extra = ALIGN(hdr->ramdisk_size, blksz) + blksz;
366 		if (length && !sysmem_alloc_base(MEM_RAMDISK,
367 			(phys_addr_t)buffer, blkcnt * blksz + extra))
368 			return -ENOMEM;
369 		break;
370 	case IMG_RAMDISK:
371 		bsoffs = pgsz + ALIGN(hdr->kernel_size, pgsz);
372 		length = hdr->ramdisk_size;
373 		buffer = (void *)env_get_ulong("ramdisk_addr_r", 16, 0);
374 		blkcnt = DIV_ROUND_UP(hdr->ramdisk_size, blksz);
375 		typesz = sizeof(hdr->ramdisk_size);
376 
377 		/*
378 		 * ramdisk_addr_r:
379 		 *	|----------------|---------|
380 		 *	| vendor-ramdisk | ramdisk |
381 		 *	|----------------|---------|
382 		 */
383 		if (hdr->header_version >= 3) {
384 			buffer += hdr->vendor_ramdisk_size;
385 			if (!IS_ALIGNED((ulong)buffer, blksz)) {
386 				memmove_dst = (ulong)buffer;
387 				buffer = (void *)ALIGN(memmove_dst, blksz);
388 			}
389 		}
390 		/* sysmem has been alloced by vendor ramdisk */
391 		if (hdr->header_version < 3) {
392 			if (length && !sysmem_alloc_base(MEM_RAMDISK,
393 				(phys_addr_t)buffer, blkcnt * blksz))
394 				return -ENOMEM;
395 		}
396 		break;
397 	case IMG_SECOND:
398 		bsoffs = pgsz +
399 			 ALIGN(hdr->kernel_size, pgsz) +
400 			 ALIGN(hdr->ramdisk_size, pgsz);
401 		length = hdr->second_size;
402 		blkcnt = DIV_ROUND_UP(hdr->second_size, blksz);
403 		buffer = malloc(blkcnt * blksz);
404 		typesz = sizeof(hdr->second_size);
405 		break;
406 	case IMG_RECOVERY_DTBO:
407 		bsoffs = pgsz +
408 			 ALIGN(hdr->kernel_size, pgsz) +
409 			 ALIGN(hdr->ramdisk_size, pgsz) +
410 			 ALIGN(hdr->second_size, pgsz);
411 		length = hdr->recovery_dtbo_size;
412 		blkcnt = DIV_ROUND_UP(hdr->recovery_dtbo_size, blksz);
413 		buffer = malloc(blkcnt * blksz);
414 		typesz = sizeof(hdr->recovery_dtbo_size);
415 		break;
416 	case IMG_DTB:
417 		bsoffs = pgsz +
418 			 ALIGN(hdr->kernel_size, pgsz) +
419 			 ALIGN(hdr->ramdisk_size, pgsz) +
420 			 ALIGN(hdr->second_size, pgsz) +
421 			 ALIGN(hdr->recovery_dtbo_size, pgsz);
422 		length = hdr->dtb_size;
423 		blkcnt = DIV_ROUND_UP(hdr->dtb_size, blksz);
424 		buffer = malloc(blkcnt * blksz);
425 		typesz = sizeof(hdr->dtb_size);
426 		break;
427 	case IMG_RK_DTB:
428 #ifdef CONFIG_RKIMG_BOOTLOADER
429 		/* No going further, it handles DTBO, HW-ID, etc */
430 		buffer = (void *)env_get_ulong("fdt_addr_r", 16, 0);
431 		if (gd->fdt_blob != (void *)buffer)
432 			ret = rockchip_read_dtb_file(buffer);
433 #endif
434 		return ret < 0 ? ret : 0;
435 	default:
436 		return -EINVAL;
437 	}
438 
439 	if (!buffer) {
440 		printf("No memory for image(%d)\n", img);
441 		return -ENOMEM;
442 	}
443 
444 	if (!blksz || !length)
445 		goto crypto_calc;
446 
447 	/* load */
448 	if (ram_base) {
449 		memcpy(buffer, (char *)((ulong)ram_base + bsoffs), length);
450 	} else {
451 		blkoff = DIV_ROUND_UP(bsoffs, blksz);
452 		ret = blk_dread(desc, blkstart + blkoff, blkcnt, buffer);
453 		if (ret != blkcnt) {
454 			printf("Failed to read img(%d), ret=%d\n", img, ret);
455 			return -EIO;
456 		}
457 	}
458 
459 	if (memmove_dst)
460 		memmove((char *)memmove_dst, buffer, length);
461 
462 crypto_calc:
463 	/* sha1 */
464 #ifdef CONFIG_DM_CRYPTO
465 	if (crypto) {
466 		if (img == IMG_KERNEL) {
467 			buffer += pgsz;
468 			length -= pgsz;
469 		}
470 
471 		crypto_sha_update(crypto, (u32 *)buffer, length);
472 		crypto_sha_update(crypto, (u32 *)&length, typesz);
473 	}
474 #endif
475 
476 	return 0;
477 }
478 
479 static int images_load_verify(struct andr_img_hdr *hdr, ulong part_start,
480 			      void *ram_base, struct udevice *crypto)
481 {
482 	/* load, never change order ! */
483 	if (image_load(IMG_KERNEL, hdr, part_start, ram_base, crypto))
484 		return -1;
485 	if (image_load(IMG_RAMDISK, hdr, part_start, ram_base, crypto))
486 		return -1;
487 	if (image_load(IMG_SECOND, hdr, part_start, ram_base, crypto))
488 		return -1;
489 	if (hdr->header_version > 0) {
490 		if (image_load(IMG_RECOVERY_DTBO, hdr, part_start,
491 			       ram_base, crypto))
492 			return -1;
493 	}
494 	if (hdr->header_version > 1) {
495 		if (image_load(IMG_DTB, hdr, part_start, ram_base, crypto))
496 			return -1;
497 	}
498 
499 	return 0;
500 }
501 
502 /*
503  * @ram_base: !NULL means require memcpy for an exist full android image.
504  */
505 static int android_image_separate(struct andr_img_hdr *hdr,
506 				  const disk_partition_t *part,
507 				  void *load_address,
508 				  void *ram_base)
509 {
510 	ulong bstart;
511 	int ret;
512 
513 	if (android_image_check_header(hdr)) {
514 		printf("Bad android image header\n");
515 		return -EINVAL;
516 	}
517 
518 	/* set for image_load(IMG_KERNEL, ...) */
519 	env_set_hex("android_addr_r", (ulong)load_address);
520 	bstart = part ? part->start : 0;
521 
522 	/*
523 	 * 1. Load images to their individual target ram position
524 	 *    in order to disable fdt/ramdisk relocation.
525 	 */
526 
527 	/* load rk-kernel.dtb alone */
528 	if (image_load(IMG_RK_DTB, hdr, bstart, ram_base, NULL))
529 		return -1;
530 
531 #if defined(CONFIG_DM_CRYPTO) && defined(CONFIG_ANDROID_BOOT_IMAGE_HASH)
532 	if (hdr->header_version < 3) {
533 		struct udevice *dev;
534 		sha_context ctx;
535 		uchar hash[20];
536 
537 		ctx.length = 0;
538 		ctx.algo = CRYPTO_SHA1;
539 		dev = crypto_get_device(ctx.algo);
540 		if (!dev) {
541 			printf("Can't find crypto device for SHA1\n");
542 			return -ENODEV;
543 		}
544 
545 		/* v1 & v2: requires total length before sha init */
546 		ctx.length += hdr->kernel_size + sizeof(hdr->kernel_size) +
547 			      hdr->ramdisk_size + sizeof(hdr->ramdisk_size) +
548 			      hdr->second_size + sizeof(hdr->second_size);
549 		if (hdr->header_version > 0)
550 			ctx.length += hdr->recovery_dtbo_size +
551 						sizeof(hdr->recovery_dtbo_size);
552 		if (hdr->header_version > 1)
553 			ctx.length += hdr->dtb_size + sizeof(hdr->dtb_size);
554 
555 		crypto_sha_init(dev, &ctx);
556 		ret = images_load_verify(hdr, bstart, ram_base, dev);
557 		if (ret)
558 			return ret;
559 		crypto_sha_final(dev, &ctx, hash);
560 
561 		if (memcmp(hash, hdr->id, 20)) {
562 			print_hash("Hash from header", (u8 *)hdr->id, 20);
563 			print_hash("Hash real", (u8 *)hash, 20);
564 			return -EBADFD;
565 		} else {
566 			printf("ANDROID: Hash OK\n");
567 		}
568 	} else
569 #endif
570 	{
571 		ret = images_load_verify(hdr, bstart, ram_base, NULL);
572 		if (ret)
573 			return ret;
574 	}
575 
576 	/* 2. Disable fdt/ramdisk relocation, it saves boot time */
577 	env_set("bootm-no-reloc", "y");
578 
579 	return 0;
580 }
581 
582 static int android_image_separate_v3(struct andr_img_hdr *hdr,
583 				     const disk_partition_t *part,
584 				     void *load_address, void *ram_base)
585 {
586 	ulong bstart;
587 
588 	if (android_image_check_header(hdr)) {
589 		printf("Bad android image header\n");
590 		return -EINVAL;
591 	}
592 
593 	/* set for image_load(IMG_KERNEL, ...) */
594 	env_set_hex("android_addr_r", (ulong)load_address);
595 	bstart = part ? part->start : 0;
596 
597 	/*
598 	 * 1. Load images to their individual target ram position
599 	 *    in order to disable fdt/ramdisk relocation.
600 	 */
601 	if (image_load(IMG_RK_DTB,  hdr, bstart, ram_base, NULL))
602 		return -1;
603 	if (image_load(IMG_KERNEL,  hdr, bstart, ram_base, NULL))
604 		return -1;
605 	if (image_load(IMG_VENDOR_RAMDISK, hdr, bstart, ram_base, NULL))
606 		return -1;
607 	if (image_load(IMG_RAMDISK, hdr, bstart, ram_base, NULL))
608 		return -1;
609 
610 	/*
611 	 * Copy the populated hdr to load address after image_load(IMG_KERNEL)
612 	 *
613 	 * The image_load(IMG_KERNEL) only reads boot_img_hdr_v3 while
614 	 * vendor_boot_img_hdr_v3 is not included, so fix it here.
615 	 */
616 	memcpy((char *)load_address, hdr, hdr->page_size);
617 
618 	/* 2. Disable fdt/ramdisk relocation, it saves boot time */
619 	env_set("bootm-no-reloc", "y");
620 
621 	return 0;
622 }
623 
624 static ulong android_image_get_comp_addr(struct andr_img_hdr *hdr, int comp)
625 {
626 	ulong kernel_addr_c;
627 	ulong load_addr = 0;
628 
629 	kernel_addr_c = env_get_ulong("kernel_addr_c", 16, 0);
630 
631 #ifdef CONFIG_ARM64
632 	/*
633 	 * On 64-bit kernel, assuming use IMAGE by default.
634 	 *
635 	 * kernel_addr_c is for LZ4-IMAGE but maybe not defined.
636 	 * kernel_addr_r is for IMAGE.
637 	 */
638 	if (comp != IH_COMP_NONE) {
639 		ulong comp_addr;
640 
641 		if (kernel_addr_c) {
642 			comp_addr = kernel_addr_c;
643 		} else {
644 			printf("Warn: No \"kernel_addr_c\"\n");
645 			comp_addr = CONFIG_SYS_SDRAM_BASE + 0x2000000;/* 32M */
646 			env_set_hex("kernel_addr_c", comp_addr);
647 		}
648 
649 		load_addr = comp_addr - hdr->page_size;
650 	}
651 #else
652 	/*
653 	 * On 32-bit kernel:
654 	 *
655 	 * The input load_addr is from env value: "kernel_addr_r", it has
656 	 * different role depends on whether kernel_addr_c is defined:
657 	 *
658 	 * - kernel_addr_r is for lz4/zImage if kernel_addr_c if [not] defined.
659 	 * - kernel_addr_r is for IMAGE if kernel_addr_c is defined.
660 	 */
661 	if (comp == IH_COMP_NONE) {
662 		if (kernel_addr_c) {
663 			/* input load_addr is for Image, nothing to do */
664 		} else {
665 			/* input load_addr is for lz4/zImage, set default addr for Image */
666 			load_addr = CONFIG_SYS_SDRAM_BASE + 0x8000;
667 			env_set_hex("kernel_addr_r", load_addr);
668 
669 			load_addr -= hdr->page_size;
670 		}
671 	} else {
672 		if (kernel_addr_c) {
673 			/* input load_addr is for Image, so use another for lz4/zImage */
674 			load_addr = kernel_addr_c - hdr->page_size;
675 		} else {
676 			/* input load_addr is for lz4/zImage, nothing to do */
677 		}
678 	}
679 #endif
680 
681 	return load_addr;
682 }
683 
684 void android_image_set_decomp(struct andr_img_hdr *hdr, int comp)
685 {
686 	ulong kernel_addr_r;
687 
688 	env_set_ulong("os_comp", comp);
689 
690 	/* zImage handles decompress itself */
691 	if (comp != IH_COMP_NONE && comp != IH_COMP_ZIMAGE) {
692 		kernel_addr_r = env_get_ulong("kernel_addr_r", 16, 0x02080000);
693 		android_image_set_kload(hdr, kernel_addr_r);
694 		android_image_set_comp(hdr, comp);
695 	} else {
696 		android_image_set_comp(hdr, IH_COMP_NONE);
697 	}
698 }
699 
700 static int android_image_load_separate(struct andr_img_hdr *hdr,
701 				       const disk_partition_t *part,
702 				       void *load_addr)
703 {
704 	if (hdr->header_version < 3)
705 		return android_image_separate(hdr, part, load_addr, NULL);
706 	else
707 		return android_image_separate_v3(hdr, part, load_addr, NULL);
708 }
709 
710 int android_image_memcpy_separate(struct andr_img_hdr *hdr, ulong *load_addr)
711 {
712 	ulong comp_addr;
713 	int comp;
714 
715 	comp = bootm_parse_comp((void *)(ulong)hdr + hdr->page_size);
716 	comp_addr = android_image_get_comp_addr(hdr, comp);
717 
718 	/* non-compressed image: already in-place */
719 	if ((ulong)hdr == *load_addr)
720 		return 0;
721 
722 	/* compressed image */
723 	if (comp_addr) {
724 		*load_addr = comp_addr;
725 		if ((ulong)hdr == comp_addr)	/* already in-place */
726 			return 0;
727 	}
728 
729 	/*
730 	 * The most possible reason to arrive here is:
731 	 *
732 	 * VBoot=1 and AVB load full partition to a temp memory buffer, now we
733 	 * separate(memcpy) subimages from boot.img to where they should be.
734 	 */
735 	if (hdr->header_version < 3) {
736 		if (android_image_separate(hdr, NULL, (void *)(*load_addr), hdr))
737 			return -1;
738 	} else {
739 		if (android_image_separate_v3(hdr, NULL, (void *)(*load_addr), hdr))
740 			return -1;
741 	}
742 
743 	android_image_set_decomp((void *)(*load_addr), comp);
744 
745 	return 0;
746 }
747 
748 long android_image_load(struct blk_desc *dev_desc,
749 			const disk_partition_t *part_info,
750 			unsigned long load_address,
751 			unsigned long max_size) {
752 	struct andr_img_hdr *hdr;
753 	ulong comp_addr;
754 	int comp, ret;
755 	int blk_off;
756 
757 	if (max_size < part_info->blksz)
758 		return -1;
759 
760 	hdr = populate_andr_img_hdr(dev_desc, (disk_partition_t *)part_info);
761 	if (!hdr) {
762 		printf("No valid android hdr\n");
763 		return -1;
764 	}
765 
766 	/*
767 	 * create the layout:
768 	 *
769 	 * |<- page_size ->|1-blk |
770 	 * |-----|---------|------|-----|
771 	 * | hdr |   ...   |   kernel   |
772 	 * |-----|----- ---|------------|
773 	 *
774 	 * Alloc page_size and 1 more blk for reading kernel image to
775 	 * get it's compression type, then fill the android hdr what
776 	 * we have populated before.
777 	 *
778 	 * Why? see: android_image_get_kernel_addr().
779 	 */
780 	blk_off = BLK_CNT(hdr->page_size, dev_desc->blksz);
781 	hdr = (struct andr_img_hdr *)
782 			realloc(hdr, (blk_off + 1) * dev_desc->blksz);
783 	if (!hdr)
784 		return -1;
785 
786 	if (blk_dread(dev_desc, part_info->start + blk_off, 1,
787 		      (char *)hdr + hdr->page_size) != 1) {
788 		free(hdr);
789 		return -1;
790 	}
791 
792 	/* Changed to compressed address ? */
793 	comp = bootm_parse_comp((void *)(ulong)hdr + hdr->page_size);
794 	comp_addr = android_image_get_comp_addr(hdr, comp);
795 	if (comp_addr)
796 		load_address = comp_addr;
797 	else
798 		load_address -= hdr->page_size;
799 
800 	ret = android_image_load_separate(hdr, part_info, (void *)load_address);
801 	if (ret) {
802 		printf("Failed to load android image\n");
803 		goto fail;
804 	}
805 	android_image_set_decomp((void *)load_address, comp);
806 
807 	debug("Loading Android Image to 0x%08lx\n", load_address);
808 
809 	free(hdr);
810 	return load_address;
811 
812 fail:
813 	free(hdr);
814 	return -1;
815 }
816 
817 static struct andr_img_hdr *
818 extract_boot_image_v012_header(struct blk_desc *dev_desc,
819 			       const disk_partition_t *boot_img)
820 {
821 	struct andr_img_hdr *hdr;
822 	long blk_cnt, blks_read;
823 
824 	blk_cnt = BLK_CNT(sizeof(struct andr_img_hdr), dev_desc->blksz);
825 	hdr = (struct andr_img_hdr *)malloc(blk_cnt * dev_desc->blksz);
826 
827 	if (!blk_cnt || !hdr)
828 		return NULL;
829 
830 	blks_read = blk_dread(dev_desc, boot_img->start, blk_cnt, hdr);
831 	if (blks_read != blk_cnt) {
832 		debug("boot img header blk cnt is %ld and blks read is %ld\n",
833 		      blk_cnt, blks_read);
834 		return NULL;
835 	}
836 
837 	if (android_image_check_header((void *)hdr)) {
838 		printf("boot header magic is invalid.\n");
839 		return NULL;
840 	}
841 
842 	if (hdr->page_size < sizeof(*hdr)) {
843 		printf("android hdr is over size\n");
844 		return NULL;
845 	}
846 
847 	return hdr;
848 }
849 
850 static struct boot_img_hdr_v3 *
851 extract_boot_image_v3_header(struct blk_desc *dev_desc,
852 			     const disk_partition_t *boot_img)
853 {
854 	struct boot_img_hdr_v3 *boot_hdr;
855 	long blk_cnt, blks_read;
856 
857 	blk_cnt = BLK_CNT(sizeof(struct boot_img_hdr_v3), dev_desc->blksz);
858 	boot_hdr = (struct boot_img_hdr_v3 *)malloc(blk_cnt * dev_desc->blksz);
859 
860 	if (!blk_cnt || !boot_hdr)
861 		return NULL;
862 
863 	blks_read = blk_dread(dev_desc, boot_img->start, blk_cnt, boot_hdr);
864 	if (blks_read != blk_cnt) {
865 		debug("boot img header blk cnt is %ld and blks read is %ld\n",
866 		      blk_cnt, blks_read);
867 		return NULL;
868 	}
869 
870 	if (android_image_check_header((void *)boot_hdr)) {
871 		printf("boot header magic is invalid.\n");
872 		return NULL;
873 	}
874 
875 	if (boot_hdr->header_version != 3) {
876 		printf("boot header is not v3.\n");
877 		return NULL;
878 	}
879 
880 	return boot_hdr;
881 }
882 
883 static struct vendor_boot_img_hdr_v3 *
884 extract_vendor_boot_image_v3_header(struct blk_desc *dev_desc,
885 				    const disk_partition_t *part_vendor_boot)
886 {
887 	struct vendor_boot_img_hdr_v3 *vboot_hdr;
888 	long blk_cnt, blks_read;
889 
890 	blk_cnt = BLK_CNT(sizeof(struct vendor_boot_img_hdr_v3),
891 				part_vendor_boot->blksz);
892 	vboot_hdr = (struct vendor_boot_img_hdr_v3 *)
893 				malloc(blk_cnt * part_vendor_boot->blksz);
894 
895 	if (!blk_cnt || !vboot_hdr)
896 		return NULL;
897 
898 	blks_read = blk_dread(dev_desc, part_vendor_boot->start,
899 			      blk_cnt, vboot_hdr);
900 	if (blks_read != blk_cnt) {
901 		debug("vboot img header blk cnt is %ld and blks read is %ld\n",
902 		      blk_cnt, blks_read);
903 		return NULL;
904 	}
905 
906 	if (strncmp(VENDOR_BOOT_MAGIC, (void *)vboot_hdr->magic,
907 		    VENDOR_BOOT_MAGIC_SIZE)) {
908 		printf("vendor boot header is invalid.\n");
909 		return NULL;
910 	}
911 
912 	if (vboot_hdr->header_version != 3) {
913 		printf("vendor boot header is not v3.\n");
914 		return NULL;
915 	}
916 
917 	return vboot_hdr;
918 }
919 
920 static int populate_boot_info(const struct boot_img_hdr_v3 *boot_hdr,
921 			      const struct vendor_boot_img_hdr_v3 *vendor_hdr,
922 			      struct andr_img_hdr *hdr)
923 {
924 	memset(hdr->magic, 0, ANDR_BOOT_MAGIC_SIZE);
925 	memcpy(hdr->magic, boot_hdr->magic, ANDR_BOOT_MAGIC_SIZE);
926 
927 	hdr->kernel_size = boot_hdr->kernel_size;
928 	/* don't use vendor_hdr->kernel_addr, we prefer "hdr + hdr->page_size" */
929 	hdr->kernel_addr = ANDROID_IMAGE_DEFAULT_KERNEL_ADDR;
930 	/* generic ramdisk: immediately following the vendor ramdisk */
931 	hdr->boot_ramdisk_size = boot_hdr->ramdisk_size;
932 	hdr->ramdisk_size = boot_hdr->ramdisk_size +
933 				vendor_hdr->vendor_ramdisk_size;
934 	/* actually, useless */
935 	hdr->ramdisk_addr = vendor_hdr->ramdisk_addr +
936 				vendor_hdr->vendor_ramdisk_size;
937 	/* removed in v3 */
938 	hdr->second_size = 0;
939 	hdr->second_addr = 0;
940 
941 	hdr->tags_addr = vendor_hdr->tags_addr;
942 
943 	/* fixed in v3 */
944 	hdr->page_size = 4096;
945 	hdr->header_version = boot_hdr->header_version;
946 	hdr->os_version = boot_hdr->os_version;
947 
948 	memset(hdr->name, 0, ANDR_BOOT_NAME_SIZE);
949 	strncpy(hdr->name, (const char *)vendor_hdr->name, ANDR_BOOT_NAME_SIZE);
950 
951 	/* removed in v3 */
952 	memset(hdr->cmdline, 0, ANDR_BOOT_ARGS_SIZE);
953 	memset(hdr->id, 0, 32);
954 	memset(hdr->extra_cmdline, 0, ANDR_BOOT_EXTRA_ARGS_SIZE);
955 	hdr->recovery_dtbo_size = 0;
956 	hdr->recovery_dtbo_offset = 0;
957 
958 	hdr->header_size = boot_hdr->header_size;
959 	hdr->dtb_size = vendor_hdr->dtb_size;
960 	hdr->dtb_addr = vendor_hdr->dtb_addr;
961 
962 	/* boot_img_hdr_v3 fields */
963 	hdr->vendor_ramdisk_size = vendor_hdr->vendor_ramdisk_size;
964 	hdr->vendor_page_size = vendor_hdr->page_size;
965 	hdr->vendor_header_version = vendor_hdr->header_version;
966 	hdr->vendor_header_size = vendor_hdr->header_size;
967 
968 	hdr->total_cmdline = calloc(1, TOTAL_BOOT_ARGS_SIZE);
969 	if (!hdr->total_cmdline)
970 		return -ENOMEM;
971 	strncpy(hdr->total_cmdline, (const char *)boot_hdr->cmdline,
972 		sizeof(boot_hdr->cmdline));
973 	strncat(hdr->total_cmdline, " ", 1);
974 	strncat(hdr->total_cmdline, (const char *)vendor_hdr->cmdline,
975 		sizeof(vendor_hdr->cmdline));
976 
977 	if (hdr->page_size < sizeof(*hdr)) {
978 		printf("android hdr is over size\n");
979 		return -EINVAL;
980 	}
981 
982 	return 0;
983 }
984 
985 /*
986  * The possible cases of boot.img + recovery.img:
987  *
988  * [N]: 0, 1, 2
989  * [M]: 0, 1, 2, 3
990  *
991  * |--------------------|---------------------|
992  * |   boot.img         |    recovery.img     |
993  * |--------------------|---------------------|
994  * | boot_img_hdr_v[N]  |  boot_img_hdr_v[N]  | <= if A/B is not required
995  * |--------------------|---------------------|
996  * | boot_img_hdr_v3    |  boot_img_hdr_v2    | <= if A/B is not required
997  * |------------------------------------------|
998  * | boot_img_hdr_v[M], no recovery.img       | <= if A/B is required
999  * |------------------------------------------|
1000  */
1001 struct andr_img_hdr *populate_andr_img_hdr(struct blk_desc *dev_desc,
1002 					   disk_partition_t *part_boot)
1003 {
1004 	disk_partition_t part_vendor_boot;
1005 	struct vendor_boot_img_hdr_v3 *vboot_hdr;
1006 	struct boot_img_hdr_v3 *boot_hdr;
1007 	struct andr_img_hdr *andr_hdr;
1008 	int header_version;
1009 
1010 	if (!dev_desc || !part_boot)
1011 		return NULL;
1012 
1013 	andr_hdr = (struct andr_img_hdr *)malloc(1 * dev_desc->blksz);
1014 	if (!andr_hdr)
1015 		return NULL;
1016 
1017 	if (blk_dread(dev_desc, part_boot->start, 1, andr_hdr) != 1) {
1018 		free(andr_hdr);
1019 		return NULL;
1020 	}
1021 
1022 	if (android_image_check_header(andr_hdr)) {
1023 		free(andr_hdr);
1024 		return NULL;
1025 	}
1026 
1027 	header_version = andr_hdr->header_version;
1028 	free(andr_hdr);
1029 
1030 	if (header_version < 3) {
1031 		return extract_boot_image_v012_header(dev_desc, part_boot);
1032 	} else {
1033 		if (part_get_info_by_name(dev_desc,
1034 					  ANDROID_PARTITION_VENDOR_BOOT,
1035 					  &part_vendor_boot) < 0) {
1036 			printf("No vendor boot partition\n");
1037 			return NULL;
1038 		}
1039 		boot_hdr = extract_boot_image_v3_header(dev_desc, part_boot);
1040 		vboot_hdr = extract_vendor_boot_image_v3_header(dev_desc,
1041 							&part_vendor_boot);
1042 		if (!boot_hdr || !vboot_hdr)
1043 			goto image_load_exit;
1044 
1045 		andr_hdr = (struct andr_img_hdr *)
1046 				malloc(sizeof(struct andr_img_hdr));
1047 		if (!andr_hdr) {
1048 			printf("No memory for andr hdr\n");
1049 			goto image_load_exit;
1050 		}
1051 
1052 		if (populate_boot_info(boot_hdr, vboot_hdr, andr_hdr)) {
1053 			printf("populate boot info failed\n");
1054 			goto image_load_exit;
1055 		}
1056 
1057 		free(boot_hdr);
1058 		free(vboot_hdr);
1059 
1060 		return andr_hdr;
1061 
1062 image_load_exit:
1063 		free(boot_hdr);
1064 		free(vboot_hdr);
1065 
1066 		return NULL;
1067 	}
1068 
1069 	return NULL;
1070 }
1071 
1072 #if !defined(CONFIG_SPL_BUILD)
1073 /**
1074  * android_print_contents - prints out the contents of the Android format image
1075  * @hdr: pointer to the Android format image header
1076  *
1077  * android_print_contents() formats a multi line Android image contents
1078  * description.
1079  * The routine prints out Android image properties
1080  *
1081  * returns:
1082  *     no returned results
1083  */
1084 void android_print_contents(const struct andr_img_hdr *hdr)
1085 {
1086 	const char * const p = IMAGE_INDENT_STRING;
1087 	/* os_version = ver << 11 | lvl */
1088 	u32 os_ver = hdr->os_version >> 11;
1089 	u32 os_lvl = hdr->os_version & ((1U << 11) - 1);
1090 	u32 header_version = hdr->header_version;
1091 
1092 	printf("%skernel size:      %x\n", p, hdr->kernel_size);
1093 	printf("%skernel address:   %x\n", p, hdr->kernel_addr);
1094 	printf("%sramdisk size:     %x\n", p, hdr->ramdisk_size);
1095 	printf("%sramdisk address: %x\n", p, hdr->ramdisk_addr);
1096 	printf("%ssecond size:      %x\n", p, hdr->second_size);
1097 	printf("%ssecond address:   %x\n", p, hdr->second_addr);
1098 	printf("%stags address:     %x\n", p, hdr->tags_addr);
1099 	printf("%spage size:        %x\n", p, hdr->page_size);
1100 	printf("%sheader_version:   %x\n", p, header_version);
1101 	/* ver = A << 14 | B << 7 | C         (7 bits for each of A, B, C)
1102 	 * lvl = ((Y - 2000) & 127) << 4 | M  (7 bits for Y, 4 bits for M) */
1103 	printf("%sos_version:       %x (ver: %u.%u.%u, level: %u.%u)\n",
1104 	       p, hdr->os_version,
1105 	       (os_ver >> 7) & 0x7F, (os_ver >> 14) & 0x7F, os_ver & 0x7F,
1106 	       (os_lvl >> 4) + 2000, os_lvl & 0x0F);
1107 	printf("%sname:             %s\n", p, hdr->name);
1108 	printf("%scmdline:          %s\n", p, hdr->cmdline);
1109 
1110 	if (header_version == 1 || header_version == 2) {
1111 		printf("%srecovery dtbo size:    %x\n", p, hdr->recovery_dtbo_size);
1112 		printf("%srecovery dtbo offset:  %llx\n", p, hdr->recovery_dtbo_offset);
1113 		printf("%sheader size:           %x\n", p, hdr->header_size);
1114 	}
1115 
1116 	if (header_version == 2 || header_version == 3) {
1117 		printf("%sdtb size:              %x\n", p, hdr->dtb_size);
1118 		printf("%sdtb addr:              %llx\n", p, hdr->dtb_addr);
1119 	}
1120 
1121 	if (header_version == 3) {
1122 		printf("%scmdline:               %s\n", p, hdr->total_cmdline);
1123 		printf("%svendor ramdisk size:   %x\n", p, hdr->vendor_ramdisk_size);
1124 		printf("%svendor page size:      %x\n", p, hdr->vendor_page_size);
1125 		printf("%svendor header version: %d\n", p, hdr->vendor_header_version);
1126 		printf("%svendor header size:    %x\n", p, hdr->vendor_header_size);
1127 	}
1128 }
1129 #endif
1130