1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Generate Renesas RZ/N1 BootROM header (SPKG)
4  * (C) Copyright 2022 Schneider Electric
5  *
6  * Based on spkg_utility.c
7  * (C) Copyright 2016 Renesas Electronics Europe Ltd
8  */
9 
10 #include "imagetool.h"
11 #include <limits.h>
12 #include <image.h>
13 #include <stdarg.h>
14 #include <stdint.h>
15 #include <u-boot/crc.h>
16 #include "renesas_spkgimage.h"
17 
18 /* Note: the ordering of the bitfields does not matter */
19 struct config_file {
20 	unsigned int version:1;
21 	unsigned int ecc_block_size:2;
22 	unsigned int ecc_enable:1;
23 	unsigned int ecc_scheme:3;
24 	unsigned int ecc_bytes:8;
25 	unsigned int blp_len;
26 	unsigned int padding;
27 };
28 
29 static struct config_file conf;
30 
check_range(const char * name,int val,int min,int max)31 static int check_range(const char *name, int val, int min, int max)
32 {
33 	if (val < min) {
34 		fprintf(stderr, "Warning: param '%s' adjusted to min %d\n",
35 			name, min);
36 		val = min;
37 	}
38 
39 	if (val > max) {
40 		fprintf(stderr, "Warning: param '%s' adjusted to max %d\n",
41 			name, max);
42 		val = max;
43 	}
44 
45 	return val;
46 }
47 
spkgimage_parse_config_line(char * line,size_t line_num)48 static int spkgimage_parse_config_line(char *line, size_t line_num)
49 {
50 	char *saveptr;
51 	char *delim = "\t ";
52 	char *name = strtok_r(line, delim, &saveptr);
53 	char *val_str = strtok_r(NULL, delim, &saveptr);
54 	int value = atoi(val_str);
55 
56 	if (!strcmp("VERSION", name)) {
57 		conf.version = check_range(name, value, 1, 15);
58 	} else if (!strcmp("NAND_ECC_ENABLE", name)) {
59 		conf.ecc_enable = check_range(name, value, 0, 1);
60 	} else if (!strcmp("NAND_ECC_BLOCK_SIZE", name)) {
61 		conf.ecc_block_size = check_range(name, value, 0, 2);
62 	} else if (!strcmp("NAND_ECC_SCHEME", name)) {
63 		conf.ecc_scheme = check_range(name, value, 0, 7);
64 	} else if (!strcmp("NAND_BYTES_PER_ECC_BLOCK", name)) {
65 		conf.ecc_bytes = check_range(name, value, 0, 255);
66 	} else if (!strcmp("ADD_DUMMY_BLP", name)) {
67 		conf.blp_len = value ? SPKG_BLP_SIZE : 0;
68 	} else if (!strcmp("PADDING", name)) {
69 		if (strrchr(val_str, 'K'))
70 			value = value * 1024;
71 		else if (strrchr(val_str, 'M'))
72 			value = value * 1024 * 1024;
73 		conf.padding = check_range(name, value, 1, INT_MAX);
74 	} else {
75 		fprintf(stderr,
76 			"config error: unknown keyword on line %zu\n",
77 			line_num);
78 		return -EINVAL;
79 	}
80 
81 	return 0;
82 }
83 
spkgimage_parse_config_file(char * filename)84 static int spkgimage_parse_config_file(char *filename)
85 {
86 	FILE *fcfg;
87 	char line[256];
88 	size_t line_num = 0;
89 
90 	fcfg = fopen(filename, "r");
91 	if (!fcfg)
92 		return -EINVAL;
93 
94 	while (fgets(line, sizeof(line), fcfg)) {
95 		line_num += 1;
96 
97 		/* Skip blank lines and comments */
98 		if (line[0] == '\n' || line[0] == '#')
99 			continue;
100 
101 		/* Strip any trailing newline */
102 		line[strcspn(line, "\n")] = 0;
103 
104 		/* Parse the line */
105 		if (spkgimage_parse_config_line(line, line_num))
106 			return -EINVAL;
107 	}
108 
109 	fclose(fcfg);
110 
111 	/* Avoid divide-by-zero later on */
112 	if (!conf.padding)
113 		conf.padding = 1;
114 
115 	return 0;
116 }
117 
spkgimage_check_params(struct image_tool_params * params)118 static int spkgimage_check_params(struct image_tool_params *params)
119 {
120 	if (!params->addr) {
121 		fprintf(stderr, "Error: Load Address must be set.\n");
122 		return -EINVAL;
123 	}
124 
125 	if (!params->imagename || !params->imagename[0]) {
126 		fprintf(stderr, "Error: Image name must be set.\n");
127 		return -EINVAL;
128 	}
129 
130 	if (!params->datafile) {
131 		fprintf(stderr, "Error: Data filename must be set.\n");
132 		return -EINVAL;
133 	}
134 
135 	return 0;
136 }
137 
spkgimage_verify_header(unsigned char * ptr,int size,struct image_tool_params * param)138 static int spkgimage_verify_header(unsigned char *ptr, int size,
139 				   struct image_tool_params *param)
140 {
141 	struct spkg_file *file = (struct spkg_file *)ptr;
142 	struct spkg_hdr *header = (struct spkg_hdr *)ptr;
143 	char marker[4] = SPKG_HEADER_MARKER;
144 	uint32_t payload_length;
145 	uint32_t crc;
146 	uint8_t *crc_buf;
147 
148 	/* Check the marker bytes */
149 	if (memcmp(header->marker, marker, 4)) {
150 		fprintf(stderr, "Error: invalid marker bytes\n");
151 		return -EINVAL;
152 	}
153 
154 	/* Check the CRC */
155 	crc = crc32(0, ptr, SPKG_HEADER_SIZE - SPKG_CRC_SIZE);
156 	if (crc != header->crc) {
157 		fprintf(stderr, "Error: invalid header CRC=\n");
158 		return -EINVAL;
159 	}
160 
161 	/* Check all copies of header are the same */
162 	for (int i = 1; i < SPKG_HEADER_COUNT; i++) {
163 		if (memcmp(&header[0], &header[i], SPKG_HEADER_SIZE)) {
164 			fprintf(stderr, "Error: header %d mismatch\n", i);
165 			return -EINVAL;
166 		}
167 	}
168 
169 	/* Check the payload CRC */
170 	payload_length = le32_to_cpu(header->payload_length) >> 8;
171 	crc_buf = file->payload + payload_length - SPKG_CRC_SIZE;
172 	crc = crc32(0, file->payload, payload_length - SPKG_CRC_SIZE);
173 	if (crc_buf[0] != (crc & 0xff) ||
174 	    crc_buf[1] != (crc >> 8 & 0xff) ||
175 	    crc_buf[2] != (crc >> 16 & 0xff) ||
176 	    crc_buf[3] != (crc >> 24 & 0xff)) {
177 		fprintf(stderr, "Error: invalid payload CRC\n");
178 		return -EINVAL;
179 	}
180 
181 	return 0;
182 }
183 
spkgimage_print_header(const void * ptr,struct image_tool_params * image)184 static void spkgimage_print_header(const void *ptr,
185 				   struct image_tool_params *image)
186 {
187 	const struct spkg_hdr *h = ptr;
188 	uint32_t offset = le32_to_cpu(h->execution_offset);
189 
190 	printf("Image type\t: Renesas SPKG Image\n");
191 	printf("Marker\t\t: %c%c%c%c\n",
192 	       h->marker[0], h->marker[1], h->marker[2], h->marker[3]);
193 	printf("Version\t\t: %d\n", h->version);
194 	printf("ECC\t\t: ");
195 	if (h->ecc & 0x20)
196 		printf("Scheme %d, Block size %d, Strength %d\n",
197 		       h->ecc_scheme, (h->ecc >> 1) & 3, h->ecc_bytes);
198 	else
199 		printf("Not enabled\n");
200 	printf("Payload length\t: %d\n", le32_to_cpu(h->payload_length) >> 8);
201 	printf("Load address\t: 0x%08x\n", le32_to_cpu(h->load_address));
202 	printf("Execution offset: 0x%08x (%s mode)\n", offset & ~1,
203 	       offset & 1 ? "THUMB" : "ARM");
204 	printf("Header checksum\t: 0x%08x\n", le32_to_cpu(h->crc));
205 }
206 
207 /*
208  * This is the same as the macro version in include/kernel.h.
209  * However we cannot include that header, because for host tools,
210  * it ends up pulling in the host /usr/include/linux/kernel.h,
211  * which lacks the definition of roundup().
212  */
roundup(uint32_t x,uint32_t y)213 static inline uint32_t roundup(uint32_t x, uint32_t y)
214 {
215 	return ((x + y - 1) / y) * y;
216 }
217 
spkgimage_vrec_header(struct image_tool_params * params,struct image_type_params * tparams)218 static int spkgimage_vrec_header(struct image_tool_params *params,
219 				 struct image_type_params *tparams)
220 {
221 	struct stat s;
222 	struct spkg_file *out_buf;
223 
224 	/* Parse the config file */
225 	if (spkgimage_parse_config_file(params->imagename)) {
226 		fprintf(stderr, "Error parsing config file\n");
227 		exit(EXIT_FAILURE);
228 	}
229 
230 	/* Get size of input data file */
231 	if (stat(params->datafile, &s)) {
232 		fprintf(stderr, "Could not stat data file: %s: %s\n",
233 			params->datafile, strerror(errno));
234 		exit(EXIT_FAILURE);
235 	}
236 	params->orig_file_size = s.st_size;
237 
238 	/* Determine size of resulting SPKG file */
239 	uint32_t header_len = SPKG_HEADER_SIZE * SPKG_HEADER_COUNT;
240 	uint32_t payload_len = conf.blp_len + s.st_size + SPKG_CRC_SIZE;
241 	uint32_t total_len = header_len + payload_len;
242 
243 	/* Round up to next multiple of padding size */
244 	uint32_t padded_len = roundup(total_len, conf.padding);
245 
246 	/* Number of padding bytes to add */
247 	conf.padding = padded_len - total_len;
248 
249 	/* Fixup payload_len to include padding bytes */
250 	payload_len += conf.padding;
251 
252 	/* Prepare the header */
253 	struct spkg_hdr header = {
254 		.marker = SPKG_HEADER_MARKER,
255 		.version = conf.version,
256 		.ecc = (conf.ecc_enable << 5) | (conf.ecc_block_size << 1),
257 		.ecc_scheme = conf.ecc_scheme,
258 		.ecc_bytes = conf.ecc_bytes,
259 		.payload_length = cpu_to_le32(payload_len << 8),
260 		.load_address = cpu_to_le32(params->addr),
261 		.execution_offset = cpu_to_le32(params->ep - params->addr),
262 	};
263 	header.crc = crc32(0, (uint8_t *)&header,
264 			   sizeof(header) - SPKG_CRC_SIZE);
265 
266 	/* The SPKG contains 8 copies of the header */
267 	out_buf = malloc(sizeof(struct spkg_file));
268 	if (!out_buf) {
269 		fprintf(stderr, "Error: Data filename must be set.\n");
270 		return -ENOMEM;
271 	}
272 	tparams->hdr = out_buf;
273 	tparams->header_size = sizeof(struct spkg_file);
274 
275 	/* Fill the SPKG with the headers */
276 	for (int i = 0; i < SPKG_HEADER_COUNT; i++)
277 		memcpy(&out_buf->header[i], &header, sizeof(header));
278 
279 	/* Extra bytes to allocate in the output file */
280 	return conf.blp_len + conf.padding + 4;
281 }
282 
spkgimage_set_header(void * ptr,struct stat * sbuf,int ifd,struct image_tool_params * params)283 static void spkgimage_set_header(void *ptr, struct stat *sbuf, int ifd,
284 				 struct image_tool_params *params)
285 {
286 	uint8_t *payload = ptr + SPKG_HEADER_SIZE * SPKG_HEADER_COUNT;
287 	uint8_t *file_end = payload + conf.blp_len + params->orig_file_size;
288 	uint8_t *crc_buf = file_end + conf.padding;
289 	uint32_t crc;
290 
291 	/* Make room for the Dummy BLp header */
292 	memmove(payload + conf.blp_len, payload, params->orig_file_size);
293 
294 	/* Fill the SPKG with the Dummy BLp */
295 	memset(payload, 0x88, conf.blp_len);
296 
297 	/*
298 	 * mkimage copy_file() pads the input file with zeros.
299 	 * Replace those zeros with flash friendly one bits.
300 	 * The original version skipped the first 4 bytes,
301 	 * probably an oversight, but for consistency we
302 	 * keep the same behaviour.
303 	 */
304 	if (conf.padding >= 4)
305 		memset(file_end + 4, 0xff, conf.padding - 4);
306 
307 	/* Add Payload CRC */
308 	crc = crc32(0, payload, crc_buf - payload);
309 	crc_buf[0] = crc;
310 	crc_buf[1] = crc >> 8;
311 	crc_buf[2] = crc >> 16;
312 	crc_buf[3] = crc >> 24;
313 }
314 
spkgimage_check_image_types(uint8_t type)315 static int spkgimage_check_image_types(uint8_t type)
316 {
317 	return type == IH_TYPE_RENESAS_SPKG ? 0 : -EINVAL;
318 }
319 
320 /*
321  * spkgimage type parameter definition
322  */
323 U_BOOT_IMAGE_TYPE(
324 	spkgimage,
325 	"Renesas SPKG Image",
326 	0,
327 	NULL,
328 	spkgimage_check_params,
329 	spkgimage_verify_header,
330 	spkgimage_print_header,
331 	spkgimage_set_header,
332 	NULL,
333 	spkgimage_check_image_types,
334 	NULL,
335 	spkgimage_vrec_header
336 );
337