xref: /rk3399_rockchip-uboot/tools/rkcommon.c (revision 7a00f0a44b0ec80f61ab1cd47fc45a04869bbfa3)
1 /*
2  * (C) Copyright 2015 Google,  Inc
3  * Written by Simon Glass <sjg@chromium.org>
4  *
5  * (C) 2017 Theobroma Systems Design und Consulting GmbH
6  *
7  * SPDX-License-Identifier:	GPL-2.0+
8  *
9  * Helper functions for Rockchip images
10  */
11 
12 #include "imagetool.h"
13 #include <image.h>
14 #include <rc4.h>
15 #include "mkimage.h"
16 #include "rkcommon.h"
17 
18 enum {
19 	RK_MAGIC		= 0x0ff0aa55,
20 };
21 
22 enum {
23 	RK_HEADER_V1	= 1,
24 };
25 
26 /**
27  * struct header0_info - header block for boot ROM
28  *
29  * This is stored at SD card block 64 (where each block is 512 bytes, or at
30  * the start of SPI flash. It is encoded with RC4.
31  *
32  * @magic:		Magic (must be RK_MAGIC)
33  * @disable_rc4:	0 to use rc4 for boot image,  1 to use plain binary
34  * @init_offset:	Offset in blocks of the SPL code from this header
35  *			block. E.g. 4 means 2KB after the start of this header.
36  * Other fields are not used by U-Boot
37  */
38 struct header0_info {
39 	uint32_t magic;
40 	uint8_t reserved[4];
41 	uint32_t disable_rc4;
42 	uint16_t init_offset;
43 	uint8_t reserved1[492];
44 	uint16_t init_size;
45 	uint16_t init_boot_size;
46 	uint8_t reserved2[2];
47 };
48 
49 /**
50  * struct header1 info
51  */
52 struct header1_info {
53 	uint32_t magic;
54 };
55 
56 /**
57  * struct spl_info - spl info for each chip
58  *
59  * @imagename:		Image name(passed by "mkimage -n")
60  * @spl_hdr:		Boot ROM requires a 4-bytes spl header
61  * @spl_size:		Spl size(include extra 4-bytes spl header)
62  * @spl_rc4:		RC4 encode the SPL binary (same key as header)
63  * @header_ver:		header block version
64  */
65 struct spl_info {
66 	const char *imagename;
67 	const char *spl_hdr;
68 	const uint32_t spl_size;
69 	const bool spl_rc4;
70 	const uint32_t header_ver;
71 };
72 
73 static struct spl_info spl_infos[] = {
74 	{ "rk3036", "RK30", 0x1000, false, RK_HEADER_V1 },
75 	{ "rk3066", "RK30", 0x8000, true, RK_HEADER_V1 },
76 	{ "rk3128", "RK31", 0x1800, false, RK_HEADER_V1 },
77 	{ "rk3188", "RK31", 0x8000 - 0x800, true, RK_HEADER_V1 },
78 	{ "rk322x", "RK32", 0x8000 - 0x1000, false, RK_HEADER_V1 },
79 	{ "rk3288", "RK32", 0x8000, false, RK_HEADER_V1 },
80 	{ "rk3308", "RK33", 0x40000 - 0x1000, false, RK_HEADER_V1 },
81 	{ "rk3328", "RK32", 0x8000 - 0x800, false, RK_HEADER_V1 },
82 	{ "rk3368", "RK33", 0x8000 - 0x1000, false, RK_HEADER_V1 },
83 	{ "rk3399", "RK33", 0x30000 - 0x2000, false, RK_HEADER_V1 },
84 	{ "px30", "RK33", 0x2800, false, RK_HEADER_V1 },
85 	{ "rv1108", "RK11", 0x1800, false, RK_HEADER_V1 },
86 	{ "rv1126", "110B", 0x10000 - 0x1000, false, RK_HEADER_V1 },
87 	{ "rk1808", "RK18", 0x200000 - 0x2000, false, RK_HEADER_V1 },
88 };
89 
90 /**
91  * struct spl_params - spl params parsed in check_params()
92  *
93  * @init_file:		Init data file path
94  * @init_size:		Aligned size of init data in bytes
95  * @boot_file:		Boot data file path
96  * @boot_size:		Aligned size of boot data in bytes
97  */
98 
99 struct spl_params {
100 	char *init_file;
101 	uint32_t init_size;
102 	char *boot_file;
103 	uint32_t boot_size;
104 };
105 
106 static struct spl_params spl_params = { 0 };
107 
108 static unsigned char rc4_key[16] = {
109 	124, 78, 3, 4, 85, 5, 9, 7,
110 	45, 44, 123, 56, 23, 13, 23, 17
111 };
112 
113 static struct spl_info *rkcommon_get_spl_info(char *imagename)
114 {
115 	int i;
116 
117 	if (!imagename)
118 		return NULL;
119 
120 	for (i = 0; i < ARRAY_SIZE(spl_infos); i++)
121 		if (!strncmp(imagename, spl_infos[i].imagename, 6))
122 			return spl_infos + i;
123 
124 	return NULL;
125 }
126 
127 static int rkcommon_get_aligned_size(struct image_tool_params *params,
128 				     const char *fname)
129 {
130 	int size;
131 
132 	size = imagetool_get_filesize(params, fname);
133 	if (size < 0)
134 		return -1;
135 
136 	/*
137 	 * Pad to a 2KB alignment, as required for init/boot size by the ROM
138 	 * (see https://lists.denx.de/pipermail/u-boot/2017-May/293268.html)
139 	 */
140 	return ROUND(size, RK_SIZE_ALIGN);
141 }
142 
143 int rkcommon_check_params(struct image_tool_params *params)
144 {
145 	int i;
146 
147 	/*
148 	 * If this is a operation (list or extract), the don't require
149 	 * imagename to be set.
150 	 */
151 	if (params->lflag || params->iflag)
152 		return EXIT_SUCCESS;
153 
154 	if (!rkcommon_get_spl_info(params->imagename))
155 		goto err_spl_info;
156 
157 	spl_params.init_file = params->datafile;
158 
159 	spl_params.boot_file = strchr(spl_params.init_file, ':');
160 	if (spl_params.boot_file) {
161 		*spl_params.boot_file = '\0';
162 		spl_params.boot_file += 1;
163 	}
164 
165 	spl_params.init_size =
166 		rkcommon_get_aligned_size(params, spl_params.init_file);
167 	if (spl_params.init_size < 0)
168 		return EXIT_FAILURE;
169 
170 	/* Boot file is optional, and only for back-to-bootrom functionality. */
171 	if (spl_params.boot_file) {
172 		spl_params.boot_size =
173 			rkcommon_get_aligned_size(params, spl_params.boot_file);
174 		if (spl_params.boot_size < 0)
175 			return EXIT_FAILURE;
176 	}
177 
178 	if (spl_params.init_size > rkcommon_get_spl_size(params)) {
179 		fprintf(stderr,
180 			"Error: SPL image is too large (size %#x than %#x)\n",
181 			spl_params.init_size, rkcommon_get_spl_size(params));
182 		return EXIT_FAILURE;
183 	}
184 
185 	return EXIT_SUCCESS;
186 
187 err_spl_info:
188 	fprintf(stderr, "ERROR: imagename (%s) is not supported!\n",
189 		params->imagename ? params->imagename : "NULL");
190 
191 	fprintf(stderr, "Available imagename:");
192 	for (i = 0; i < ARRAY_SIZE(spl_infos); i++)
193 		fprintf(stderr, "\t%s", spl_infos[i].imagename);
194 	fprintf(stderr, "\n");
195 
196 	return EXIT_FAILURE;
197 }
198 
199 const char *rkcommon_get_spl_hdr(struct image_tool_params *params)
200 {
201 	struct spl_info *info = rkcommon_get_spl_info(params->imagename);
202 
203 	/*
204 	 * info would not be NULL, because of we checked params before.
205 	 */
206 	return info->spl_hdr;
207 }
208 
209 
210 int rkcommon_get_spl_size(struct image_tool_params *params)
211 {
212 	struct spl_info *info = rkcommon_get_spl_info(params->imagename);
213 
214 	/*
215 	 * info would not be NULL, because of we checked params before.
216 	 */
217 	return info->spl_size;
218 }
219 
220 bool rkcommon_need_rc4_spl(struct image_tool_params *params)
221 {
222 	struct spl_info *info = rkcommon_get_spl_info(params->imagename);
223 
224 	/*
225 	 * info would not be NULL, because of we checked params before.
226 	 */
227 	return info->spl_rc4;
228 }
229 
230 static void rkcommon_set_header0(void *buf, struct image_tool_params *params)
231 {
232 	struct header0_info *hdr = buf;
233 
234 	memset(buf, '\0', RK_INIT_OFFSET * RK_BLK_SIZE);
235 	hdr->magic = RK_MAGIC;
236 	hdr->disable_rc4 = !rkcommon_need_rc4_spl(params);
237 	hdr->init_offset = RK_INIT_OFFSET;
238 	hdr->init_size = spl_params.init_size / RK_BLK_SIZE;
239 
240 	/*
241 	 * init_boot_size needs to be set, as it is read by the BootROM
242 	 * to determine the size of the next-stage bootloader (e.g. U-Boot
243 	 * proper), when used with the back-to-bootrom functionality.
244 	 *
245 	 * see https://lists.denx.de/pipermail/u-boot/2017-May/293267.html
246 	 * for a more detailed explanation by Andy Yan
247 	 */
248 	if (spl_params.boot_file)
249 		hdr->init_boot_size =
250 			hdr->init_size + spl_params.boot_size / RK_BLK_SIZE;
251 	else
252 		hdr->init_boot_size =
253 			hdr->init_size + RK_MAX_BOOT_SIZE / RK_BLK_SIZE;
254 
255 	rc4_encode(buf, RK_BLK_SIZE, rc4_key);
256 }
257 
258 void rkcommon_set_header(void *buf,  struct stat *sbuf,  int ifd,
259 			 struct image_tool_params *params)
260 {
261 	struct header1_info *hdr = buf + RK_SPL_HDR_START;
262 
263 	rkcommon_set_header0(buf, params);
264 
265 	/* Set up the SPL name (i.e. copy spl_hdr over) */
266 	if (memcmp(&hdr->magic, "RSAK", 4))
267 		memcpy(&hdr->magic, rkcommon_get_spl_hdr(params), RK_SPL_HDR_SIZE);
268 
269 	if (rkcommon_need_rc4_spl(params))
270 		rkcommon_rc4_encode_spl(buf, RK_SPL_HDR_START,
271 					spl_params.init_size);
272 
273 	if (spl_params.boot_file) {
274 		if (rkcommon_need_rc4_spl(params))
275 			rkcommon_rc4_encode_spl(buf + RK_SPL_HDR_START,
276 						spl_params.init_size,
277 						spl_params.boot_size);
278 	}
279 }
280 
281 static inline unsigned rkcommon_offset_to_spi(unsigned offset)
282 {
283 	/*
284 	 * While SD/MMC images use a flat addressing, SPI images are padded
285 	 * to use the first 2K of every 4K sector only.
286 	 */
287 	return ((offset & ~0x7ff) << 1) + (offset & 0x7ff);
288 }
289 
290 static int rkcommon_parse_header(const void *buf, struct header0_info *header0,
291 				 struct spl_info **spl_info)
292 {
293 	unsigned hdr1_offset;
294 	struct header1_info *hdr1_sdmmc, *hdr1_spi;
295 	int i;
296 
297 	if (spl_info)
298 		*spl_info = NULL;
299 
300 	/*
301 	 * The first header (hdr0) is always RC4 encoded, so try to decrypt
302 	 * with the well-known key.
303 	 */
304 	memcpy((void *)header0, buf, sizeof(struct header0_info));
305 	rc4_encode((void *)header0, sizeof(struct header0_info), rc4_key);
306 
307 	if (header0->magic != RK_MAGIC)
308 		return -EPROTO;
309 
310 	/* We don't support RC4 encoded image payloads here, yet... */
311 	if (header0->disable_rc4 == 0)
312 		return -ENOSYS;
313 
314 	hdr1_offset = header0->init_offset * RK_BLK_SIZE;
315 	hdr1_sdmmc = (struct header1_info *)(buf + hdr1_offset);
316 	hdr1_spi = (struct header1_info *)(buf +
317 					   rkcommon_offset_to_spi(hdr1_offset));
318 
319 	for (i = 0; i < ARRAY_SIZE(spl_infos); i++) {
320 		if (!memcmp(&hdr1_sdmmc->magic, spl_infos[i].spl_hdr, 4)) {
321 			if (spl_info)
322 				*spl_info = &spl_infos[i];
323 			return IH_TYPE_RKSD;
324 		} else if (!memcmp(&hdr1_spi->magic, spl_infos[i].spl_hdr, 4)) {
325 			if (spl_info)
326 				*spl_info = &spl_infos[i];
327 			return IH_TYPE_RKSPI;
328 		}
329 	}
330 
331 	return -1;
332 }
333 
334 int rkcommon_verify_header(unsigned char *buf, int size,
335 			   struct image_tool_params *params)
336 {
337 	struct header0_info header0;
338 	struct spl_info *img_spl_info, *spl_info;
339 	int ret;
340 
341 	ret = rkcommon_parse_header(buf, &header0, &img_spl_info);
342 
343 	/* If this is the (unimplemented) RC4 case, then rewrite the result */
344 	if (ret == -ENOSYS)
345 		return 0;
346 
347 	if (ret < 0)
348 		return ret;
349 
350 	/*
351 	 * If no 'imagename' is specified via the commandline (e.g. if this is
352 	 * 'dumpimage -l' w/o any further constraints), we accept any spl_info.
353 	 */
354 	if (params->imagename == NULL)
355 		return 0;
356 
357 	/* Match the 'imagename' against the 'spl_hdr' found */
358 	spl_info = rkcommon_get_spl_info(params->imagename);
359 	if (spl_info && img_spl_info)
360 		return strcmp(spl_info->spl_hdr, img_spl_info->spl_hdr);
361 
362 	return -ENOENT;
363 }
364 
365 void rkcommon_print_header(const void *buf)
366 {
367 	struct header0_info header0;
368 	struct spl_info *spl_info;
369 	uint8_t image_type;
370 	int ret, boot_size;
371 
372 	ret = rkcommon_parse_header(buf, &header0, &spl_info);
373 
374 	/* If this is the (unimplemented) RC4 case, then fail silently */
375 	if (ret == -ENOSYS)
376 		return;
377 
378 	if (ret < 0) {
379 		fprintf(stderr, "Error: image verification failed\n");
380 		return;
381 	}
382 
383 	image_type = ret;
384 
385 	printf("Image Type:   Rockchip %s (%s) boot image\n",
386 	       spl_info->spl_hdr,
387 	       (image_type == IH_TYPE_RKSD) ? "SD/MMC" : "SPI");
388 	printf("Init Data Size: %d bytes\n", header0.init_size * RK_BLK_SIZE);
389 
390 	boot_size = (header0.init_boot_size - header0.init_size) * RK_BLK_SIZE;
391 	if (boot_size != RK_MAX_BOOT_SIZE)
392 		printf("Boot Data Size: %d bytes\n", boot_size);
393 }
394 
395 void rkcommon_rc4_encode_spl(void *buf, unsigned int offset, unsigned int size)
396 {
397 	unsigned int remaining = size;
398 
399 	while (remaining > 0) {
400 		int step = (remaining > RK_BLK_SIZE) ? RK_BLK_SIZE : remaining;
401 
402 		rc4_encode(buf + offset, step, rc4_key);
403 		offset += RK_BLK_SIZE;
404 		remaining -= step;
405 	}
406 }
407 
408 int rkcommon_vrec_header(struct image_tool_params *params,
409 			 struct image_type_params *tparams)
410 {
411 	/*
412 	 * The SPL image looks as follows:
413 	 *
414 	 * 0x0    header0 (see rkcommon.c)
415 	 * 0x800  spl_name ('RK30', ..., 'RK33')
416 	 *        (start of the payload for AArch64 payloads: we expect the
417 	 *        first 4 bytes to be available for overwriting with our
418 	 *        spl_name)
419 	 * 0x804  first instruction to be executed
420 	 *        (start of the image/payload for 32bit payloads)
421 	 *
422 	 * For AArch64 (ARMv8) payloads, natural alignment (8-bytes) is
423 	 * required for its sections (so the image we receive needs to
424 	 * have the first 4 bytes reserved for the spl_name).  Reserving
425 	 * these 4 bytes is done using the BOOT0_HOOK infrastructure.
426 	 *
427 	 * The header is always at 0x800 (as we now use a payload
428 	 * prepadded using the boot0 hook for all targets): the first
429 	 * 4 bytes of these images can safely be overwritten using the
430 	 * boot magic.
431 	 */
432 	tparams->header_size = RK_SPL_HDR_START;
433 
434 	/* Allocate, clear and install the header */
435 	tparams->hdr = malloc(tparams->header_size);
436 	if (!tparams->hdr) {
437 		fprintf(stderr, "%s: Can't alloc header: %s\n",
438 			params->cmdname, strerror(errno));
439 		exit(EXIT_FAILURE);
440 	}
441 	memset(tparams->hdr, 0, tparams->header_size);
442 
443 	/*
444 	 * We need to store the original file-size (i.e. before padding), as
445 	 * imagetool does not set this during its adjustment of file_size.
446 	 */
447 	params->orig_file_size = tparams->header_size +
448 		spl_params.init_size + spl_params.boot_size;
449 
450 	params->file_size = ROUND(params->orig_file_size, RK_SIZE_ALIGN);
451 
452 	/* Ignoring pad len, since we are using our own copy_image() */
453 	return 0;
454 }
455 
456 static int pad_file(struct image_tool_params *params, int ifd, int pad)
457 {
458 	uint8_t zeros[4096];
459 
460 	memset(zeros, 0, sizeof(zeros));
461 
462 	while (pad > 0) {
463 		int todo = sizeof(zeros);
464 
465 		if (todo > pad)
466 			todo = pad;
467 		if (write(ifd, (char *)&zeros, todo) != todo) {
468 			fprintf(stderr, "%s: Write error on %s: %s\n",
469 				params->cmdname, params->imagefile,
470 				strerror(errno));
471 			return -1;
472 		}
473 		pad -= todo;
474 	}
475 
476 	return 0;
477 }
478 
479 static int copy_file(struct image_tool_params *params, int ifd,
480 		     const char *file, int padded_size)
481 {
482 	int dfd;
483 	struct stat sbuf;
484 	unsigned char *ptr;
485 	int size;
486 
487 	if (params->vflag)
488 		fprintf(stderr, "Adding Image %s\n", file);
489 
490 	dfd = open(file, O_RDONLY | O_BINARY);
491 	if (dfd < 0) {
492 		fprintf(stderr, "%s: Can't open %s: %s\n",
493 			params->cmdname, file, strerror(errno));
494 		return -1;
495 	}
496 
497 	if (fstat(dfd, &sbuf) < 0) {
498 		fprintf(stderr, "%s: Can't stat %s: %s\n",
499 			params->cmdname, file, strerror(errno));
500 		goto err_close;
501 	}
502 
503 	if (params->vflag)
504 		fprintf(stderr, "Size %u(pad to %u)\n",
505 			(int)sbuf.st_size, padded_size);
506 
507 	ptr = mmap(0, sbuf.st_size, PROT_READ, MAP_SHARED, dfd, 0);
508 	if (ptr == MAP_FAILED) {
509 		fprintf(stderr, "%s: Can't read %s: %s\n",
510 			params->cmdname, file, strerror(errno));
511 		goto err_munmap;
512 	}
513 
514 	size = sbuf.st_size;
515 	if (write(ifd, ptr, size) != size) {
516 		fprintf(stderr, "%s: Write error on %s: %s\n",
517 			params->cmdname, params->imagefile, strerror(errno));
518 		goto err_munmap;
519 	}
520 
521 	munmap((void *)ptr, sbuf.st_size);
522 	close(dfd);
523 	return pad_file(params, ifd, padded_size - size);
524 
525 err_munmap:
526 	munmap((void *)ptr, sbuf.st_size);
527 err_close:
528 	close(dfd);
529 	return -1;
530 }
531 
532 int rockchip_copy_image(int ifd, struct image_tool_params *params)
533 {
534 	int ret;
535 
536 	ret = copy_file(params, ifd, spl_params.init_file,
537 			spl_params.init_size);
538 	if (ret)
539 		return ret;
540 
541 	if (spl_params.boot_file) {
542 		ret = copy_file(params, ifd, spl_params.boot_file,
543 				spl_params.boot_size);
544 		if (ret)
545 			return ret;
546 	}
547 
548 	return pad_file(params, ifd,
549 			params->file_size - params->orig_file_size);
550 }
551