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 		if (param->type == IH_TYPE_RENESAS_SPKG)
151 			fprintf(stderr, "Error: invalid marker bytes\n");
152 		return -EINVAL;
153 	}
154 
155 	/* Check the CRC */
156 	crc = crc32(0, ptr, SPKG_HEADER_SIZE - SPKG_CRC_SIZE);
157 	if (crc != header->crc) {
158 		fprintf(stderr, "Error: invalid header CRC=\n");
159 		return -EINVAL;
160 	}
161 
162 	/* Check all copies of header are the same */
163 	for (int i = 1; i < SPKG_HEADER_COUNT; i++) {
164 		if (memcmp(&header[0], &header[i], SPKG_HEADER_SIZE)) {
165 			fprintf(stderr, "Error: header %d mismatch\n", i);
166 			return -EINVAL;
167 		}
168 	}
169 
170 	/* Check the payload CRC */
171 	payload_length = le32_to_cpu(header->payload_length) >> 8;
172 	crc_buf = file->payload + payload_length - SPKG_CRC_SIZE;
173 	crc = crc32(0, file->payload, payload_length - SPKG_CRC_SIZE);
174 	if (crc_buf[0] != (crc & 0xff) ||
175 	    crc_buf[1] != (crc >> 8 & 0xff) ||
176 	    crc_buf[2] != (crc >> 16 & 0xff) ||
177 	    crc_buf[3] != (crc >> 24 & 0xff)) {
178 		fprintf(stderr, "Error: invalid payload CRC\n");
179 		return -EINVAL;
180 	}
181 
182 	return 0;
183 }
184 
spkgimage_print_header(const void * ptr,struct image_tool_params * image)185 static void spkgimage_print_header(const void *ptr,
186 				   struct image_tool_params *image)
187 {
188 	const struct spkg_hdr *h = ptr;
189 	uint32_t offset = le32_to_cpu(h->execution_offset);
190 
191 	printf("Image type\t: Renesas SPKG Image\n");
192 	printf("Marker\t\t: %c%c%c%c\n",
193 	       h->marker[0], h->marker[1], h->marker[2], h->marker[3]);
194 	printf("Version\t\t: %d\n", h->version);
195 	printf("ECC\t\t: ");
196 	if (h->ecc & 0x20)
197 		printf("Scheme %d, Block size %d, Strength %d\n",
198 		       h->ecc_scheme, (h->ecc >> 1) & 3, h->ecc_bytes);
199 	else
200 		printf("Not enabled\n");
201 	printf("Payload length\t: %d\n", le32_to_cpu(h->payload_length) >> 8);
202 	printf("Load address\t: 0x%08x\n", le32_to_cpu(h->load_address));
203 	printf("Execution offset: 0x%08x (%s mode)\n", offset & ~1,
204 	       offset & 1 ? "THUMB" : "ARM");
205 	printf("Header checksum\t: 0x%08x\n", le32_to_cpu(h->crc));
206 }
207 
208 /*
209  * This is the same as the macro version in include/kernel.h.
210  * However we cannot include that header, because for host tools,
211  * it ends up pulling in the host /usr/include/linux/kernel.h,
212  * which lacks the definition of roundup().
213  */
roundup(uint32_t x,uint32_t y)214 static inline uint32_t roundup(uint32_t x, uint32_t y)
215 {
216 	return ((x + y - 1) / y) * y;
217 }
218 
spkgimage_vrec_header(struct image_tool_params * params,struct image_type_params * tparams)219 static int spkgimage_vrec_header(struct image_tool_params *params,
220 				 struct image_type_params *tparams)
221 {
222 	struct stat s;
223 	struct spkg_file *out_buf;
224 
225 	/* Parse the config file */
226 	if (spkgimage_parse_config_file(params->imagename)) {
227 		fprintf(stderr, "Error parsing config file\n");
228 		exit(EXIT_FAILURE);
229 	}
230 
231 	/* Get size of input data file */
232 	if (stat(params->datafile, &s)) {
233 		fprintf(stderr, "Could not stat data file: %s: %s\n",
234 			params->datafile, strerror(errno));
235 		exit(EXIT_FAILURE);
236 	}
237 	params->orig_file_size = s.st_size;
238 
239 	/* Determine size of resulting SPKG file */
240 	uint32_t header_len = SPKG_HEADER_SIZE * SPKG_HEADER_COUNT;
241 	uint32_t payload_len = conf.blp_len + s.st_size + SPKG_CRC_SIZE;
242 	uint32_t total_len = header_len + payload_len;
243 
244 	/* Round up to next multiple of padding size */
245 	uint32_t padded_len = roundup(total_len, conf.padding);
246 
247 	/* Number of padding bytes to add */
248 	conf.padding = padded_len - total_len;
249 
250 	/* Fixup payload_len to include padding bytes */
251 	payload_len += conf.padding;
252 
253 	/* Prepare the header */
254 	struct spkg_hdr header = {
255 		.marker = SPKG_HEADER_MARKER,
256 		.version = conf.version,
257 		.ecc = (conf.ecc_enable << 5) | (conf.ecc_block_size << 1),
258 		.ecc_scheme = conf.ecc_scheme,
259 		.ecc_bytes = conf.ecc_bytes,
260 		.payload_length = cpu_to_le32(payload_len << 8),
261 		.load_address = cpu_to_le32(params->addr),
262 		.execution_offset = cpu_to_le32(params->ep - params->addr),
263 	};
264 	header.crc = crc32(0, (uint8_t *)&header,
265 			   sizeof(header) - SPKG_CRC_SIZE);
266 
267 	/* The SPKG contains 8 copies of the header */
268 	out_buf = malloc(sizeof(struct spkg_file));
269 	if (!out_buf) {
270 		fprintf(stderr, "Error: Data filename must be set.\n");
271 		return -ENOMEM;
272 	}
273 	tparams->hdr = out_buf;
274 	tparams->header_size = sizeof(struct spkg_file);
275 
276 	/* Fill the SPKG with the headers */
277 	for (int i = 0; i < SPKG_HEADER_COUNT; i++)
278 		memcpy(&out_buf->header[i], &header, sizeof(header));
279 
280 	/* Extra bytes to allocate in the output file */
281 	return conf.blp_len + conf.padding + 4;
282 }
283 
spkgimage_set_header(void * ptr,struct stat * sbuf,int ifd,struct image_tool_params * params)284 static void spkgimage_set_header(void *ptr, struct stat *sbuf, int ifd,
285 				 struct image_tool_params *params)
286 {
287 	uint8_t *payload = ptr + SPKG_HEADER_SIZE * SPKG_HEADER_COUNT;
288 	uint8_t *file_end = payload + conf.blp_len + params->orig_file_size;
289 	uint8_t *crc_buf = file_end + conf.padding;
290 	uint32_t crc;
291 
292 	/* Make room for the Dummy BLp header */
293 	memmove(payload + conf.blp_len, payload, params->orig_file_size);
294 
295 	/* Fill the SPKG with the Dummy BLp */
296 	memset(payload, 0x88, conf.blp_len);
297 
298 	/*
299 	 * mkimage copy_file() pads the input file with zeros.
300 	 * Replace those zeros with flash friendly one bits.
301 	 * The original version skipped the first 4 bytes,
302 	 * probably an oversight, but for consistency we
303 	 * keep the same behaviour.
304 	 */
305 	if (conf.padding >= 4)
306 		memset(file_end + 4, 0xff, conf.padding - 4);
307 
308 	/* Add Payload CRC */
309 	crc = crc32(0, payload, crc_buf - payload);
310 	crc_buf[0] = crc;
311 	crc_buf[1] = crc >> 8;
312 	crc_buf[2] = crc >> 16;
313 	crc_buf[3] = crc >> 24;
314 }
315 
spkgimage_check_image_types(uint8_t type)316 static int spkgimage_check_image_types(uint8_t type)
317 {
318 	return type == IH_TYPE_RENESAS_SPKG ? 0 : -EINVAL;
319 }
320 
321 /*
322  * spkgimage type parameter definition
323  */
324 U_BOOT_IMAGE_TYPE(
325 	spkgimage,
326 	"Renesas SPKG Image",
327 	0,
328 	NULL,
329 	spkgimage_check_params,
330 	spkgimage_verify_header,
331 	spkgimage_print_header,
332 	spkgimage_set_header,
333 	NULL,
334 	spkgimage_check_image_types,
335 	NULL,
336 	spkgimage_vrec_header
337 );
338