Blame view

tools/kwbimage.c 38.2 KB
83d290c56   Tom Rini   SPDX: Convert all...
1
  // SPDX-License-Identifier: GPL-2.0+
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
2
  /*
4acd2d24b   Stefan Roese   tools: kwbimage: ...
3
   * Image manipulator for Marvell SoCs
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
4
   *  supports Kirkwood, Dove, Armada 370, Armada XP, and Armada 38x
4acd2d24b   Stefan Roese   tools: kwbimage: ...
5
6
7
   *
   * (C) Copyright 2013 Thomas Petazzoni
   * <thomas.petazzoni@free-electrons.com>
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
8
   *
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
9
   * Not implemented: support for the register headers in v1 images
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
10
   */
f86ed6a8d   Guilherme Maciel Ferreira   tools: moved code...
11
  #include "imagetool.h"
e5f1a586a   Andreas Bießmann   tools/kwbimage.c:...
12
  #include <limits.h>
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
13
  #include <image.h>
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
14
  #include <stdarg.h>
4acd2d24b   Stefan Roese   tools: kwbimage: ...
15
  #include <stdint.h>
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
16
  #include "kwbimage.h"
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
17
  #ifdef CONFIG_KWB_SECURE
e15843b11   Jelle van der Waa   tools: kwbimage f...
18
  #include <openssl/bn.h>
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
19
20
21
22
  #include <openssl/rsa.h>
  #include <openssl/pem.h>
  #include <openssl/err.h>
  #include <openssl/evp.h>
e15843b11   Jelle van der Waa   tools: kwbimage f...
23

a2d5efd74   Jonathan Gray   tools/kwbimage: f...
24
25
  #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
      (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL)
e15843b11   Jelle van der Waa   tools: kwbimage f...
26
27
28
29
30
31
32
33
34
35
  static void RSA_get0_key(const RSA *r,
                   const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
  {
     if (n != NULL)
         *n = r->n;
     if (e != NULL)
         *e = r->e;
     if (d != NULL)
         *d = r->d;
  }
a2d5efd74   Jonathan Gray   tools/kwbimage: f...
36
  #elif !defined(LIBRESSL_VERSION_NUMBER)
e15843b11   Jelle van der Waa   tools: kwbimage f...
37
38
39
40
41
  void EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx)
  {
  	EVP_MD_CTX_reset(ctx);
  }
  #endif
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
42
  #endif
4acd2d24b   Stefan Roese   tools: kwbimage: ...
43
44
  static struct image_cfg_element *image_cfg;
  static int cfgn;
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
45
46
47
  #ifdef CONFIG_KWB_SECURE
  static int verbose_mode;
  #endif
4acd2d24b   Stefan Roese   tools: kwbimage: ...
48
49
50
51
52
  
  struct boot_mode {
  	unsigned int id;
  	const char *name;
  };
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
53
54
55
56
57
58
  /*
   * SHA2-256 hash
   */
  struct hash_v1 {
  	uint8_t hash[32];
  };
4acd2d24b   Stefan Roese   tools: kwbimage: ...
59
60
61
62
63
64
65
  struct boot_mode boot_modes[] = {
  	{ 0x4D, "i2c"  },
  	{ 0x5A, "spi"  },
  	{ 0x8B, "nand" },
  	{ 0x78, "sata" },
  	{ 0x9C, "pex"  },
  	{ 0x69, "uart" },
1bbe63c3f   Stefan Roese   kwbimage: Add sup...
66
  	{ 0xAE, "sdio" },
4acd2d24b   Stefan Roese   tools: kwbimage: ...
67
  	{},
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
68
  };
4acd2d24b   Stefan Roese   tools: kwbimage: ...
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
  struct nand_ecc_mode {
  	unsigned int id;
  	const char *name;
  };
  
  struct nand_ecc_mode nand_ecc_modes[] = {
  	{ 0x00, "default" },
  	{ 0x01, "hamming" },
  	{ 0x02, "rs" },
  	{ 0x03, "disabled" },
  	{},
  };
  
  /* Used to identify an undefined execution or destination address */
  #define ADDR_INVALID ((uint32_t)-1)
  
  #define BINARY_MAX_ARGS 8
  
  /* In-memory representation of a line of the configuration file */
4991b4f7f   Mario Six   tools: kwbimage: ...
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
  
  enum image_cfg_type {
  	IMAGE_CFG_VERSION = 0x1,
  	IMAGE_CFG_BOOT_FROM,
  	IMAGE_CFG_DEST_ADDR,
  	IMAGE_CFG_EXEC_ADDR,
  	IMAGE_CFG_NAND_BLKSZ,
  	IMAGE_CFG_NAND_BADBLK_LOCATION,
  	IMAGE_CFG_NAND_ECC_MODE,
  	IMAGE_CFG_NAND_PAGESZ,
  	IMAGE_CFG_BINARY,
  	IMAGE_CFG_PAYLOAD,
  	IMAGE_CFG_DATA,
  	IMAGE_CFG_BAUDRATE,
  	IMAGE_CFG_DEBUG,
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
103
104
105
106
107
108
109
110
111
112
  	IMAGE_CFG_KAK,
  	IMAGE_CFG_CSK,
  	IMAGE_CFG_CSK_INDEX,
  	IMAGE_CFG_JTAG_DELAY,
  	IMAGE_CFG_BOX_ID,
  	IMAGE_CFG_FLASH_ID,
  	IMAGE_CFG_SEC_COMMON_IMG,
  	IMAGE_CFG_SEC_SPECIALIZED_IMG,
  	IMAGE_CFG_SEC_BOOT_DEV,
  	IMAGE_CFG_SEC_FUSE_DUMP,
4991b4f7f   Mario Six   tools: kwbimage: ...
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
  
  	IMAGE_CFG_COUNT
  } type;
  
  static const char * const id_strs[] = {
  	[IMAGE_CFG_VERSION] = "VERSION",
  	[IMAGE_CFG_BOOT_FROM] = "BOOT_FROM",
  	[IMAGE_CFG_DEST_ADDR] = "DEST_ADDR",
  	[IMAGE_CFG_EXEC_ADDR] = "EXEC_ADDR",
  	[IMAGE_CFG_NAND_BLKSZ] = "NAND_BLKSZ",
  	[IMAGE_CFG_NAND_BADBLK_LOCATION] = "NAND_BADBLK_LOCATION",
  	[IMAGE_CFG_NAND_ECC_MODE] = "NAND_ECC_MODE",
  	[IMAGE_CFG_NAND_PAGESZ] = "NAND_PAGE_SIZE",
  	[IMAGE_CFG_BINARY] = "BINARY",
  	[IMAGE_CFG_PAYLOAD] = "PAYLOAD",
  	[IMAGE_CFG_DATA] = "DATA",
  	[IMAGE_CFG_BAUDRATE] = "BAUDRATE",
  	[IMAGE_CFG_DEBUG] = "DEBUG",
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
131
132
133
134
135
136
137
138
139
140
  	[IMAGE_CFG_KAK] = "KAK",
  	[IMAGE_CFG_CSK] = "CSK",
  	[IMAGE_CFG_CSK_INDEX] = "CSK_INDEX",
  	[IMAGE_CFG_JTAG_DELAY] = "JTAG_DELAY",
  	[IMAGE_CFG_BOX_ID] = "BOX_ID",
  	[IMAGE_CFG_FLASH_ID] = "FLASH_ID",
  	[IMAGE_CFG_SEC_COMMON_IMG] = "SEC_COMMON_IMG",
  	[IMAGE_CFG_SEC_SPECIALIZED_IMG] = "SEC_SPECIALIZED_IMG",
  	[IMAGE_CFG_SEC_BOOT_DEV] = "SEC_BOOT_DEV",
  	[IMAGE_CFG_SEC_FUSE_DUMP] = "SEC_FUSE_DUMP"
4991b4f7f   Mario Six   tools: kwbimage: ...
141
  };
4acd2d24b   Stefan Roese   tools: kwbimage: ...
142
  struct image_cfg_element {
4991b4f7f   Mario Six   tools: kwbimage: ...
143
  	enum image_cfg_type type;
4acd2d24b   Stefan Roese   tools: kwbimage: ...
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
  	union {
  		unsigned int version;
  		unsigned int bootfrom;
  		struct {
  			const char *file;
  			unsigned int args[BINARY_MAX_ARGS];
  			unsigned int nargs;
  		} binary;
  		const char *payload;
  		unsigned int dstaddr;
  		unsigned int execaddr;
  		unsigned int nandblksz;
  		unsigned int nandbadblklocation;
  		unsigned int nandeccmode;
  		unsigned int nandpagesz;
  		struct ext_hdr_v0_reg regdata;
4bdb54797   Chris Packham   tools/kwbimage: a...
160
  		unsigned int baudrate;
2611c05e8   Chris Packham   tools/kwbimage: a...
161
  		unsigned int debug;
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
162
163
164
165
166
167
168
169
  		const char *key_name;
  		int csk_idx;
  		uint8_t jtag_delay;
  		uint32_t boxid;
  		uint32_t flashid;
  		bool sec_specialized_img;
  		unsigned int sec_boot_dev;
  		const char *name;
4acd2d24b   Stefan Roese   tools: kwbimage: ...
170
171
172
173
  	};
  };
  
  #define IMAGE_CFG_ELEMENT_MAX 256
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
174
175
  
  /*
4acd2d24b   Stefan Roese   tools: kwbimage: ...
176
177
178
179
180
181
182
183
   * Utility functions to manipulate boot mode and ecc modes (convert
   * them back and forth between description strings and the
   * corresponding numerical identifiers).
   */
  
  static const char *image_boot_mode_name(unsigned int id)
  {
  	int i;
94490a4a7   Mario Six   tools: kwbimage: ...
184

4acd2d24b   Stefan Roese   tools: kwbimage: ...
185
186
187
188
189
190
191
192
193
  	for (i = 0; boot_modes[i].name; i++)
  		if (boot_modes[i].id == id)
  			return boot_modes[i].name;
  	return NULL;
  }
  
  int image_boot_mode_id(const char *boot_mode_name)
  {
  	int i;
94490a4a7   Mario Six   tools: kwbimage: ...
194

4acd2d24b   Stefan Roese   tools: kwbimage: ...
195
196
197
198
199
200
201
202
203
204
  	for (i = 0; boot_modes[i].name; i++)
  		if (!strcmp(boot_modes[i].name, boot_mode_name))
  			return boot_modes[i].id;
  
  	return -1;
  }
  
  int image_nand_ecc_mode_id(const char *nand_ecc_mode_name)
  {
  	int i;
94490a4a7   Mario Six   tools: kwbimage: ...
205

4acd2d24b   Stefan Roese   tools: kwbimage: ...
206
207
208
209
  	for (i = 0; nand_ecc_modes[i].name; i++)
  		if (!strcmp(nand_ecc_modes[i].name, nand_ecc_mode_name))
  			return nand_ecc_modes[i].id;
  	return -1;
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
210
  }
4acd2d24b   Stefan Roese   tools: kwbimage: ...
211
212
  static struct image_cfg_element *
  image_find_option(unsigned int optiontype)
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
213
  {
4acd2d24b   Stefan Roese   tools: kwbimage: ...
214
  	int i;
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
215

4acd2d24b   Stefan Roese   tools: kwbimage: ...
216
217
218
  	for (i = 0; i < cfgn; i++) {
  		if (image_cfg[i].type == optiontype)
  			return &image_cfg[i];
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
219
  	}
4acd2d24b   Stefan Roese   tools: kwbimage: ...
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
  
  	return NULL;
  }
  
  static unsigned int
  image_count_options(unsigned int optiontype)
  {
  	int i;
  	unsigned int count = 0;
  
  	for (i = 0; i < cfgn; i++)
  		if (image_cfg[i].type == optiontype)
  			count++;
  
  	return count;
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
235
  }
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
  #if defined(CONFIG_KWB_SECURE)
  
  static int image_get_csk_index(void)
  {
  	struct image_cfg_element *e;
  
  	e = image_find_option(IMAGE_CFG_CSK_INDEX);
  	if (!e)
  		return -1;
  
  	return e->csk_idx;
  }
  
  static bool image_get_spezialized_img(void)
  {
  	struct image_cfg_element *e;
  
  	e = image_find_option(IMAGE_CFG_SEC_SPECIALIZED_IMG);
  	if (!e)
  		return false;
  
  	return e->sec_specialized_img;
  }
  
  #endif
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
261
  /*
4acd2d24b   Stefan Roese   tools: kwbimage: ...
262
263
   * Compute a 8-bit checksum of a memory area. This algorithm follows
   * the requirements of the Marvell SoC BootROM specifications.
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
264
   */
4acd2d24b   Stefan Roese   tools: kwbimage: ...
265
  static uint8_t image_checksum8(void *start, uint32_t len)
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
266
  {
4acd2d24b   Stefan Roese   tools: kwbimage: ...
267
268
  	uint8_t csum = 0;
  	uint8_t *p = start;
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
269
270
271
272
273
274
  
  	/* check len and return zero checksum if invalid */
  	if (!len)
  		return 0;
  
  	do {
4acd2d24b   Stefan Roese   tools: kwbimage: ...
275
  		csum += *p;
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
276
277
  		p++;
  	} while (--len);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
278
279
  
  	return csum;
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
280
  }
db7cd4ed3   Baruch Siach   tools/kwbimage: f...
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
  size_t kwbimage_header_size(unsigned char *ptr)
  {
  	if (image_version((void *)ptr) == 0)
  		return sizeof(struct main_hdr_v0);
  	else
  		return KWBHEADER_V1_SIZE((struct main_hdr_v1 *)ptr);
  }
  
  /*
   * Verify checksum over a complete header that includes the checksum field.
   * Return 1 when OK, otherwise 0.
   */
  static int main_hdr_checksum_ok(void *hdr)
  {
  	/* Offsets of checksum in v0 and v1 headers are the same */
  	struct main_hdr_v0 *main_hdr = (struct main_hdr_v0 *)hdr;
  	uint8_t checksum;
  
  	checksum = image_checksum8(hdr, kwbimage_header_size(hdr));
  	/* Calculated checksum includes the header checksum field. Compensate
  	 * for that.
  	 */
  	checksum -= main_hdr->checksum;
  
  	return checksum == main_hdr->checksum;
  }
4acd2d24b   Stefan Roese   tools: kwbimage: ...
307
  static uint32_t image_checksum32(void *start, uint32_t len)
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
308
  {
4acd2d24b   Stefan Roese   tools: kwbimage: ...
309
310
  	uint32_t csum = 0;
  	uint32_t *p = start;
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
311
312
313
314
315
316
  
  	/* check len and return zero checksum if invalid */
  	if (!len)
  		return 0;
  
  	if (len % sizeof(uint32_t)) {
4acd2d24b   Stefan Roese   tools: kwbimage: ...
317
318
319
  		fprintf(stderr, "Length %d is not in multiple of %zu
  ",
  			len, sizeof(uint32_t));
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
320
321
322
323
  		return 0;
  	}
  
  	do {
4acd2d24b   Stefan Roese   tools: kwbimage: ...
324
  		csum += *p;
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
325
326
327
  		p++;
  		len -= sizeof(uint32_t);
  	} while (len > 0);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
328
329
  
  	return csum;
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
330
  }
4bdb54797   Chris Packham   tools/kwbimage: a...
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
  static uint8_t baudrate_to_option(unsigned int baudrate)
  {
  	switch (baudrate) {
  	case 2400:
  		return MAIN_HDR_V1_OPT_BAUD_2400;
  	case 4800:
  		return MAIN_HDR_V1_OPT_BAUD_4800;
  	case 9600:
  		return MAIN_HDR_V1_OPT_BAUD_9600;
  	case 19200:
  		return MAIN_HDR_V1_OPT_BAUD_19200;
  	case 38400:
  		return MAIN_HDR_V1_OPT_BAUD_38400;
  	case 57600:
  		return MAIN_HDR_V1_OPT_BAUD_57600;
  	case 115200:
  		return MAIN_HDR_V1_OPT_BAUD_115200;
  	default:
  		return MAIN_HDR_V1_OPT_BAUD_DEFAULT;
  	}
  }
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
  #if defined(CONFIG_KWB_SECURE)
  static void kwb_msg(const char *fmt, ...)
  {
  	if (verbose_mode) {
  		va_list ap;
  
  		va_start(ap, fmt);
  		vfprintf(stdout, fmt, ap);
  		va_end(ap);
  	}
  }
  
  static int openssl_err(const char *msg)
  {
  	unsigned long ssl_err = ERR_get_error();
  
  	fprintf(stderr, "%s", msg);
  	fprintf(stderr, ": %s
  ",
  		ERR_error_string(ssl_err, 0));
  
  	return -1;
  }
  
  static int kwb_load_rsa_key(const char *keydir, const char *name, RSA **p_rsa)
  {
  	char path[PATH_MAX];
  	RSA *rsa;
  	FILE *f;
  
  	if (!keydir)
  		keydir = ".";
  
  	snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
  	f = fopen(path, "r");
  	if (!f) {
  		fprintf(stderr, "Couldn't open RSA private key: '%s': %s
  ",
  			path, strerror(errno));
  		return -ENOENT;
  	}
  
  	rsa = PEM_read_RSAPrivateKey(f, 0, NULL, "");
  	if (!rsa) {
  		openssl_err("Failure reading private key");
  		fclose(f);
  		return -EPROTO;
  	}
  	fclose(f);
  	*p_rsa = rsa;
  
  	return 0;
  }
  
  static int kwb_load_cfg_key(struct image_tool_params *params,
  			    unsigned int cfg_option, const char *key_name,
  			    RSA **p_key)
  {
  	struct image_cfg_element *e_key;
  	RSA *key;
  	int res;
  
  	*p_key = NULL;
  
  	e_key = image_find_option(cfg_option);
  	if (!e_key) {
  		fprintf(stderr, "%s not configured
  ", key_name);
  		return -ENOENT;
  	}
  
  	res = kwb_load_rsa_key(params->keydir, e_key->key_name, &key);
  	if (res < 0) {
  		fprintf(stderr, "Failed to load %s
  ", key_name);
  		return -ENOENT;
  	}
  
  	*p_key = key;
  
  	return 0;
  }
  
  static int kwb_load_kak(struct image_tool_params *params, RSA **p_kak)
  {
  	return kwb_load_cfg_key(params, IMAGE_CFG_KAK, "KAK", p_kak);
  }
  
  static int kwb_load_csk(struct image_tool_params *params, RSA **p_csk)
  {
  	return kwb_load_cfg_key(params, IMAGE_CFG_CSK, "CSK", p_csk);
  }
  
  static int kwb_compute_pubkey_hash(struct pubkey_der_v1 *pk,
  				   struct hash_v1 *hash)
  {
  	EVP_MD_CTX *ctx;
  	unsigned int key_size;
  	unsigned int hash_size;
  	int ret = 0;
  
  	if (!pk || !hash || pk->key[0] != 0x30 || pk->key[1] != 0x82)
  		return -EINVAL;
  
  	key_size = (pk->key[2] << 8) + pk->key[3] + 4;
  
  	ctx = EVP_MD_CTX_create();
  	if (!ctx)
  		return openssl_err("EVP context creation failed");
  
  	EVP_MD_CTX_init(ctx);
  	if (!EVP_DigestInit(ctx, EVP_sha256())) {
  		ret = openssl_err("Digest setup failed");
  		goto hash_err_ctx;
  	}
  
  	if (!EVP_DigestUpdate(ctx, pk->key, key_size)) {
  		ret = openssl_err("Hashing data failed");
  		goto hash_err_ctx;
  	}
  
  	if (!EVP_DigestFinal(ctx, hash->hash, &hash_size)) {
  		ret = openssl_err("Could not obtain hash");
  		goto hash_err_ctx;
  	}
  
  	EVP_MD_CTX_cleanup(ctx);
  
  hash_err_ctx:
  	EVP_MD_CTX_destroy(ctx);
  	return ret;
  }
  
  static int kwb_import_pubkey(RSA **key, struct pubkey_der_v1 *src, char *keyname)
  {
  	RSA *rsa;
  	const unsigned char *ptr;
  
  	if (!key || !src)
  		goto fail;
  
  	ptr = src->key;
  	rsa = d2i_RSAPublicKey(key, &ptr, sizeof(src->key));
  	if (!rsa) {
  		openssl_err("error decoding public key");
  		goto fail;
  	}
  
  	return 0;
  fail:
  	fprintf(stderr, "Failed to decode %s pubkey
  ", keyname);
  	return -EINVAL;
  }
  
  static int kwb_export_pubkey(RSA *key, struct pubkey_der_v1 *dst, FILE *hashf,
  			     char *keyname)
  {
  	int size_exp, size_mod, size_seq;
e15843b11   Jelle van der Waa   tools: kwbimage f...
511
  	const BIGNUM *key_e, *key_n;
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
512
513
514
  	uint8_t *cur;
  	char *errmsg = "Failed to encode %s
  ";
e15843b11   Jelle van der Waa   tools: kwbimage f...
515
516
517
518
  	RSA_get0_key(key, NULL, &key_e, NULL);
  	RSA_get0_key(key, &key_n, NULL, NULL);
  
  	if (!key || !key_e || !key_n || !dst) {
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
519
  		fprintf(stderr, "export pk failed: (%p, %p, %p, %p)",
e15843b11   Jelle van der Waa   tools: kwbimage f...
520
  			key, key_e, key_n, dst);
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
521
522
523
524
525
526
527
528
529
530
531
532
533
  		fprintf(stderr, errmsg, keyname);
  		return -EINVAL;
  	}
  
  	/*
  	 * According to the specs, the key should be PKCS#1 DER encoded.
  	 * But unfortunately the really required encoding seems to be different;
  	 * it violates DER...! (But it still conformes to BER.)
  	 * (Length always in long form w/ 2 byte length code; no leading zero
  	 * when MSB of first byte is set...)
  	 * So we cannot use the encoding func provided by OpenSSL and have to
  	 * do the encoding manually.
  	 */
e15843b11   Jelle van der Waa   tools: kwbimage f...
534
535
  	size_exp = BN_num_bytes(key_e);
  	size_mod = BN_num_bytes(key_n);
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
  	size_seq = 4 + size_mod + 4 + size_exp;
  
  	if (size_mod > 256) {
  		fprintf(stderr, "export pk failed: wrong mod size: %d
  ",
  			size_mod);
  		fprintf(stderr, errmsg, keyname);
  		return -EINVAL;
  	}
  
  	if (4 + size_seq > sizeof(dst->key)) {
  		fprintf(stderr, "export pk failed: seq too large (%d, %lu)
  ",
  			4 + size_seq, sizeof(dst->key));
  		fprintf(stderr, errmsg, keyname);
  		return -ENOBUFS;
  	}
  
  	cur = dst->key;
  
  	/* PKCS#1 (RFC3447) RSAPublicKey structure */
  	*cur++ = 0x30;		/* SEQUENCE */
  	*cur++ = 0x82;
  	*cur++ = (size_seq >> 8) & 0xFF;
  	*cur++ = size_seq & 0xFF;
  	/* Modulus */
  	*cur++ = 0x02;		/* INTEGER */
  	*cur++ = 0x82;
  	*cur++ = (size_mod >> 8) & 0xFF;
  	*cur++ = size_mod & 0xFF;
e15843b11   Jelle van der Waa   tools: kwbimage f...
566
  	BN_bn2bin(key_n, cur);
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
567
568
569
570
571
572
  	cur += size_mod;
  	/* Exponent */
  	*cur++ = 0x02;		/* INTEGER */
  	*cur++ = 0x82;
  	*cur++ = (size_exp >> 8) & 0xFF;
  	*cur++ = size_exp & 0xFF;
e15843b11   Jelle van der Waa   tools: kwbimage f...
573
  	BN_bn2bin(key_e, cur);
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
  
  	if (hashf) {
  		struct hash_v1 pk_hash;
  		int i;
  		int ret = 0;
  
  		ret = kwb_compute_pubkey_hash(dst, &pk_hash);
  		if (ret < 0) {
  			fprintf(stderr, errmsg, keyname);
  			return ret;
  		}
  
  		fprintf(hashf, "SHA256 = ");
  		for (i = 0 ; i < sizeof(pk_hash.hash); ++i)
  			fprintf(hashf, "%02X", pk_hash.hash[i]);
  		fprintf(hashf, "
  ");
  	}
  
  	return 0;
  }
  
  int kwb_sign(RSA *key, void *data, int datasz, struct sig_v1 *sig, char *signame)
  {
  	EVP_PKEY *evp_key;
  	EVP_MD_CTX *ctx;
  	unsigned int sig_size;
  	int size;
  	int ret = 0;
  
  	evp_key = EVP_PKEY_new();
  	if (!evp_key)
  		return openssl_err("EVP_PKEY object creation failed");
  
  	if (!EVP_PKEY_set1_RSA(evp_key, key)) {
  		ret = openssl_err("EVP key setup failed");
  		goto err_key;
  	}
  
  	size = EVP_PKEY_size(evp_key);
  	if (size > sizeof(sig->sig)) {
  		fprintf(stderr, "Buffer to small for signature (%d bytes)
  ",
  			size);
  		ret = -ENOBUFS;
  		goto err_key;
  	}
  
  	ctx = EVP_MD_CTX_create();
  	if (!ctx) {
  		ret = openssl_err("EVP context creation failed");
  		goto err_key;
  	}
  	EVP_MD_CTX_init(ctx);
  	if (!EVP_SignInit(ctx, EVP_sha256())) {
  		ret = openssl_err("Signer setup failed");
  		goto err_ctx;
  	}
  
  	if (!EVP_SignUpdate(ctx, data, datasz)) {
  		ret = openssl_err("Signing data failed");
  		goto err_ctx;
  	}
  
  	if (!EVP_SignFinal(ctx, sig->sig, &sig_size, evp_key)) {
  		ret = openssl_err("Could not obtain signature");
  		goto err_ctx;
  	}
  
  	EVP_MD_CTX_cleanup(ctx);
  	EVP_MD_CTX_destroy(ctx);
  	EVP_PKEY_free(evp_key);
  
  	return 0;
  
  err_ctx:
  	EVP_MD_CTX_destroy(ctx);
  err_key:
  	EVP_PKEY_free(evp_key);
  	fprintf(stderr, "Failed to create %s signature
  ", signame);
  	return ret;
  }
  
  int kwb_verify(RSA *key, void *data, int datasz, struct sig_v1 *sig,
  	       char *signame)
  {
  	EVP_PKEY *evp_key;
  	EVP_MD_CTX *ctx;
  	int size;
  	int ret = 0;
  
  	evp_key = EVP_PKEY_new();
  	if (!evp_key)
  		return openssl_err("EVP_PKEY object creation failed");
  
  	if (!EVP_PKEY_set1_RSA(evp_key, key)) {
  		ret = openssl_err("EVP key setup failed");
  		goto err_key;
  	}
  
  	size = EVP_PKEY_size(evp_key);
  	if (size > sizeof(sig->sig)) {
  		fprintf(stderr, "Invalid signature size (%d bytes)
  ",
  			size);
  		ret = -EINVAL;
  		goto err_key;
  	}
  
  	ctx = EVP_MD_CTX_create();
  	if (!ctx) {
  		ret = openssl_err("EVP context creation failed");
  		goto err_key;
  	}
  	EVP_MD_CTX_init(ctx);
  	if (!EVP_VerifyInit(ctx, EVP_sha256())) {
  		ret = openssl_err("Verifier setup failed");
  		goto err_ctx;
  	}
  
  	if (!EVP_VerifyUpdate(ctx, data, datasz)) {
  		ret = openssl_err("Hashing data failed");
  		goto err_ctx;
  	}
  
  	if (!EVP_VerifyFinal(ctx, sig->sig, sizeof(sig->sig), evp_key)) {
  		ret = openssl_err("Could not verify signature");
  		goto err_ctx;
  	}
  
  	EVP_MD_CTX_cleanup(ctx);
  	EVP_MD_CTX_destroy(ctx);
  	EVP_PKEY_free(evp_key);
  
  	return 0;
  
  err_ctx:
  	EVP_MD_CTX_destroy(ctx);
  err_key:
  	EVP_PKEY_free(evp_key);
  	fprintf(stderr, "Failed to verify %s signature
  ", signame);
  	return ret;
  }
  
  int kwb_sign_and_verify(RSA *key, void *data, int datasz, struct sig_v1 *sig,
  			char *signame)
  {
  	if (kwb_sign(key, data, datasz, sig, signame) < 0)
  		return -1;
  
  	if (kwb_verify(key, data, datasz, sig, signame) < 0)
  		return -1;
  
  	return 0;
  }
  
  
  int kwb_dump_fuse_cmds_38x(FILE *out, struct secure_hdr_v1 *sec_hdr)
  {
  	struct hash_v1 kak_pub_hash;
  	struct image_cfg_element *e;
  	unsigned int fuse_line;
  	int i, idx;
  	uint8_t *ptr;
  	uint32_t val;
  	int ret = 0;
  
  	if (!out || !sec_hdr)
  		return -EINVAL;
  
  	ret = kwb_compute_pubkey_hash(&sec_hdr->kak, &kak_pub_hash);
  	if (ret < 0)
  		goto done;
  
  	fprintf(out, "# burn KAK pub key hash
  ");
  	ptr = kak_pub_hash.hash;
  	for (fuse_line = 26; fuse_line <= 30; ++fuse_line) {
  		fprintf(out, "fuse prog -y %u 0 ", fuse_line);
  
  		for (i = 4; i-- > 0;)
  			fprintf(out, "%02hx", (ushort)ptr[i]);
  		ptr += 4;
  		fprintf(out, " 00");
  
  		if (fuse_line < 30) {
  			for (i = 3; i-- > 0;)
  				fprintf(out, "%02hx", (ushort)ptr[i]);
  			ptr += 3;
  		} else {
  			fprintf(out, "000000");
  		}
  
  		fprintf(out, " 1
  ");
  	}
  
  	fprintf(out, "# burn CSK selection
  ");
  
  	idx = image_get_csk_index();
  	if (idx < 0 || idx > 15) {
  		ret = -EINVAL;
  		goto done;
  	}
  	if (idx > 0) {
  		for (fuse_line = 31; fuse_line < 31 + idx; ++fuse_line)
  			fprintf(out, "fuse prog -y %u 0 00000001 00000000 1
  ",
  				fuse_line);
  	} else {
  		fprintf(out, "# CSK index is 0; no mods needed
  ");
  	}
  
  	e = image_find_option(IMAGE_CFG_BOX_ID);
  	if (e) {
  		fprintf(out, "# set box ID
  ");
  		fprintf(out, "fuse prog -y 48 0 %08x 00000000 1
  ", e->boxid);
  	}
  
  	e = image_find_option(IMAGE_CFG_FLASH_ID);
  	if (e) {
  		fprintf(out, "# set flash ID
  ");
  		fprintf(out, "fuse prog -y 47 0 %08x 00000000 1
  ", e->flashid);
  	}
  
  	fprintf(out, "# enable secure mode ");
  	fprintf(out, "(must be the last fuse line written)
  ");
  
  	val = 1;
  	e = image_find_option(IMAGE_CFG_SEC_BOOT_DEV);
  	if (!e) {
  		fprintf(stderr, "ERROR: secured mode boot device not given
  ");
  		ret = -EINVAL;
  		goto done;
  	}
  
  	if (e->sec_boot_dev > 0xff) {
  		fprintf(stderr, "ERROR: secured mode boot device invalid
  ");
  		ret = -EINVAL;
  		goto done;
  	}
  
  	val |= (e->sec_boot_dev << 8);
  
  	fprintf(out, "fuse prog -y 24 0 %08x 0103e0a9 1
  ", val);
  
  	fprintf(out, "# lock (unused) fuse lines (0-23)s
  ");
  	for (fuse_line = 0; fuse_line < 24; ++fuse_line)
  		fprintf(out, "fuse prog -y %u 2 1
  ", fuse_line);
  
  	fprintf(out, "# OK, that's all :-)
  ");
  
  done:
  	return ret;
  }
  
  static int kwb_dump_fuse_cmds(struct secure_hdr_v1 *sec_hdr)
  {
  	int ret = 0;
  	struct image_cfg_element *e;
  
  	e = image_find_option(IMAGE_CFG_SEC_FUSE_DUMP);
  	if (!e)
  		return 0;
  
  	if (!strcmp(e->name, "a38x")) {
  		FILE *out = fopen("kwb_fuses_a38x.txt", "w+");
  
  		kwb_dump_fuse_cmds_38x(out, sec_hdr);
  		fclose(out);
  		goto done;
  	}
  
  	ret = -ENOSYS;
  
  done:
  	return ret;
  }
  
  #endif
4acd2d24b   Stefan Roese   tools: kwbimage: ...
869
870
  static void *image_create_v0(size_t *imagesz, struct image_tool_params *params,
  			     int payloadsz)
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
871
  {
4acd2d24b   Stefan Roese   tools: kwbimage: ...
872
873
874
  	struct image_cfg_element *e;
  	size_t headersz;
  	struct main_hdr_v0 *main_hdr;
885fba155   Mario Six   tools: kwbimage: ...
875
  	uint8_t *image;
4acd2d24b   Stefan Roese   tools: kwbimage: ...
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
  	int has_ext = 0;
  
  	/*
  	 * Calculate the size of the header and the size of the
  	 * payload
  	 */
  	headersz  = sizeof(struct main_hdr_v0);
  
  	if (image_count_options(IMAGE_CFG_DATA) > 0) {
  		has_ext = 1;
  		headersz += sizeof(struct ext_hdr_v0);
  	}
  
  	if (image_count_options(IMAGE_CFG_PAYLOAD) > 1) {
  		fprintf(stderr, "More than one payload, not possible
  ");
  		return NULL;
  	}
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
894

4acd2d24b   Stefan Roese   tools: kwbimage: ...
895
896
897
898
899
  	image = malloc(headersz);
  	if (!image) {
  		fprintf(stderr, "Cannot allocate memory for image
  ");
  		return NULL;
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
900
  	}
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
901

4acd2d24b   Stefan Roese   tools: kwbimage: ...
902
  	memset(image, 0, headersz);
885fba155   Mario Six   tools: kwbimage: ...
903
  	main_hdr = (struct main_hdr_v0 *)image;
4acd2d24b   Stefan Roese   tools: kwbimage: ...
904
905
  
  	/* Fill in the main header */
a8840dced   Reinhard Pfau   tools/kwbimage: f...
906
907
908
  	main_hdr->blocksize =
  		cpu_to_le32(payloadsz + sizeof(uint32_t) - headersz);
  	main_hdr->srcaddr   = cpu_to_le32(headersz);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
909
  	main_hdr->ext       = has_ext;
a8840dced   Reinhard Pfau   tools/kwbimage: f...
910
911
  	main_hdr->destaddr  = cpu_to_le32(params->addr);
  	main_hdr->execaddr  = cpu_to_le32(params->ep);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
912
913
914
915
916
917
918
919
920
  
  	e = image_find_option(IMAGE_CFG_BOOT_FROM);
  	if (e)
  		main_hdr->blockid = e->bootfrom;
  	e = image_find_option(IMAGE_CFG_NAND_ECC_MODE);
  	if (e)
  		main_hdr->nandeccmode = e->nandeccmode;
  	e = image_find_option(IMAGE_CFG_NAND_PAGESZ);
  	if (e)
a8840dced   Reinhard Pfau   tools/kwbimage: f...
921
  		main_hdr->nandpagesize = cpu_to_le16(e->nandpagesz);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
922
923
924
925
926
  	main_hdr->checksum = image_checksum8(image,
  					     sizeof(struct main_hdr_v0));
  
  	/* Generate the ext header */
  	if (has_ext) {
e89016c44   Mario Six   tools: kwbimage: ...
927
  		struct ext_hdr_v0 *ext_hdr;
4acd2d24b   Stefan Roese   tools: kwbimage: ...
928
  		int cfgi, datai;
885fba155   Mario Six   tools: kwbimage: ...
929
930
  		ext_hdr = (struct ext_hdr_v0 *)
  				(image + sizeof(struct main_hdr_v0));
a8840dced   Reinhard Pfau   tools/kwbimage: f...
931
  		ext_hdr->offset = cpu_to_le32(0x40);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
932
933
934
935
936
  
  		for (cfgi = 0, datai = 0; cfgi < cfgn; cfgi++) {
  			e = &image_cfg[cfgi];
  			if (e->type != IMAGE_CFG_DATA)
  				continue;
a8840dced   Reinhard Pfau   tools/kwbimage: f...
937
938
939
940
  			ext_hdr->rcfg[datai].raddr =
  				cpu_to_le32(e->regdata.raddr);
  			ext_hdr->rcfg[datai].rdata =
  				cpu_to_le32(e->regdata.rdata);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
941
942
943
944
945
946
947
948
949
  			datai++;
  		}
  
  		ext_hdr->checksum = image_checksum8(ext_hdr,
  						    sizeof(struct ext_hdr_v0));
  	}
  
  	*imagesz = headersz;
  	return image;
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
950
  }
e93cf53f1   Mario Six   tools: kwbimage: ...
951
  static size_t image_headersz_v1(int *hasext)
4acd2d24b   Stefan Roese   tools: kwbimage: ...
952
953
954
  {
  	struct image_cfg_element *binarye;
  	size_t headersz;
4acd2d24b   Stefan Roese   tools: kwbimage: ...
955
956
957
958
959
960
961
962
963
964
965
  
  	/*
  	 * Calculate the size of the header and the size of the
  	 * payload
  	 */
  	headersz = sizeof(struct main_hdr_v1);
  
  	if (image_count_options(IMAGE_CFG_BINARY) > 1) {
  		fprintf(stderr, "More than one binary blob, not supported
  ");
  		return 0;
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
966
  	}
4acd2d24b   Stefan Roese   tools: kwbimage: ...
967
968
969
970
971
  	if (image_count_options(IMAGE_CFG_PAYLOAD) > 1) {
  		fprintf(stderr, "More than one payload, not possible
  ");
  		return 0;
  	}
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
972

4acd2d24b   Stefan Roese   tools: kwbimage: ...
973
974
  	binarye = image_find_option(IMAGE_CFG_BINARY);
  	if (binarye) {
e89016c44   Mario Six   tools: kwbimage: ...
975
  		int ret;
4acd2d24b   Stefan Roese   tools: kwbimage: ...
976
977
978
979
  		struct stat s;
  
  		ret = stat(binarye->binary.file, &s);
  		if (ret < 0) {
e5f1a586a   Andreas Bießmann   tools/kwbimage.c:...
980
981
982
983
984
985
986
987
  			char cwd[PATH_MAX];
  			char *dir = cwd;
  
  			memset(cwd, 0, sizeof(cwd));
  			if (!getcwd(cwd, sizeof(cwd))) {
  				dir = "current working directory";
  				perror("getcwd() failed");
  			}
4acd2d24b   Stefan Roese   tools: kwbimage: ...
988
989
990
991
992
993
994
  			fprintf(stderr,
  				"Didn't find the file '%s' in '%s' which is mandatory to generate the image
  "
  				"This file generally contains the DDR3 training code, and should be extracted from an existing bootable
  "
  				"image for your board. See 'kwbimage -x' to extract it from an existing image.
  ",
e5f1a586a   Andreas Bießmann   tools/kwbimage.c:...
995
  				binarye->binary.file, dir);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
996
997
  			return 0;
  		}
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
998

76b391cde   Reinhard Pfau   tools/kwbimage: f...
999
1000
1001
  		headersz += sizeof(struct opt_hdr_v1) +
  			s.st_size +
  			(binarye->binary.nargs + 2) * sizeof(uint32_t);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1002
1003
1004
  		if (hasext)
  			*hasext = 1;
  	}
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1005

a1b6b0a9c   Mario Six   arm: mvebu: Imple...
1006
1007
1008
1009
1010
1011
1012
  #if defined(CONFIG_KWB_SECURE)
  	if (image_get_csk_index() >= 0) {
  		headersz += sizeof(struct secure_hdr_v1);
  		if (hasext)
  			*hasext = 1;
  	}
  #endif
7ddf8cfb0   Stefan Roese   kwbimage: Rename ...
1013
1014
  #if defined(CONFIG_SYS_U_BOOT_OFFS)
  	if (headersz > CONFIG_SYS_U_BOOT_OFFS) {
94490a4a7   Mario Six   tools: kwbimage: ...
1015
1016
1017
  		fprintf(stderr,
  			"Error: Image header (incl. SPL image) too big!
  ");
7ddf8cfb0   Stefan Roese   kwbimage: Rename ...
1018
1019
1020
1021
1022
  		fprintf(stderr, "header=0x%x CONFIG_SYS_U_BOOT_OFFS=0x%x!
  ",
  			(int)headersz, CONFIG_SYS_U_BOOT_OFFS);
  		fprintf(stderr, "Increase CONFIG_SYS_U_BOOT_OFFS!
  ");
a0aad1234   Kevin Smith   tools/kwbimage.c:...
1023
  		return 0;
a0aad1234   Kevin Smith   tools/kwbimage.c:...
1024
  	}
79066ef8c   Mario Six   tools: kwbimage: ...
1025

94490a4a7   Mario Six   tools: kwbimage: ...
1026
  	headersz = CONFIG_SYS_U_BOOT_OFFS;
a0aad1234   Kevin Smith   tools/kwbimage.c:...
1027
  #endif
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1028
1029
1030
1031
1032
1033
  	/*
  	 * The payload should be aligned on some reasonable
  	 * boundary
  	 */
  	return ALIGN_SUP(headersz, 4096);
  }
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1034

79066ef8c   Mario Six   tools: kwbimage: ...
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
  int add_binary_header_v1(uint8_t *cur)
  {
  	struct image_cfg_element *binarye;
  	struct opt_hdr_v1 *hdr = (struct opt_hdr_v1 *)cur;
  	uint32_t *args;
  	size_t binhdrsz;
  	struct stat s;
  	int argi;
  	FILE *bin;
  	int ret;
  
  	binarye = image_find_option(IMAGE_CFG_BINARY);
  
  	if (!binarye)
  		return 0;
  
  	hdr->headertype = OPT_HDR_V1_BINARY_TYPE;
  
  	bin = fopen(binarye->binary.file, "r");
  	if (!bin) {
  		fprintf(stderr, "Cannot open binary file %s
  ",
  			binarye->binary.file);
  		return -1;
  	}
1f6c8a573   Mario Six   tools: kwbimage: ...
1060
1061
1062
1063
1064
1065
  	if (fstat(fileno(bin), &s)) {
  		fprintf(stderr, "Cannot stat binary file %s
  ",
  			binarye->binary.file);
  		goto err_close;
  	}
79066ef8c   Mario Six   tools: kwbimage: ...
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
  
  	binhdrsz = sizeof(struct opt_hdr_v1) +
  		(binarye->binary.nargs + 2) * sizeof(uint32_t) +
  		s.st_size;
  
  	/*
  	 * The size includes the binary image size, rounded
  	 * up to a 4-byte boundary. Plus 4 bytes for the
  	 * next-header byte and 3-byte alignment at the end.
  	 */
  	binhdrsz = ALIGN_SUP(binhdrsz, 4) + 4;
  	hdr->headersz_lsb = cpu_to_le16(binhdrsz & 0xFFFF);
  	hdr->headersz_msb = (binhdrsz & 0xFFFF0000) >> 16;
  
  	cur += sizeof(struct opt_hdr_v1);
  
  	args = (uint32_t *)cur;
  	*args = cpu_to_le32(binarye->binary.nargs);
  	args++;
  	for (argi = 0; argi < binarye->binary.nargs; argi++)
  		args[argi] = cpu_to_le32(binarye->binary.args[argi]);
  
  	cur += (binarye->binary.nargs + 1) * sizeof(uint32_t);
  
  	ret = fread(cur, s.st_size, 1, bin);
  	if (ret != 1) {
  		fprintf(stderr,
  			"Could not read binary image %s
  ",
  			binarye->binary.file);
1f6c8a573   Mario Six   tools: kwbimage: ...
1096
  		goto err_close;
79066ef8c   Mario Six   tools: kwbimage: ...
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
  	}
  
  	fclose(bin);
  
  	cur += ALIGN_SUP(s.st_size, 4);
  
  	/*
  	 * For now, we don't support more than one binary
  	 * header, and no other header types are
  	 * supported. So, the binary header is necessarily the
  	 * last one
  	 */
  	*((uint32_t *)cur) = 0x00000000;
  
  	cur += sizeof(uint32_t);
  
  	return 0;
1f6c8a573   Mario Six   tools: kwbimage: ...
1114
1115
1116
1117
1118
  
  err_close:
  	fclose(bin);
  
  	return -1;
79066ef8c   Mario Six   tools: kwbimage: ...
1119
  }
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
  #if defined(CONFIG_KWB_SECURE)
  
  int export_pub_kak_hash(RSA *kak, struct secure_hdr_v1 *secure_hdr)
  {
  	FILE *hashf;
  	int res;
  
  	hashf = fopen("pub_kak_hash.txt", "w");
  
  	res = kwb_export_pubkey(kak, &secure_hdr->kak, hashf, "KAK");
  
  	fclose(hashf);
  
  	return res < 0 ? 1 : 0;
  }
  
  int kwb_sign_csk_with_kak(struct image_tool_params *params,
  			  struct secure_hdr_v1 *secure_hdr, RSA *csk)
  {
  	RSA *kak = NULL;
  	RSA *kak_pub = NULL;
  	int csk_idx = image_get_csk_index();
  	struct sig_v1 tmp_sig;
  
  	if (csk_idx >= 16) {
  		fprintf(stderr, "Invalid CSK index %d
  ", csk_idx);
  		return 1;
  	}
  
  	if (kwb_load_kak(params, &kak) < 0)
  		return 1;
  
  	if (export_pub_kak_hash(kak, secure_hdr))
  		return 1;
  
  	if (kwb_import_pubkey(&kak_pub, &secure_hdr->kak, "KAK") < 0)
  		return 1;
  
  	if (kwb_export_pubkey(csk, &secure_hdr->csk[csk_idx], NULL, "CSK") < 0)
  		return 1;
  
  	if (kwb_sign_and_verify(kak, &secure_hdr->csk,
  				sizeof(secure_hdr->csk) +
  				sizeof(secure_hdr->csksig),
  				&tmp_sig, "CSK") < 0)
  		return 1;
  
  	if (kwb_verify(kak_pub, &secure_hdr->csk,
  		       sizeof(secure_hdr->csk) +
  		       sizeof(secure_hdr->csksig),
  		       &tmp_sig, "CSK (2)") < 0)
  		return 1;
  
  	secure_hdr->csksig = tmp_sig;
  
  	return 0;
  }
  
  int add_secure_header_v1(struct image_tool_params *params, uint8_t *ptr,
  			 int payloadsz, size_t headersz, uint8_t *image,
  			 struct secure_hdr_v1 *secure_hdr)
  {
  	struct image_cfg_element *e_jtagdelay;
  	struct image_cfg_element *e_boxid;
  	struct image_cfg_element *e_flashid;
  	RSA *csk = NULL;
  	unsigned char *image_ptr;
  	size_t image_size;
  	struct sig_v1 tmp_sig;
  	bool specialized_img = image_get_spezialized_img();
  
  	kwb_msg("Create secure header content
  ");
  
  	e_jtagdelay = image_find_option(IMAGE_CFG_JTAG_DELAY);
  	e_boxid = image_find_option(IMAGE_CFG_BOX_ID);
  	e_flashid = image_find_option(IMAGE_CFG_FLASH_ID);
  
  	if (kwb_load_csk(params, &csk) < 0)
  		return 1;
  
  	secure_hdr->headertype = OPT_HDR_V1_SECURE_TYPE;
  	secure_hdr->headersz_msb = 0;
  	secure_hdr->headersz_lsb = cpu_to_le16(sizeof(struct secure_hdr_v1));
  	if (e_jtagdelay)
  		secure_hdr->jtag_delay = e_jtagdelay->jtag_delay;
  	if (e_boxid && specialized_img)
  		secure_hdr->boxid = cpu_to_le32(e_boxid->boxid);
  	if (e_flashid && specialized_img)
  		secure_hdr->flashid = cpu_to_le32(e_flashid->flashid);
  
  	if (kwb_sign_csk_with_kak(params, secure_hdr, csk))
  		return 1;
  
  	image_ptr = ptr + headersz;
  	image_size = payloadsz - headersz;
  
  	if (kwb_sign_and_verify(csk, image_ptr, image_size,
  				&secure_hdr->imgsig, "image") < 0)
  		return 1;
  
  	if (kwb_sign_and_verify(csk, image, headersz, &tmp_sig, "header") < 0)
  		return 1;
  
  	secure_hdr->hdrsig = tmp_sig;
  
  	kwb_dump_fuse_cmds(secure_hdr);
  
  	return 0;
  }
  #endif
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1232
  static void *image_create_v1(size_t *imagesz, struct image_tool_params *params,
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
1233
  			     uint8_t *ptr, int payloadsz)
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1234
  {
79066ef8c   Mario Six   tools: kwbimage: ...
1235
  	struct image_cfg_element *e;
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1236
  	struct main_hdr_v1 *main_hdr;
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
1237
1238
1239
  #if defined(CONFIG_KWB_SECURE)
  	struct secure_hdr_v1 *secure_hdr = NULL;
  #endif
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1240
  	size_t headersz;
885fba155   Mario Six   tools: kwbimage: ...
1241
  	uint8_t *image, *cur;
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1242
  	int hasext = 0;
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
1243
  	uint8_t *next_ext = NULL;
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1244
1245
1246
1247
1248
  
  	/*
  	 * Calculate the size of the header and the size of the
  	 * payload
  	 */
e93cf53f1   Mario Six   tools: kwbimage: ...
1249
  	headersz = image_headersz_v1(&hasext);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1250
1251
1252
1253
1254
1255
1256
1257
1258
  	if (headersz == 0)
  		return NULL;
  
  	image = malloc(headersz);
  	if (!image) {
  		fprintf(stderr, "Cannot allocate memory for image
  ");
  		return NULL;
  	}
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1259

4acd2d24b   Stefan Roese   tools: kwbimage: ...
1260
  	memset(image, 0, headersz);
885fba155   Mario Six   tools: kwbimage: ...
1261
  	main_hdr = (struct main_hdr_v1 *)image;
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
1262
1263
1264
  	cur = image;
  	cur += sizeof(struct main_hdr_v1);
  	next_ext = &main_hdr->ext;
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1265
1266
  
  	/* Fill the main header */
a8840dced   Reinhard Pfau   tools/kwbimage: f...
1267
1268
1269
  	main_hdr->blocksize    =
  		cpu_to_le32(payloadsz - headersz + sizeof(uint32_t));
  	main_hdr->headersz_lsb = cpu_to_le16(headersz & 0xFFFF);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1270
  	main_hdr->headersz_msb = (headersz & 0xFFFF0000) >> 16;
94084eea3   Mario Six   tools: kwbimage: ...
1271
1272
  	main_hdr->destaddr     = cpu_to_le32(params->addr)
  				 - sizeof(image_header_t);
a8840dced   Reinhard Pfau   tools/kwbimage: f...
1273
1274
  	main_hdr->execaddr     = cpu_to_le32(params->ep);
  	main_hdr->srcaddr      = cpu_to_le32(headersz);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
  	main_hdr->ext          = hasext;
  	main_hdr->version      = 1;
  	e = image_find_option(IMAGE_CFG_BOOT_FROM);
  	if (e)
  		main_hdr->blockid = e->bootfrom;
  	e = image_find_option(IMAGE_CFG_NAND_BLKSZ);
  	if (e)
  		main_hdr->nandblocksize = e->nandblksz / (64 * 1024);
  	e = image_find_option(IMAGE_CFG_NAND_BADBLK_LOCATION);
  	if (e)
  		main_hdr->nandbadblklocation = e->nandbadblklocation;
4bdb54797   Chris Packham   tools/kwbimage: a...
1286
1287
1288
  	e = image_find_option(IMAGE_CFG_BAUDRATE);
  	if (e)
  		main_hdr->options = baudrate_to_option(e->baudrate);
2611c05e8   Chris Packham   tools/kwbimage: a...
1289
1290
1291
  	e = image_find_option(IMAGE_CFG_DEBUG);
  	if (e)
  		main_hdr->flags = e->debug ? 0x1 : 0;
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1292

a1b6b0a9c   Mario Six   arm: mvebu: Imple...
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
  #if defined(CONFIG_KWB_SECURE)
  	if (image_get_csk_index() >= 0) {
  		/*
  		 * only reserve the space here; we fill the header later since
  		 * we need the header to be complete to compute the signatures
  		 */
  		secure_hdr = (struct secure_hdr_v1 *)cur;
  		cur += sizeof(struct secure_hdr_v1);
  		next_ext = &secure_hdr->next;
  	}
  #endif
  	*next_ext = 1;
79066ef8c   Mario Six   tools: kwbimage: ...
1305
1306
  	if (add_binary_header_v1(cur))
  		return NULL;
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1307

a1b6b0a9c   Mario Six   arm: mvebu: Imple...
1308
1309
1310
1311
1312
  #if defined(CONFIG_KWB_SECURE)
  	if (secure_hdr && add_secure_header_v1(params, ptr, payloadsz,
  					       headersz, image, secure_hdr))
  		return NULL;
  #endif
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1313
1314
1315
1316
1317
1318
  	/* Calculate and set the header checksum */
  	main_hdr->checksum = image_checksum8(main_hdr, headersz);
  
  	*imagesz = headersz;
  	return image;
  }
4991b4f7f   Mario Six   tools: kwbimage: ...
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
  int recognize_keyword(char *keyword)
  {
  	int kw_id;
  
  	for (kw_id = 1; kw_id < IMAGE_CFG_COUNT; ++kw_id)
  		if (!strcmp(keyword, id_strs[kw_id]))
  			return kw_id;
  
  	return 0;
  }
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1329
1330
1331
  static int image_create_config_parse_oneline(char *line,
  					     struct image_cfg_element *el)
  {
4991b4f7f   Mario Six   tools: kwbimage: ...
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
  	char *keyword, *saveptr, *value1, *value2;
  	char delimiters[] = " \t";
  	int keyword_id, ret, argi;
  	char *unknown_msg = "Ignoring unknown line '%s'
  ";
  
  	keyword = strtok_r(line, delimiters, &saveptr);
  	keyword_id = recognize_keyword(keyword);
  
  	if (!keyword_id) {
  		fprintf(stderr, unknown_msg, line);
  		return 0;
  	}
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1345

4991b4f7f   Mario Six   tools: kwbimage: ...
1346
  	el->type = keyword_id;
94490a4a7   Mario Six   tools: kwbimage: ...
1347

4991b4f7f   Mario Six   tools: kwbimage: ...
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
  	value1 = strtok_r(NULL, delimiters, &saveptr);
  
  	if (!value1) {
  		fprintf(stderr, "Parameter missing in line '%s'
  ", line);
  		return -1;
  	}
  
  	switch (keyword_id) {
  	case IMAGE_CFG_VERSION:
  		el->version = atoi(value1);
  		break;
  	case IMAGE_CFG_BOOT_FROM:
  		ret = image_boot_mode_id(value1);
94490a4a7   Mario Six   tools: kwbimage: ...
1362

f411b8f22   Andreas Bießmann   tools/kwbimage.c:...
1363
  		if (ret < 0) {
4991b4f7f   Mario Six   tools: kwbimage: ...
1364
1365
  			fprintf(stderr, "Invalid boot media '%s'
  ", value1);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1366
1367
  			return -1;
  		}
f411b8f22   Andreas Bießmann   tools/kwbimage.c:...
1368
  		el->bootfrom = ret;
4991b4f7f   Mario Six   tools: kwbimage: ...
1369
1370
1371
1372
1373
1374
1375
1376
1377
  		break;
  	case IMAGE_CFG_NAND_BLKSZ:
  		el->nandblksz = strtoul(value1, NULL, 16);
  		break;
  	case IMAGE_CFG_NAND_BADBLK_LOCATION:
  		el->nandbadblklocation = strtoul(value1, NULL, 16);
  		break;
  	case IMAGE_CFG_NAND_ECC_MODE:
  		ret = image_nand_ecc_mode_id(value1);
94490a4a7   Mario Six   tools: kwbimage: ...
1378

f411b8f22   Andreas Bießmann   tools/kwbimage.c:...
1379
  		if (ret < 0) {
4991b4f7f   Mario Six   tools: kwbimage: ...
1380
1381
  			fprintf(stderr, "Invalid NAND ECC mode '%s'
  ", value1);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1382
1383
  			return -1;
  		}
f411b8f22   Andreas Bießmann   tools/kwbimage.c:...
1384
  		el->nandeccmode = ret;
4991b4f7f   Mario Six   tools: kwbimage: ...
1385
1386
1387
1388
1389
1390
1391
1392
  		break;
  	case IMAGE_CFG_NAND_PAGESZ:
  		el->nandpagesz = strtoul(value1, NULL, 16);
  		break;
  	case IMAGE_CFG_BINARY:
  		argi = 0;
  
  		el->binary.file = strdup(value1);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1393
  		while (1) {
4991b4f7f   Mario Six   tools: kwbimage: ...
1394
  			char *value = strtok_r(NULL, delimiters, &saveptr);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1395
1396
1397
1398
1399
1400
  			if (!value)
  				break;
  			el->binary.args[argi] = strtoul(value, NULL, 16);
  			argi++;
  			if (argi >= BINARY_MAX_ARGS) {
  				fprintf(stderr,
4991b4f7f   Mario Six   tools: kwbimage: ...
1401
1402
  					"Too many arguments for BINARY
  ");
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1403
  				return -1;
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1404
  			}
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1405
  		}
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1406
  		el->binary.nargs = argi;
4991b4f7f   Mario Six   tools: kwbimage: ...
1407
1408
1409
  		break;
  	case IMAGE_CFG_DATA:
  		value2 = strtok_r(NULL, delimiters, &saveptr);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1410
1411
1412
1413
1414
1415
1416
  
  		if (!value1 || !value2) {
  			fprintf(stderr,
  				"Invalid number of arguments for DATA
  ");
  			return -1;
  		}
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1417
1418
  		el->regdata.raddr = strtoul(value1, NULL, 16);
  		el->regdata.rdata = strtoul(value2, NULL, 16);
4991b4f7f   Mario Six   tools: kwbimage: ...
1419
1420
1421
1422
1423
1424
1425
  		break;
  	case IMAGE_CFG_BAUDRATE:
  		el->baudrate = strtoul(value1, NULL, 10);
  		break;
  	case IMAGE_CFG_DEBUG:
  		el->debug = strtoul(value1, NULL, 10);
  		break;
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
  	case IMAGE_CFG_KAK:
  		el->key_name = strdup(value1);
  		break;
  	case IMAGE_CFG_CSK:
  		el->key_name = strdup(value1);
  		break;
  	case IMAGE_CFG_CSK_INDEX:
  		el->csk_idx = strtol(value1, NULL, 0);
  		break;
  	case IMAGE_CFG_JTAG_DELAY:
  		el->jtag_delay = strtoul(value1, NULL, 0);
  		break;
  	case IMAGE_CFG_BOX_ID:
  		el->boxid = strtoul(value1, NULL, 0);
  		break;
  	case IMAGE_CFG_FLASH_ID:
  		el->flashid = strtoul(value1, NULL, 0);
  		break;
  	case IMAGE_CFG_SEC_SPECIALIZED_IMG:
  		el->sec_specialized_img = true;
  		break;
  	case IMAGE_CFG_SEC_COMMON_IMG:
  		el->sec_specialized_img = false;
  		break;
  	case IMAGE_CFG_SEC_BOOT_DEV:
  		el->sec_boot_dev = strtoul(value1, NULL, 0);
  		break;
  	case IMAGE_CFG_SEC_FUSE_DUMP:
  		el->name = strdup(value1);
  		break;
4991b4f7f   Mario Six   tools: kwbimage: ...
1456
1457
  	default:
  		fprintf(stderr, unknown_msg, line);
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1458
  	}
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1459

4acd2d24b   Stefan Roese   tools: kwbimage: ...
1460
1461
  	return 0;
  }
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1462
1463
  
  /*
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1464
1465
1466
   * Parse the configuration file 'fcfg' into the array of configuration
   * elements 'image_cfg', and return the number of configuration
   * elements in 'cfgn'.
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1467
   */
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
  static int image_create_config_parse(FILE *fcfg)
  {
  	int ret;
  	int cfgi = 0;
  
  	/* Parse the configuration file */
  	while (!feof(fcfg)) {
  		char *line;
  		char buf[256];
  
  		/* Read the current line */
  		memset(buf, 0, sizeof(buf));
  		line = fgets(buf, sizeof(buf), fcfg);
  		if (!line)
  			break;
  
  		/* Ignore useless lines */
  		if (line[0] == '
  ' || line[0] == '#')
  			continue;
  
  		/* Strip final newline */
  		if (line[strlen(line) - 1] == '
  ')
  			line[strlen(line) - 1] = 0;
  
  		/* Parse the current line */
  		ret = image_create_config_parse_oneline(line,
  							&image_cfg[cfgi]);
  		if (ret)
  			return ret;
  
  		cfgi++;
  
  		if (cfgi >= IMAGE_CFG_ELEMENT_MAX) {
  			fprintf(stderr,
  				"Too many configuration elements in .cfg file
  ");
  			return -1;
  		}
  	}
  
  	cfgn = cfgi;
  	return 0;
  }
  
  static int image_get_version(void)
  {
  	struct image_cfg_element *e;
  
  	e = image_find_option(IMAGE_CFG_VERSION);
  	if (!e)
  		return -1;
  
  	return e->version;
  }
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1524
  static void kwbimage_set_header(void *ptr, struct stat *sbuf, int ifd,
f86ed6a8d   Guilherme Maciel Ferreira   tools: moved code...
1525
  				struct image_tool_params *params)
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1526
  {
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1527
1528
1529
  	FILE *fcfg;
  	void *image = NULL;
  	int version;
93e9371f0   Łukasz Majewski   fix: tools: kwbim...
1530
  	size_t headersz = 0;
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1531
  	uint32_t checksum;
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1532
  	int ret;
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1533
  	int size;
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
  	fcfg = fopen(params->imagename, "r");
  	if (!fcfg) {
  		fprintf(stderr, "Could not open input file %s
  ",
  			params->imagename);
  		exit(EXIT_FAILURE);
  	}
  
  	image_cfg = malloc(IMAGE_CFG_ELEMENT_MAX *
  			   sizeof(struct image_cfg_element));
  	if (!image_cfg) {
  		fprintf(stderr, "Cannot allocate memory
  ");
  		fclose(fcfg);
  		exit(EXIT_FAILURE);
  	}
  
  	memset(image_cfg, 0,
  	       IMAGE_CFG_ELEMENT_MAX * sizeof(struct image_cfg_element));
  	rewind(fcfg);
  
  	ret = image_create_config_parse(fcfg);
  	fclose(fcfg);
  	if (ret) {
  		free(image_cfg);
  		exit(EXIT_FAILURE);
  	}
9b163d8c4   Stefan Roese   kwbimage: Align p...
1561
1562
  	/* The MVEBU BootROM does not allow non word aligned payloads */
  	sbuf->st_size = ALIGN_SUP(sbuf->st_size, 4);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1563
  	version = image_get_version();
934a529f9   Stefan Roese   tools/kwbimage: F...
1564
1565
1566
1567
1568
1569
1570
  	switch (version) {
  		/*
  		 * Fallback to version 0 if no version is provided in the
  		 * cfg file
  		 */
  	case -1:
  	case 0:
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1571
  		image = image_create_v0(&headersz, params, sbuf->st_size);
934a529f9   Stefan Roese   tools/kwbimage: F...
1572
1573
1574
  		break;
  
  	case 1:
a1b6b0a9c   Mario Six   arm: mvebu: Imple...
1575
  		image = image_create_v1(&headersz, params, ptr, sbuf->st_size);
934a529f9   Stefan Roese   tools/kwbimage: F...
1576
1577
1578
1579
1580
1581
1582
1583
  		break;
  
  	default:
  		fprintf(stderr, "Unsupported version %d
  ", version);
  		free(image_cfg);
  		exit(EXIT_FAILURE);
  	}
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1584
1585
1586
1587
1588
1589
1590
1591
1592
  
  	if (!image) {
  		fprintf(stderr, "Could not create image
  ");
  		free(image_cfg);
  		exit(EXIT_FAILURE);
  	}
  
  	free(image_cfg);
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1593

4acd2d24b   Stefan Roese   tools: kwbimage: ...
1594
  	/* Build and add image checksum header */
a8840dced   Reinhard Pfau   tools/kwbimage: f...
1595
1596
  	checksum =
  		cpu_to_le32(image_checksum32((uint32_t *)ptr, sbuf->st_size));
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1597
  	size = write(ifd, &checksum, sizeof(uint32_t));
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1598
  	if (size != sizeof(uint32_t)) {
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1599
1600
  		fprintf(stderr, "Error:%s - Checksum write %d bytes %s
  ",
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1601
  			params->cmdname, size, params->imagefile);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1602
  		exit(EXIT_FAILURE);
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1603
1604
1605
  	}
  
  	sbuf->st_size += sizeof(uint32_t);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1606
1607
  	/* Finally copy the header into the image area */
  	memcpy(ptr, image, headersz);
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1608

4acd2d24b   Stefan Roese   tools: kwbimage: ...
1609
  	free(image);
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1610
  }
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1611
  static void kwbimage_print_header(const void *ptr)
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1612
  {
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1613
1614
1615
1616
1617
  	struct main_hdr_v0 *mhdr = (struct main_hdr_v0 *)ptr;
  
  	printf("Image Type:   MVEBU Boot from %s Image
  ",
  	       image_boot_mode_name(mhdr->blockid));
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1618
1619
  	printf("Image version:%d
  ", image_version((void *)ptr));
26f195c71   Gerald Kerma   ARM: kwimage: fix...
1620
  	printf("Data Size:    ");
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1621
1622
1623
1624
1625
  	genimg_print_size(mhdr->blocksize - sizeof(uint32_t));
  	printf("Load Address: %08x
  ", mhdr->destaddr);
  	printf("Entry Point:  %08x
  ", mhdr->execaddr);
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1626
  }
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1627
  static int kwbimage_check_image_types(uint8_t type)
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1628
1629
1630
  {
  	if (type == IH_TYPE_KWBIMAGE)
  		return EXIT_SUCCESS;
94490a4a7   Mario Six   tools: kwbimage: ...
1631
1632
  
  	return EXIT_FAILURE;
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1633
  }
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1634
1635
1636
  static int kwbimage_verify_header(unsigned char *ptr, int image_size,
  				  struct image_tool_params *params)
  {
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1637
  	uint8_t checksum;
6cd5678c4   Alexander Graf   kwbimage: Fix out...
1638
1639
1640
1641
  	size_t header_size = kwbimage_header_size(ptr);
  
  	if (header_size > image_size)
  		return -FDT_ERR_BADSTRUCTURE;
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1642

db7cd4ed3   Baruch Siach   tools/kwbimage: f...
1643
  	if (!main_hdr_checksum_ok(ptr))
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1644
1645
1646
1647
  		return -FDT_ERR_BADSTRUCTURE;
  
  	/* Only version 0 extended header has checksum */
  	if (image_version((void *)ptr) == 0) {
e89016c44   Mario Six   tools: kwbimage: ...
1648
  		struct ext_hdr_v0 *ext_hdr;
885fba155   Mario Six   tools: kwbimage: ...
1649
1650
  		ext_hdr = (struct ext_hdr_v0 *)
  				(ptr + sizeof(struct main_hdr_v0));
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1651
  		checksum = image_checksum8(ext_hdr,
26f195c71   Gerald Kerma   ARM: kwimage: fix...
1652
1653
  					   sizeof(struct ext_hdr_v0)
  					   - sizeof(uint8_t));
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
  		if (checksum != ext_hdr->checksum)
  			return -FDT_ERR_BADSTRUCTURE;
  	}
  
  	return 0;
  }
  
  static int kwbimage_generate(struct image_tool_params *params,
  			     struct image_type_params *tparams)
  {
6cbf7eda3   Patrick Wildt   arm: mvebu: kwbim...
1664
  	FILE *fcfg;
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1665
  	int alloc_len;
6cbf7eda3   Patrick Wildt   arm: mvebu: kwbim...
1666
  	int version;
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1667
  	void *hdr;
6cbf7eda3   Patrick Wildt   arm: mvebu: kwbim...
1668
  	int ret;
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1669

6cbf7eda3   Patrick Wildt   arm: mvebu: kwbim...
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
  	fcfg = fopen(params->imagename, "r");
  	if (!fcfg) {
  		fprintf(stderr, "Could not open input file %s
  ",
  			params->imagename);
  		exit(EXIT_FAILURE);
  	}
  
  	image_cfg = malloc(IMAGE_CFG_ELEMENT_MAX *
  			   sizeof(struct image_cfg_element));
  	if (!image_cfg) {
  		fprintf(stderr, "Cannot allocate memory
  ");
  		fclose(fcfg);
  		exit(EXIT_FAILURE);
  	}
  
  	memset(image_cfg, 0,
  	       IMAGE_CFG_ELEMENT_MAX * sizeof(struct image_cfg_element));
  	rewind(fcfg);
  
  	ret = image_create_config_parse(fcfg);
  	fclose(fcfg);
  	if (ret) {
  		free(image_cfg);
  		exit(EXIT_FAILURE);
  	}
  
  	version = image_get_version();
  	switch (version) {
  		/*
  		 * Fallback to version 0 if no version is provided in the
  		 * cfg file
  		 */
  	case -1:
  	case 0:
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1706
1707
  		alloc_len = sizeof(struct main_hdr_v0) +
  			sizeof(struct ext_hdr_v0);
6cbf7eda3   Patrick Wildt   arm: mvebu: kwbim...
1708
1709
1710
  		break;
  
  	case 1:
e93cf53f1   Mario Six   tools: kwbimage: ...
1711
  		alloc_len = image_headersz_v1(NULL);
6cbf7eda3   Patrick Wildt   arm: mvebu: kwbim...
1712
1713
1714
1715
1716
1717
1718
  		break;
  
  	default:
  		fprintf(stderr, "Unsupported version %d
  ", version);
  		free(image_cfg);
  		exit(EXIT_FAILURE);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1719
  	}
6cbf7eda3   Patrick Wildt   arm: mvebu: kwbim...
1720
  	free(image_cfg);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
  	hdr = malloc(alloc_len);
  	if (!hdr) {
  		fprintf(stderr, "%s: malloc return failure: %s
  ",
  			params->cmdname, strerror(errno));
  		exit(EXIT_FAILURE);
  	}
  
  	memset(hdr, 0, alloc_len);
  	tparams->header_size = alloc_len;
  	tparams->hdr = hdr;
777208593   Stefan Roese   tools/kwbimage.c:...
1732
1733
1734
1735
1736
1737
1738
1739
1740
  	/*
  	 * The resulting image needs to be 4-byte aligned. At least
  	 * the Marvell hdrparser tool complains if its unaligned.
  	 * By returning 1 here in this function, called via
  	 * tparams->vrec_header() in mkimage.c, mkimage will
  	 * automatically pad the the resulting image to a 4-byte
  	 * size if necessary.
  	 */
  	return 1;
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1741
1742
1743
1744
1745
1746
1747
1748
  }
  
  /*
   * Report Error if xflag is set in addition to default
   */
  static int kwbimage_check_params(struct image_tool_params *params)
  {
  	if (!strlen(params->imagename)) {
94490a4a7   Mario Six   tools: kwbimage: ...
1749
1750
1751
1752
  		char *msg = "Configuration file for kwbimage creation omitted";
  
  		fprintf(stderr, "Error:%s - %s
  ", params->cmdname, msg);
4acd2d24b   Stefan Roese   tools: kwbimage: ...
1753
1754
1755
1756
1757
1758
1759
1760
  		return CFG_INVALID;
  	}
  
  	return (params->dflag && (params->fflag || params->lflag)) ||
  		(params->fflag && (params->dflag || params->lflag)) ||
  		(params->lflag && (params->dflag || params->fflag)) ||
  		(params->xflag) || !(strlen(params->imagename));
  }
aa0c7a86c   Prafulla Wadaskar   mkimage: Add Kirk...
1761
1762
1763
  /*
   * kwbimage type parameters definition
   */
a93648d19   Guilherme Maciel Ferreira   imagetool: replac...
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
  U_BOOT_IMAGE_TYPE(
  	kwbimage,
  	"Marvell MVEBU Boot Image support",
  	0,
  	NULL,
  	kwbimage_check_params,
  	kwbimage_verify_header,
  	kwbimage_print_header,
  	kwbimage_set_header,
  	NULL,
  	kwbimage_check_image_types,
  	NULL,
  	kwbimage_generate
  );