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