]> git.ipfire.org Git - thirdparty/u-boot.git/blame - tools/kwbimage.c
tools: kwbimage: Simplify add_secure_header_v1()
[thirdparty/u-boot.git] / tools / kwbimage.c
CommitLineData
83d290c5 1// SPDX-License-Identifier: GPL-2.0+
aa0c7a86 2/*
4acd2d24 3 * Image manipulator for Marvell SoCs
8010f4ff
T
4 * supports Kirkwood, Dove, Armada 370, Armada XP, Armada 375, Armada 38x and
5 * Armada 39x
4acd2d24
SR
6 *
7 * (C) Copyright 2013 Thomas Petazzoni
8 * <thomas.petazzoni@free-electrons.com>
43558a02
T
9 *
10 * (C) Copyright 2022 Pali Rohár <pali@kernel.org>
aa0c7a86
PW
11 */
12
3a8b9199
HS
13#define OPENSSL_API_COMPAT 0x10101000L
14
f86ed6a8 15#include "imagetool.h"
e5f1a586 16#include <limits.h>
aa0c7a86 17#include <image.h>
a1b6b0a9 18#include <stdarg.h>
4acd2d24 19#include <stdint.h>
aa0c7a86
PW
20#include "kwbimage.h"
21
e15843b1 22#include <openssl/bn.h>
a1b6b0a9
MS
23#include <openssl/rsa.h>
24#include <openssl/pem.h>
25#include <openssl/err.h>
26#include <openssl/evp.h>
e15843b1 27
a2d5efd7
JG
28#if OPENSSL_VERSION_NUMBER < 0x10100000L || \
29 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL)
e15843b1
JW
30static void RSA_get0_key(const RSA *r,
31 const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
32{
33 if (n != NULL)
34 *n = r->n;
35 if (e != NULL)
36 *e = r->e;
37 if (d != NULL)
38 *d = r->d;
39}
40
a2d5efd7 41#elif !defined(LIBRESSL_VERSION_NUMBER)
e15843b1
JW
42void EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx)
43{
44 EVP_MD_CTX_reset(ctx);
45}
46#endif
a1b6b0a9 47
f76ae257
T
48/* fls - find last (most-significant) bit set in 4-bit integer */
49static inline int fls4(int num)
50{
51 if (num & 0x8)
52 return 4;
53 else if (num & 0x4)
54 return 3;
55 else if (num & 0x2)
56 return 2;
57 else if (num & 0x1)
58 return 1;
59 else
60 return 0;
61}
62
4acd2d24
SR
63static struct image_cfg_element *image_cfg;
64static int cfgn;
a1b6b0a9 65static int verbose_mode;
4acd2d24
SR
66
67struct boot_mode {
68 unsigned int id;
69 const char *name;
70};
71
a1b6b0a9
MS
72/*
73 * SHA2-256 hash
74 */
75struct hash_v1 {
76 uint8_t hash[32];
77};
78
4acd2d24 79struct boot_mode boot_modes[] = {
e515a330
T
80 { IBR_HDR_I2C_ID, "i2c" },
81 { IBR_HDR_SPI_ID, "spi" },
82 { IBR_HDR_NAND_ID, "nand" },
83 { IBR_HDR_SATA_ID, "sata" },
84 { IBR_HDR_PEX_ID, "pex" },
85 { IBR_HDR_UART_ID, "uart" },
86 { IBR_HDR_SDIO_ID, "sdio" },
4acd2d24 87 {},
aa0c7a86
PW
88};
89
4acd2d24
SR
90struct nand_ecc_mode {
91 unsigned int id;
92 const char *name;
93};
94
95struct nand_ecc_mode nand_ecc_modes[] = {
e515a330
T
96 { IBR_HDR_ECC_DEFAULT, "default" },
97 { IBR_HDR_ECC_FORCED_HAMMING, "hamming" },
98 { IBR_HDR_ECC_FORCED_RS, "rs" },
99 { IBR_HDR_ECC_DISABLED, "disabled" },
4acd2d24
SR
100 {},
101};
102
103/* Used to identify an undefined execution or destination address */
104#define ADDR_INVALID ((uint32_t)-1)
105
6c7f152e 106#define BINARY_MAX_ARGS 255
4acd2d24
SR
107
108/* In-memory representation of a line of the configuration file */
4991b4f7
MS
109
110enum image_cfg_type {
111 IMAGE_CFG_VERSION = 0x1,
112 IMAGE_CFG_BOOT_FROM,
113 IMAGE_CFG_DEST_ADDR,
114 IMAGE_CFG_EXEC_ADDR,
115 IMAGE_CFG_NAND_BLKSZ,
116 IMAGE_CFG_NAND_BADBLK_LOCATION,
117 IMAGE_CFG_NAND_ECC_MODE,
118 IMAGE_CFG_NAND_PAGESZ,
af49605b 119 IMAGE_CFG_CPU,
4991b4f7 120 IMAGE_CFG_BINARY,
4991b4f7 121 IMAGE_CFG_DATA,
f63c583f 122 IMAGE_CFG_DATA_DELAY,
4991b4f7 123 IMAGE_CFG_BAUDRATE,
12f2c03f
T
124 IMAGE_CFG_UART_PORT,
125 IMAGE_CFG_UART_MPP,
4991b4f7 126 IMAGE_CFG_DEBUG,
a1b6b0a9
MS
127 IMAGE_CFG_KAK,
128 IMAGE_CFG_CSK,
129 IMAGE_CFG_CSK_INDEX,
130 IMAGE_CFG_JTAG_DELAY,
131 IMAGE_CFG_BOX_ID,
132 IMAGE_CFG_FLASH_ID,
133 IMAGE_CFG_SEC_COMMON_IMG,
134 IMAGE_CFG_SEC_SPECIALIZED_IMG,
135 IMAGE_CFG_SEC_BOOT_DEV,
136 IMAGE_CFG_SEC_FUSE_DUMP,
4991b4f7
MS
137
138 IMAGE_CFG_COUNT
139} type;
140
141static const char * const id_strs[] = {
142 [IMAGE_CFG_VERSION] = "VERSION",
143 [IMAGE_CFG_BOOT_FROM] = "BOOT_FROM",
144 [IMAGE_CFG_DEST_ADDR] = "DEST_ADDR",
145 [IMAGE_CFG_EXEC_ADDR] = "EXEC_ADDR",
146 [IMAGE_CFG_NAND_BLKSZ] = "NAND_BLKSZ",
147 [IMAGE_CFG_NAND_BADBLK_LOCATION] = "NAND_BADBLK_LOCATION",
148 [IMAGE_CFG_NAND_ECC_MODE] = "NAND_ECC_MODE",
149 [IMAGE_CFG_NAND_PAGESZ] = "NAND_PAGE_SIZE",
af49605b 150 [IMAGE_CFG_CPU] = "CPU",
4991b4f7 151 [IMAGE_CFG_BINARY] = "BINARY",
4991b4f7 152 [IMAGE_CFG_DATA] = "DATA",
f63c583f 153 [IMAGE_CFG_DATA_DELAY] = "DATA_DELAY",
4991b4f7 154 [IMAGE_CFG_BAUDRATE] = "BAUDRATE",
12f2c03f
T
155 [IMAGE_CFG_UART_PORT] = "UART_PORT",
156 [IMAGE_CFG_UART_MPP] = "UART_MPP",
4991b4f7 157 [IMAGE_CFG_DEBUG] = "DEBUG",
a1b6b0a9
MS
158 [IMAGE_CFG_KAK] = "KAK",
159 [IMAGE_CFG_CSK] = "CSK",
160 [IMAGE_CFG_CSK_INDEX] = "CSK_INDEX",
161 [IMAGE_CFG_JTAG_DELAY] = "JTAG_DELAY",
162 [IMAGE_CFG_BOX_ID] = "BOX_ID",
163 [IMAGE_CFG_FLASH_ID] = "FLASH_ID",
164 [IMAGE_CFG_SEC_COMMON_IMG] = "SEC_COMMON_IMG",
165 [IMAGE_CFG_SEC_SPECIALIZED_IMG] = "SEC_SPECIALIZED_IMG",
166 [IMAGE_CFG_SEC_BOOT_DEV] = "SEC_BOOT_DEV",
167 [IMAGE_CFG_SEC_FUSE_DUMP] = "SEC_FUSE_DUMP"
4991b4f7
MS
168};
169
4acd2d24 170struct image_cfg_element {
4991b4f7 171 enum image_cfg_type type;
4acd2d24
SR
172 union {
173 unsigned int version;
af49605b 174 unsigned int cpu_sheeva;
4acd2d24
SR
175 unsigned int bootfrom;
176 struct {
177 const char *file;
0aca27ea 178 unsigned int loadaddr;
4acd2d24
SR
179 unsigned int args[BINARY_MAX_ARGS];
180 unsigned int nargs;
181 } binary;
4acd2d24
SR
182 unsigned int dstaddr;
183 unsigned int execaddr;
184 unsigned int nandblksz;
185 unsigned int nandbadblklocation;
186 unsigned int nandeccmode;
187 unsigned int nandpagesz;
188 struct ext_hdr_v0_reg regdata;
f63c583f 189 unsigned int regdata_delay;
4bdb5479 190 unsigned int baudrate;
12f2c03f
T
191 unsigned int uart_port;
192 unsigned int uart_mpp;
2611c05e 193 unsigned int debug;
a1b6b0a9
MS
194 const char *key_name;
195 int csk_idx;
196 uint8_t jtag_delay;
197 uint32_t boxid;
198 uint32_t flashid;
199 bool sec_specialized_img;
200 unsigned int sec_boot_dev;
201 const char *name;
4acd2d24
SR
202 };
203};
204
205#define IMAGE_CFG_ELEMENT_MAX 256
aa0c7a86 206
4acd2d24
SR
207/*
208 * Utility functions to manipulate boot mode and ecc modes (convert
209 * them back and forth between description strings and the
210 * corresponding numerical identifiers).
211 */
212
213static const char *image_boot_mode_name(unsigned int id)
214{
215 int i;
94490a4a 216
4acd2d24
SR
217 for (i = 0; boot_modes[i].name; i++)
218 if (boot_modes[i].id == id)
219 return boot_modes[i].name;
220 return NULL;
221}
222
6eb20bbf 223static int image_boot_mode_id(const char *boot_mode_name)
4acd2d24
SR
224{
225 int i;
94490a4a 226
4acd2d24
SR
227 for (i = 0; boot_modes[i].name; i++)
228 if (!strcmp(boot_modes[i].name, boot_mode_name))
229 return boot_modes[i].id;
230
231 return -1;
232}
233
1a8e6b63
T
234static const char *image_nand_ecc_mode_name(unsigned int id)
235{
236 int i;
237
238 for (i = 0; nand_ecc_modes[i].name; i++)
239 if (nand_ecc_modes[i].id == id)
240 return nand_ecc_modes[i].name;
241
242 return NULL;
243}
244
6eb20bbf 245static int image_nand_ecc_mode_id(const char *nand_ecc_mode_name)
4acd2d24
SR
246{
247 int i;
94490a4a 248
4acd2d24
SR
249 for (i = 0; nand_ecc_modes[i].name; i++)
250 if (!strcmp(nand_ecc_modes[i].name, nand_ecc_mode_name))
251 return nand_ecc_modes[i].id;
252 return -1;
aa0c7a86
PW
253}
254
4acd2d24
SR
255static struct image_cfg_element *
256image_find_option(unsigned int optiontype)
aa0c7a86 257{
4acd2d24 258 int i;
aa0c7a86 259
4acd2d24
SR
260 for (i = 0; i < cfgn; i++) {
261 if (image_cfg[i].type == optiontype)
262 return &image_cfg[i];
aa0c7a86 263 }
4acd2d24
SR
264
265 return NULL;
266}
267
268static unsigned int
269image_count_options(unsigned int optiontype)
270{
271 int i;
272 unsigned int count = 0;
273
274 for (i = 0; i < cfgn; i++)
275 if (image_cfg[i].type == optiontype)
276 count++;
277
278 return count;
aa0c7a86
PW
279}
280
a1b6b0a9
MS
281static int image_get_csk_index(void)
282{
283 struct image_cfg_element *e;
284
285 e = image_find_option(IMAGE_CFG_CSK_INDEX);
286 if (!e)
287 return -1;
288
289 return e->csk_idx;
290}
291
292static bool image_get_spezialized_img(void)
293{
294 struct image_cfg_element *e;
295
296 e = image_find_option(IMAGE_CFG_SEC_SPECIALIZED_IMG);
297 if (!e)
298 return false;
299
300 return e->sec_specialized_img;
301}
302
d1547b36
T
303static int image_get_bootfrom(void)
304{
305 struct image_cfg_element *e;
306
307 e = image_find_option(IMAGE_CFG_BOOT_FROM);
308 if (!e)
309 /* fallback to SPI if no BOOT_FROM is not provided */
310 return IBR_HDR_SPI_ID;
311
312 return e->bootfrom;
313}
314
af49605b
T
315static int image_is_cpu_sheeva(void)
316{
317 struct image_cfg_element *e;
318
319 e = image_find_option(IMAGE_CFG_CPU);
320 if (!e)
321 return 0;
322
323 return e->cpu_sheeva;
324}
325
aa0c7a86 326/*
4acd2d24
SR
327 * Compute a 8-bit checksum of a memory area. This algorithm follows
328 * the requirements of the Marvell SoC BootROM specifications.
aa0c7a86 329 */
4acd2d24 330static uint8_t image_checksum8(void *start, uint32_t len)
aa0c7a86 331{
4acd2d24
SR
332 uint8_t csum = 0;
333 uint8_t *p = start;
aa0c7a86
PW
334
335 /* check len and return zero checksum if invalid */
336 if (!len)
337 return 0;
338
339 do {
4acd2d24 340 csum += *p;
aa0c7a86
PW
341 p++;
342 } while (--len);
4acd2d24
SR
343
344 return csum;
aa0c7a86
PW
345}
346
db7cd4ed
BS
347/*
348 * Verify checksum over a complete header that includes the checksum field.
349 * Return 1 when OK, otherwise 0.
350 */
351static int main_hdr_checksum_ok(void *hdr)
352{
353 /* Offsets of checksum in v0 and v1 headers are the same */
354 struct main_hdr_v0 *main_hdr = (struct main_hdr_v0 *)hdr;
355 uint8_t checksum;
356
fe2fd73d 357 checksum = image_checksum8(hdr, kwbheader_size_for_csum(hdr));
db7cd4ed
BS
358 /* Calculated checksum includes the header checksum field. Compensate
359 * for that.
360 */
361 checksum -= main_hdr->checksum;
362
363 return checksum == main_hdr->checksum;
364}
365
4acd2d24 366static uint32_t image_checksum32(void *start, uint32_t len)
aa0c7a86 367{
4acd2d24
SR
368 uint32_t csum = 0;
369 uint32_t *p = start;
aa0c7a86
PW
370
371 /* check len and return zero checksum if invalid */
372 if (!len)
373 return 0;
374
375 if (len % sizeof(uint32_t)) {
4acd2d24
SR
376 fprintf(stderr, "Length %d is not in multiple of %zu\n",
377 len, sizeof(uint32_t));
aa0c7a86
PW
378 return 0;
379 }
380
381 do {
4acd2d24 382 csum += *p;
aa0c7a86
PW
383 p++;
384 len -= sizeof(uint32_t);
385 } while (len > 0);
4acd2d24
SR
386
387 return csum;
aa0c7a86
PW
388}
389
1a8e6b63
T
390static unsigned int options_to_baudrate(uint8_t options)
391{
392 switch (options & 0x7) {
393 case MAIN_HDR_V1_OPT_BAUD_2400:
394 return 2400;
395 case MAIN_HDR_V1_OPT_BAUD_4800:
396 return 4800;
397 case MAIN_HDR_V1_OPT_BAUD_9600:
398 return 9600;
399 case MAIN_HDR_V1_OPT_BAUD_19200:
400 return 19200;
401 case MAIN_HDR_V1_OPT_BAUD_38400:
402 return 38400;
403 case MAIN_HDR_V1_OPT_BAUD_57600:
404 return 57600;
405 case MAIN_HDR_V1_OPT_BAUD_115200:
406 return 115200;
407 case MAIN_HDR_V1_OPT_BAUD_DEFAULT:
408 default:
409 return 0;
410 }
411}
412
4bdb5479
CP
413static uint8_t baudrate_to_option(unsigned int baudrate)
414{
415 switch (baudrate) {
416 case 2400:
417 return MAIN_HDR_V1_OPT_BAUD_2400;
418 case 4800:
419 return MAIN_HDR_V1_OPT_BAUD_4800;
420 case 9600:
421 return MAIN_HDR_V1_OPT_BAUD_9600;
422 case 19200:
423 return MAIN_HDR_V1_OPT_BAUD_19200;
424 case 38400:
425 return MAIN_HDR_V1_OPT_BAUD_38400;
426 case 57600:
427 return MAIN_HDR_V1_OPT_BAUD_57600;
428 case 115200:
429 return MAIN_HDR_V1_OPT_BAUD_115200;
430 default:
431 return MAIN_HDR_V1_OPT_BAUD_DEFAULT;
432 }
433}
434
a1b6b0a9
MS
435static void kwb_msg(const char *fmt, ...)
436{
437 if (verbose_mode) {
438 va_list ap;
439
440 va_start(ap, fmt);
441 vfprintf(stdout, fmt, ap);
442 va_end(ap);
443 }
444}
445
446static int openssl_err(const char *msg)
447{
448 unsigned long ssl_err = ERR_get_error();
449
450 fprintf(stderr, "%s", msg);
451 fprintf(stderr, ": %s\n",
452 ERR_error_string(ssl_err, 0));
453
454 return -1;
455}
456
457static int kwb_load_rsa_key(const char *keydir, const char *name, RSA **p_rsa)
458{
459 char path[PATH_MAX];
460 RSA *rsa;
461 FILE *f;
462
463 if (!keydir)
464 keydir = ".";
465
466 snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
467 f = fopen(path, "r");
468 if (!f) {
469 fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
470 path, strerror(errno));
471 return -ENOENT;
472 }
473
474 rsa = PEM_read_RSAPrivateKey(f, 0, NULL, "");
475 if (!rsa) {
476 openssl_err("Failure reading private key");
477 fclose(f);
478 return -EPROTO;
479 }
480 fclose(f);
481 *p_rsa = rsa;
482
483 return 0;
484}
485
486static int kwb_load_cfg_key(struct image_tool_params *params,
487 unsigned int cfg_option, const char *key_name,
488 RSA **p_key)
489{
490 struct image_cfg_element *e_key;
491 RSA *key;
492 int res;
493
494 *p_key = NULL;
495
496 e_key = image_find_option(cfg_option);
497 if (!e_key) {
498 fprintf(stderr, "%s not configured\n", key_name);
499 return -ENOENT;
500 }
501
502 res = kwb_load_rsa_key(params->keydir, e_key->key_name, &key);
503 if (res < 0) {
504 fprintf(stderr, "Failed to load %s\n", key_name);
505 return -ENOENT;
506 }
507
508 *p_key = key;
509
510 return 0;
511}
512
513static int kwb_load_kak(struct image_tool_params *params, RSA **p_kak)
514{
515 return kwb_load_cfg_key(params, IMAGE_CFG_KAK, "KAK", p_kak);
516}
517
518static int kwb_load_csk(struct image_tool_params *params, RSA **p_csk)
519{
520 return kwb_load_cfg_key(params, IMAGE_CFG_CSK, "CSK", p_csk);
521}
522
523static int kwb_compute_pubkey_hash(struct pubkey_der_v1 *pk,
524 struct hash_v1 *hash)
525{
526 EVP_MD_CTX *ctx;
527 unsigned int key_size;
528 unsigned int hash_size;
529 int ret = 0;
530
531 if (!pk || !hash || pk->key[0] != 0x30 || pk->key[1] != 0x82)
532 return -EINVAL;
533
534 key_size = (pk->key[2] << 8) + pk->key[3] + 4;
535
536 ctx = EVP_MD_CTX_create();
537 if (!ctx)
538 return openssl_err("EVP context creation failed");
539
540 EVP_MD_CTX_init(ctx);
541 if (!EVP_DigestInit(ctx, EVP_sha256())) {
542 ret = openssl_err("Digest setup failed");
543 goto hash_err_ctx;
544 }
545
546 if (!EVP_DigestUpdate(ctx, pk->key, key_size)) {
547 ret = openssl_err("Hashing data failed");
548 goto hash_err_ctx;
549 }
550
551 if (!EVP_DigestFinal(ctx, hash->hash, &hash_size)) {
552 ret = openssl_err("Could not obtain hash");
553 goto hash_err_ctx;
554 }
555
556 EVP_MD_CTX_cleanup(ctx);
557
558hash_err_ctx:
559 EVP_MD_CTX_destroy(ctx);
560 return ret;
561}
562
563static int kwb_import_pubkey(RSA **key, struct pubkey_der_v1 *src, char *keyname)
564{
565 RSA *rsa;
566 const unsigned char *ptr;
567
568 if (!key || !src)
569 goto fail;
570
571 ptr = src->key;
572 rsa = d2i_RSAPublicKey(key, &ptr, sizeof(src->key));
573 if (!rsa) {
574 openssl_err("error decoding public key");
575 goto fail;
576 }
577
578 return 0;
579fail:
580 fprintf(stderr, "Failed to decode %s pubkey\n", keyname);
581 return -EINVAL;
582}
583
584static int kwb_export_pubkey(RSA *key, struct pubkey_der_v1 *dst, FILE *hashf,
585 char *keyname)
586{
587 int size_exp, size_mod, size_seq;
e15843b1 588 const BIGNUM *key_e, *key_n;
a1b6b0a9
MS
589 uint8_t *cur;
590 char *errmsg = "Failed to encode %s\n";
591
e15843b1
JW
592 RSA_get0_key(key, NULL, &key_e, NULL);
593 RSA_get0_key(key, &key_n, NULL, NULL);
594
595 if (!key || !key_e || !key_n || !dst) {
a1b6b0a9 596 fprintf(stderr, "export pk failed: (%p, %p, %p, %p)",
e15843b1 597 key, key_e, key_n, dst);
a1b6b0a9
MS
598 fprintf(stderr, errmsg, keyname);
599 return -EINVAL;
600 }
601
602 /*
603 * According to the specs, the key should be PKCS#1 DER encoded.
604 * But unfortunately the really required encoding seems to be different;
605 * it violates DER...! (But it still conformes to BER.)
606 * (Length always in long form w/ 2 byte length code; no leading zero
607 * when MSB of first byte is set...)
608 * So we cannot use the encoding func provided by OpenSSL and have to
609 * do the encoding manually.
610 */
611
e15843b1
JW
612 size_exp = BN_num_bytes(key_e);
613 size_mod = BN_num_bytes(key_n);
a1b6b0a9
MS
614 size_seq = 4 + size_mod + 4 + size_exp;
615
616 if (size_mod > 256) {
617 fprintf(stderr, "export pk failed: wrong mod size: %d\n",
618 size_mod);
619 fprintf(stderr, errmsg, keyname);
620 return -EINVAL;
621 }
622
623 if (4 + size_seq > sizeof(dst->key)) {
3b5da64e 624 fprintf(stderr, "export pk failed: seq too large (%d, %zu)\n",
a1b6b0a9
MS
625 4 + size_seq, sizeof(dst->key));
626 fprintf(stderr, errmsg, keyname);
627 return -ENOBUFS;
628 }
629
630 cur = dst->key;
631
632 /* PKCS#1 (RFC3447) RSAPublicKey structure */
633 *cur++ = 0x30; /* SEQUENCE */
634 *cur++ = 0x82;
635 *cur++ = (size_seq >> 8) & 0xFF;
636 *cur++ = size_seq & 0xFF;
637 /* Modulus */
638 *cur++ = 0x02; /* INTEGER */
639 *cur++ = 0x82;
640 *cur++ = (size_mod >> 8) & 0xFF;
641 *cur++ = size_mod & 0xFF;
e15843b1 642 BN_bn2bin(key_n, cur);
a1b6b0a9
MS
643 cur += size_mod;
644 /* Exponent */
645 *cur++ = 0x02; /* INTEGER */
646 *cur++ = 0x82;
647 *cur++ = (size_exp >> 8) & 0xFF;
648 *cur++ = size_exp & 0xFF;
e15843b1 649 BN_bn2bin(key_e, cur);
a1b6b0a9
MS
650
651 if (hashf) {
652 struct hash_v1 pk_hash;
653 int i;
654 int ret = 0;
655
656 ret = kwb_compute_pubkey_hash(dst, &pk_hash);
657 if (ret < 0) {
658 fprintf(stderr, errmsg, keyname);
659 return ret;
660 }
661
662 fprintf(hashf, "SHA256 = ");
663 for (i = 0 ; i < sizeof(pk_hash.hash); ++i)
664 fprintf(hashf, "%02X", pk_hash.hash[i]);
665 fprintf(hashf, "\n");
666 }
667
668 return 0;
669}
670
6eb20bbf
T
671static int kwb_sign(RSA *key, void *data, int datasz, struct sig_v1 *sig,
672 char *signame)
a1b6b0a9
MS
673{
674 EVP_PKEY *evp_key;
675 EVP_MD_CTX *ctx;
676 unsigned int sig_size;
677 int size;
678 int ret = 0;
679
680 evp_key = EVP_PKEY_new();
681 if (!evp_key)
682 return openssl_err("EVP_PKEY object creation failed");
683
684 if (!EVP_PKEY_set1_RSA(evp_key, key)) {
685 ret = openssl_err("EVP key setup failed");
686 goto err_key;
687 }
688
689 size = EVP_PKEY_size(evp_key);
690 if (size > sizeof(sig->sig)) {
691 fprintf(stderr, "Buffer to small for signature (%d bytes)\n",
692 size);
693 ret = -ENOBUFS;
694 goto err_key;
695 }
696
697 ctx = EVP_MD_CTX_create();
698 if (!ctx) {
699 ret = openssl_err("EVP context creation failed");
700 goto err_key;
701 }
702 EVP_MD_CTX_init(ctx);
703 if (!EVP_SignInit(ctx, EVP_sha256())) {
704 ret = openssl_err("Signer setup failed");
705 goto err_ctx;
706 }
707
708 if (!EVP_SignUpdate(ctx, data, datasz)) {
709 ret = openssl_err("Signing data failed");
710 goto err_ctx;
711 }
712
713 if (!EVP_SignFinal(ctx, sig->sig, &sig_size, evp_key)) {
714 ret = openssl_err("Could not obtain signature");
715 goto err_ctx;
716 }
717
718 EVP_MD_CTX_cleanup(ctx);
719 EVP_MD_CTX_destroy(ctx);
720 EVP_PKEY_free(evp_key);
721
722 return 0;
723
724err_ctx:
725 EVP_MD_CTX_destroy(ctx);
726err_key:
727 EVP_PKEY_free(evp_key);
728 fprintf(stderr, "Failed to create %s signature\n", signame);
729 return ret;
730}
731
6eb20bbf
T
732static int kwb_verify(RSA *key, void *data, int datasz, struct sig_v1 *sig,
733 char *signame)
a1b6b0a9
MS
734{
735 EVP_PKEY *evp_key;
736 EVP_MD_CTX *ctx;
737 int size;
738 int ret = 0;
739
740 evp_key = EVP_PKEY_new();
741 if (!evp_key)
742 return openssl_err("EVP_PKEY object creation failed");
743
744 if (!EVP_PKEY_set1_RSA(evp_key, key)) {
745 ret = openssl_err("EVP key setup failed");
746 goto err_key;
747 }
748
749 size = EVP_PKEY_size(evp_key);
750 if (size > sizeof(sig->sig)) {
751 fprintf(stderr, "Invalid signature size (%d bytes)\n",
752 size);
753 ret = -EINVAL;
754 goto err_key;
755 }
756
757 ctx = EVP_MD_CTX_create();
758 if (!ctx) {
759 ret = openssl_err("EVP context creation failed");
760 goto err_key;
761 }
762 EVP_MD_CTX_init(ctx);
763 if (!EVP_VerifyInit(ctx, EVP_sha256())) {
764 ret = openssl_err("Verifier setup failed");
765 goto err_ctx;
766 }
767
768 if (!EVP_VerifyUpdate(ctx, data, datasz)) {
769 ret = openssl_err("Hashing data failed");
770 goto err_ctx;
771 }
772
22515123 773 if (EVP_VerifyFinal(ctx, sig->sig, sizeof(sig->sig), evp_key) != 1) {
a1b6b0a9
MS
774 ret = openssl_err("Could not verify signature");
775 goto err_ctx;
776 }
777
778 EVP_MD_CTX_cleanup(ctx);
779 EVP_MD_CTX_destroy(ctx);
780 EVP_PKEY_free(evp_key);
781
782 return 0;
783
784err_ctx:
785 EVP_MD_CTX_destroy(ctx);
786err_key:
787 EVP_PKEY_free(evp_key);
788 fprintf(stderr, "Failed to verify %s signature\n", signame);
789 return ret;
790}
791
6eb20bbf
T
792static int kwb_sign_and_verify(RSA *key, void *data, int datasz,
793 struct sig_v1 *sig, char *signame)
a1b6b0a9
MS
794{
795 if (kwb_sign(key, data, datasz, sig, signame) < 0)
796 return -1;
797
798 if (kwb_verify(key, data, datasz, sig, signame) < 0)
799 return -1;
800
801 return 0;
802}
803
804
6eb20bbf 805static int kwb_dump_fuse_cmds_38x(FILE *out, struct secure_hdr_v1 *sec_hdr)
a1b6b0a9
MS
806{
807 struct hash_v1 kak_pub_hash;
808 struct image_cfg_element *e;
809 unsigned int fuse_line;
810 int i, idx;
811 uint8_t *ptr;
812 uint32_t val;
813 int ret = 0;
814
815 if (!out || !sec_hdr)
816 return -EINVAL;
817
818 ret = kwb_compute_pubkey_hash(&sec_hdr->kak, &kak_pub_hash);
819 if (ret < 0)
820 goto done;
821
822 fprintf(out, "# burn KAK pub key hash\n");
823 ptr = kak_pub_hash.hash;
824 for (fuse_line = 26; fuse_line <= 30; ++fuse_line) {
825 fprintf(out, "fuse prog -y %u 0 ", fuse_line);
826
827 for (i = 4; i-- > 0;)
828 fprintf(out, "%02hx", (ushort)ptr[i]);
829 ptr += 4;
830 fprintf(out, " 00");
831
832 if (fuse_line < 30) {
833 for (i = 3; i-- > 0;)
834 fprintf(out, "%02hx", (ushort)ptr[i]);
835 ptr += 3;
836 } else {
837 fprintf(out, "000000");
838 }
839
840 fprintf(out, " 1\n");
841 }
842
843 fprintf(out, "# burn CSK selection\n");
844
845 idx = image_get_csk_index();
846 if (idx < 0 || idx > 15) {
847 ret = -EINVAL;
848 goto done;
849 }
850 if (idx > 0) {
851 for (fuse_line = 31; fuse_line < 31 + idx; ++fuse_line)
852 fprintf(out, "fuse prog -y %u 0 00000001 00000000 1\n",
853 fuse_line);
854 } else {
855 fprintf(out, "# CSK index is 0; no mods needed\n");
856 }
857
858 e = image_find_option(IMAGE_CFG_BOX_ID);
859 if (e) {
860 fprintf(out, "# set box ID\n");
861 fprintf(out, "fuse prog -y 48 0 %08x 00000000 1\n", e->boxid);
862 }
863
864 e = image_find_option(IMAGE_CFG_FLASH_ID);
865 if (e) {
866 fprintf(out, "# set flash ID\n");
867 fprintf(out, "fuse prog -y 47 0 %08x 00000000 1\n", e->flashid);
868 }
869
870 fprintf(out, "# enable secure mode ");
871 fprintf(out, "(must be the last fuse line written)\n");
872
873 val = 1;
874 e = image_find_option(IMAGE_CFG_SEC_BOOT_DEV);
875 if (!e) {
876 fprintf(stderr, "ERROR: secured mode boot device not given\n");
877 ret = -EINVAL;
878 goto done;
879 }
880
881 if (e->sec_boot_dev > 0xff) {
882 fprintf(stderr, "ERROR: secured mode boot device invalid\n");
883 ret = -EINVAL;
884 goto done;
885 }
886
887 val |= (e->sec_boot_dev << 8);
888
889 fprintf(out, "fuse prog -y 24 0 %08x 0103e0a9 1\n", val);
890
891 fprintf(out, "# lock (unused) fuse lines (0-23)s\n");
892 for (fuse_line = 0; fuse_line < 24; ++fuse_line)
893 fprintf(out, "fuse prog -y %u 2 1\n", fuse_line);
894
895 fprintf(out, "# OK, that's all :-)\n");
896
897done:
898 return ret;
899}
900
901static int kwb_dump_fuse_cmds(struct secure_hdr_v1 *sec_hdr)
902{
903 int ret = 0;
904 struct image_cfg_element *e;
905
906 e = image_find_option(IMAGE_CFG_SEC_FUSE_DUMP);
907 if (!e)
908 return 0;
909
910 if (!strcmp(e->name, "a38x")) {
911 FILE *out = fopen("kwb_fuses_a38x.txt", "w+");
912
f858bb2e
HS
913 if (!out) {
914 fprintf(stderr, "Couldn't open eFuse settings: '%s': %s\n",
915 "kwb_fuses_a38x.txt", strerror(errno));
916 return -ENOENT;
917 }
918
a1b6b0a9
MS
919 kwb_dump_fuse_cmds_38x(out, sec_hdr);
920 fclose(out);
921 goto done;
922 }
923
924 ret = -ENOSYS;
925
926done:
927 return ret;
928}
929
5cad2e6c
T
930static size_t image_headersz_align(size_t headersz, uint8_t blockid)
931{
932 /*
933 * Header needs to be 4-byte aligned, which is already ensured by code
934 * above. Moreover UART images must have header aligned to 128 bytes
935 * (xmodem block size), NAND images to 256 bytes (ECC calculation),
936 * and SATA and SDIO images to 512 bytes (storage block size).
937 * Note that SPI images do not have to have header size aligned
938 * to 256 bytes because it is possible to read from SPI storage from
939 * any offset (read offset does not have to be aligned to block size).
940 */
941 if (blockid == IBR_HDR_UART_ID)
942 return ALIGN(headersz, 128);
943 else if (blockid == IBR_HDR_NAND_ID)
944 return ALIGN(headersz, 256);
945 else if (blockid == IBR_HDR_SATA_ID || blockid == IBR_HDR_SDIO_ID)
946 return ALIGN(headersz, 512);
947 else
948 return headersz;
949}
950
851114be
T
951static size_t image_headersz_v0(int *hasext)
952{
953 size_t headersz;
954
955 headersz = sizeof(struct main_hdr_v0);
956 if (image_count_options(IMAGE_CFG_DATA) > 0) {
957 headersz += sizeof(struct ext_hdr_v0);
958 if (hasext)
959 *hasext = 1;
960 }
961
962 return image_headersz_align(headersz, image_get_bootfrom());
963}
964
4acd2d24
SR
965static void *image_create_v0(size_t *imagesz, struct image_tool_params *params,
966 int payloadsz)
aa0c7a86 967{
4acd2d24
SR
968 struct image_cfg_element *e;
969 size_t headersz;
970 struct main_hdr_v0 *main_hdr;
885fba15 971 uint8_t *image;
4acd2d24
SR
972 int has_ext = 0;
973
974 /*
975 * Calculate the size of the header and the size of the
976 * payload
977 */
851114be 978 headersz = image_headersz_v0(&has_ext);
4acd2d24 979
4acd2d24
SR
980 image = malloc(headersz);
981 if (!image) {
982 fprintf(stderr, "Cannot allocate memory for image\n");
983 return NULL;
aa0c7a86 984 }
aa0c7a86 985
4acd2d24
SR
986 memset(image, 0, headersz);
987
885fba15 988 main_hdr = (struct main_hdr_v0 *)image;
4acd2d24
SR
989
990 /* Fill in the main header */
a8840dce 991 main_hdr->blocksize =
e23ad5d5 992 cpu_to_le32(payloadsz);
a8840dce 993 main_hdr->srcaddr = cpu_to_le32(headersz);
4acd2d24 994 main_hdr->ext = has_ext;
01bdac6d 995 main_hdr->version = 0;
a8840dce
RP
996 main_hdr->destaddr = cpu_to_le32(params->addr);
997 main_hdr->execaddr = cpu_to_le32(params->ep);
d1547b36 998 main_hdr->blockid = image_get_bootfrom();
4acd2d24 999
4acd2d24
SR
1000 e = image_find_option(IMAGE_CFG_NAND_ECC_MODE);
1001 if (e)
1002 main_hdr->nandeccmode = e->nandeccmode;
a6661a0e
T
1003 e = image_find_option(IMAGE_CFG_NAND_BLKSZ);
1004 if (e)
1005 main_hdr->nandblocksize = e->nandblksz / (64 * 1024);
4acd2d24
SR
1006 e = image_find_option(IMAGE_CFG_NAND_PAGESZ);
1007 if (e)
a8840dce 1008 main_hdr->nandpagesize = cpu_to_le16(e->nandpagesz);
a6661a0e
T
1009 e = image_find_option(IMAGE_CFG_NAND_BADBLK_LOCATION);
1010 if (e)
1011 main_hdr->nandbadblklocation = e->nandbadblklocation;
4acd2d24 1012
5c61710c 1013 /*
954c94aa 1014 * For SATA srcaddr is specified in number of sectors.
5c61710c
T
1015 * This expects the sector size to be 512 bytes.
1016 * Header size is already aligned.
1017 */
1018 if (main_hdr->blockid == IBR_HDR_SATA_ID)
954c94aa 1019 main_hdr->srcaddr = cpu_to_le32(headersz / 512);
5c61710c 1020
5c61710c
T
1021 /* For PCIe srcaddr is not used and must be set to 0xFFFFFFFF. */
1022 if (main_hdr->blockid == IBR_HDR_PEX_ID)
1023 main_hdr->srcaddr = cpu_to_le32(0xFFFFFFFF);
1024
4acd2d24
SR
1025 /* Generate the ext header */
1026 if (has_ext) {
e89016c4 1027 struct ext_hdr_v0 *ext_hdr;
4acd2d24
SR
1028 int cfgi, datai;
1029
885fba15
MS
1030 ext_hdr = (struct ext_hdr_v0 *)
1031 (image + sizeof(struct main_hdr_v0));
a8840dce 1032 ext_hdr->offset = cpu_to_le32(0x40);
4acd2d24
SR
1033
1034 for (cfgi = 0, datai = 0; cfgi < cfgn; cfgi++) {
1035 e = &image_cfg[cfgi];
1036 if (e->type != IMAGE_CFG_DATA)
1037 continue;
1038
a8840dce
RP
1039 ext_hdr->rcfg[datai].raddr =
1040 cpu_to_le32(e->regdata.raddr);
1041 ext_hdr->rcfg[datai].rdata =
1042 cpu_to_le32(e->regdata.rdata);
4acd2d24
SR
1043 datai++;
1044 }
1045
1046 ext_hdr->checksum = image_checksum8(ext_hdr,
1047 sizeof(struct ext_hdr_v0));
1048 }
1049
ee3da92d
T
1050 main_hdr->checksum = image_checksum8(image,
1051 sizeof(struct main_hdr_v0));
1052
4acd2d24
SR
1053 *imagesz = headersz;
1054 return image;
aa0c7a86
PW
1055}
1056
e93cf53f 1057static size_t image_headersz_v1(int *hasext)
4acd2d24 1058{
0aca27ea 1059 struct image_cfg_element *e;
02ba70ad 1060 unsigned int count;
4acd2d24 1061 size_t headersz;
0aca27ea
T
1062 int cpu_sheeva;
1063 struct stat s;
d9fb82c5 1064 int cfgi;
0aca27ea 1065 int ret;
4acd2d24
SR
1066
1067 /*
1068 * Calculate the size of the header and the size of the
1069 * payload
1070 */
1071 headersz = sizeof(struct main_hdr_v1);
1072
e58f08b4
T
1073 if (image_get_csk_index() >= 0) {
1074 headersz += sizeof(struct secure_hdr_v1);
1075 if (hasext)
1076 *hasext = 1;
1077 }
1078
0aca27ea
T
1079 cpu_sheeva = image_is_cpu_sheeva();
1080
d737d5d2
T
1081 count = 0;
1082 for (cfgi = 0; cfgi < cfgn; cfgi++) {
1083 e = &image_cfg[cfgi];
1084
1085 if (e->type == IMAGE_CFG_DATA)
1086 count++;
1087
3db9c417
T
1088 if (e->type == IMAGE_CFG_DATA_DELAY ||
1089 (e->type == IMAGE_CFG_BINARY && count > 0)) {
d737d5d2
T
1090 headersz += sizeof(struct register_set_hdr_v1) + 8 * count + 4;
1091 count = 0;
1092 }
4acd2d24 1093
0aca27ea 1094 if (e->type != IMAGE_CFG_BINARY)
d9fb82c5
T
1095 continue;
1096
0aca27ea 1097 ret = stat(e->binary.file, &s);
4acd2d24 1098 if (ret < 0) {
e5f1a586
AB
1099 char cwd[PATH_MAX];
1100 char *dir = cwd;
1101
1102 memset(cwd, 0, sizeof(cwd));
1103 if (!getcwd(cwd, sizeof(cwd))) {
1104 dir = "current working directory";
1105 perror("getcwd() failed");
1106 }
1107
4acd2d24
SR
1108 fprintf(stderr,
1109 "Didn't find the file '%s' in '%s' which is mandatory to generate the image\n"
1110 "This file generally contains the DDR3 training code, and should be extracted from an existing bootable\n"
107d587f 1111 "image for your board. Use 'dumpimage -T kwbimage -p 1' to extract it from an existing image.\n",
0aca27ea 1112 e->binary.file, dir);
4acd2d24
SR
1113 return 0;
1114 }
aa0c7a86 1115
e58f08b4 1116 headersz += sizeof(struct opt_hdr_v1) + sizeof(uint32_t) +
0aca27ea
T
1117 (e->binary.nargs) * sizeof(uint32_t);
1118
1119 if (e->binary.loadaddr) {
1120 /*
1121 * BootROM loads kwbimage header (in which the
1122 * executable code is also stored) to address
1123 * 0x40004000 or 0x40000000. Thus there is
1124 * restriction for the load address of the N-th
1125 * BINARY image.
1126 */
1127 unsigned int base_addr, low_addr, high_addr;
1128
1129 base_addr = cpu_sheeva ? 0x40004000 : 0x40000000;
1130 low_addr = base_addr + headersz;
1131 high_addr = low_addr +
1132 (BINARY_MAX_ARGS - e->binary.nargs) * sizeof(uint32_t);
1133
1134 if (cpu_sheeva && e->binary.loadaddr % 16) {
1135 fprintf(stderr,
1136 "Invalid LOAD_ADDRESS 0x%08x for BINARY %s with %d args.\n"
1137 "Address for CPU SHEEVA must be 16-byte aligned.\n",
1138 e->binary.loadaddr, e->binary.file, e->binary.nargs);
1139 return 0;
1140 }
1141
1142 if (e->binary.loadaddr % 4 || e->binary.loadaddr < low_addr ||
1143 e->binary.loadaddr > high_addr) {
1144 fprintf(stderr,
1145 "Invalid LOAD_ADDRESS 0x%08x for BINARY %s with %d args.\n"
1146 "Address must be 4-byte aligned and in range 0x%08x-0x%08x.\n",
1147 e->binary.loadaddr, e->binary.file,
1148 e->binary.nargs, low_addr, high_addr);
1149 return 0;
1150 }
1151 headersz = e->binary.loadaddr - base_addr;
bdf8c9f2 1152 } else if (cpu_sheeva) {
0aca27ea 1153 headersz = ALIGN(headersz, 16);
bdf8c9f2
T
1154 } else {
1155 headersz = ALIGN(headersz, 4);
0aca27ea
T
1156 }
1157
e58f08b4 1158 headersz += ALIGN(s.st_size, 4) + sizeof(uint32_t);
a1b6b0a9
MS
1159 if (hasext)
1160 *hasext = 1;
1161 }
a1b6b0a9 1162
0aca27ea
T
1163 if (count > 0)
1164 headersz += sizeof(struct register_set_hdr_v1) + 8 * count + 4;
1165
5cad2e6c 1166 return image_headersz_align(headersz, image_get_bootfrom());
4acd2d24 1167}
aa0c7a86 1168
6eb20bbf
T
1169static int add_binary_header_v1(uint8_t **cur, uint8_t **next_ext,
1170 struct image_cfg_element *binarye,
1171 struct main_hdr_v1 *main_hdr)
79066ef8 1172{
d9fb82c5 1173 struct opt_hdr_v1 *hdr = (struct opt_hdr_v1 *)*cur;
0aca27ea 1174 uint32_t base_addr;
e58f08b4
T
1175 uint32_t add_args;
1176 uint32_t offset;
79066ef8
MS
1177 uint32_t *args;
1178 size_t binhdrsz;
0aca27ea 1179 int cpu_sheeva;
79066ef8
MS
1180 struct stat s;
1181 int argi;
1182 FILE *bin;
1183 int ret;
1184
79066ef8
MS
1185 hdr->headertype = OPT_HDR_V1_BINARY_TYPE;
1186
1187 bin = fopen(binarye->binary.file, "r");
1188 if (!bin) {
1189 fprintf(stderr, "Cannot open binary file %s\n",
1190 binarye->binary.file);
1191 return -1;
1192 }
1193
1f6c8a57
MS
1194 if (fstat(fileno(bin), &s)) {
1195 fprintf(stderr, "Cannot stat binary file %s\n",
1196 binarye->binary.file);
1197 goto err_close;
1198 }
79066ef8 1199
d9fb82c5 1200 *cur += sizeof(struct opt_hdr_v1);
79066ef8 1201
d9fb82c5 1202 args = (uint32_t *)*cur;
79066ef8
MS
1203 *args = cpu_to_le32(binarye->binary.nargs);
1204 args++;
1205 for (argi = 0; argi < binarye->binary.nargs; argi++)
1206 args[argi] = cpu_to_le32(binarye->binary.args[argi]);
1207
d9fb82c5 1208 *cur += (binarye->binary.nargs + 1) * sizeof(uint32_t);
79066ef8 1209
e58f08b4 1210 /*
bdf8c9f2
T
1211 * ARM executable code inside the BIN header on platforms with Sheeva
1212 * CPU (A370 and AXP) must always be aligned with the 128-bit boundary.
0aca27ea
T
1213 * In the case when this code is not position independent (e.g. ARM
1214 * SPL), it must be placed at fixed load and execute address.
e58f08b4
T
1215 * This requirement can be met by inserting dummy arguments into
1216 * BIN header, if needed.
1217 */
0aca27ea
T
1218 cpu_sheeva = image_is_cpu_sheeva();
1219 base_addr = cpu_sheeva ? 0x40004000 : 0x40000000;
e58f08b4 1220 offset = *cur - (uint8_t *)main_hdr;
0aca27ea
T
1221 if (binarye->binary.loadaddr)
1222 add_args = (binarye->binary.loadaddr - base_addr - offset) / sizeof(uint32_t);
bdf8c9f2 1223 else if (cpu_sheeva)
0aca27ea 1224 add_args = ((16 - offset % 16) % 16) / sizeof(uint32_t);
bdf8c9f2
T
1225 else
1226 add_args = 0;
e58f08b4
T
1227 if (add_args) {
1228 *(args - 1) = cpu_to_le32(binarye->binary.nargs + add_args);
1229 *cur += add_args * sizeof(uint32_t);
1230 }
1231
d9fb82c5 1232 ret = fread(*cur, s.st_size, 1, bin);
79066ef8
MS
1233 if (ret != 1) {
1234 fprintf(stderr,
1235 "Could not read binary image %s\n",
1236 binarye->binary.file);
1f6c8a57 1237 goto err_close;
79066ef8
MS
1238 }
1239
1240 fclose(bin);
1241
d9fb82c5 1242 *cur += ALIGN(s.st_size, 4);
79066ef8 1243
d9fb82c5
T
1244 *((uint32_t *)*cur) = 0x00000000;
1245 **next_ext = 1;
1246 *next_ext = *cur;
79066ef8 1247
d9fb82c5 1248 *cur += sizeof(uint32_t);
79066ef8 1249
e58f08b4
T
1250 binhdrsz = sizeof(struct opt_hdr_v1) +
1251 (binarye->binary.nargs + add_args + 2) * sizeof(uint32_t) +
1252 ALIGN(s.st_size, 4);
1253 hdr->headersz_lsb = cpu_to_le16(binhdrsz & 0xFFFF);
1254 hdr->headersz_msb = (binhdrsz & 0xFFFF0000) >> 16;
1255
79066ef8 1256 return 0;
1f6c8a57
MS
1257
1258err_close:
1259 fclose(bin);
1260
1261 return -1;
79066ef8
MS
1262}
1263
6eb20bbf 1264static int export_pub_kak_hash(RSA *kak, struct secure_hdr_v1 *secure_hdr)
a1b6b0a9
MS
1265{
1266 FILE *hashf;
1267 int res;
1268
1269 hashf = fopen("pub_kak_hash.txt", "w");
f858bb2e
HS
1270 if (!hashf) {
1271 fprintf(stderr, "Couldn't open hash file: '%s': %s\n",
1272 "pub_kak_hash.txt", strerror(errno));
1273 return 1;
1274 }
a1b6b0a9
MS
1275
1276 res = kwb_export_pubkey(kak, &secure_hdr->kak, hashf, "KAK");
1277
1278 fclose(hashf);
1279
1280 return res < 0 ? 1 : 0;
1281}
1282
6eb20bbf
T
1283static int kwb_sign_csk_with_kak(struct image_tool_params *params,
1284 struct secure_hdr_v1 *secure_hdr, RSA *csk)
a1b6b0a9
MS
1285{
1286 RSA *kak = NULL;
1287 RSA *kak_pub = NULL;
1288 int csk_idx = image_get_csk_index();
1289 struct sig_v1 tmp_sig;
1290
f0317d78 1291 if (csk_idx < 0 || csk_idx > 15) {
a1b6b0a9
MS
1292 fprintf(stderr, "Invalid CSK index %d\n", csk_idx);
1293 return 1;
1294 }
1295
1296 if (kwb_load_kak(params, &kak) < 0)
1297 return 1;
1298
1299 if (export_pub_kak_hash(kak, secure_hdr))
1300 return 1;
1301
1302 if (kwb_import_pubkey(&kak_pub, &secure_hdr->kak, "KAK") < 0)
1303 return 1;
1304
1305 if (kwb_export_pubkey(csk, &secure_hdr->csk[csk_idx], NULL, "CSK") < 0)
1306 return 1;
1307
1308 if (kwb_sign_and_verify(kak, &secure_hdr->csk,
1309 sizeof(secure_hdr->csk) +
1310 sizeof(secure_hdr->csksig),
1311 &tmp_sig, "CSK") < 0)
1312 return 1;
1313
1314 if (kwb_verify(kak_pub, &secure_hdr->csk,
1315 sizeof(secure_hdr->csk) +
1316 sizeof(secure_hdr->csksig),
1317 &tmp_sig, "CSK (2)") < 0)
1318 return 1;
1319
1320 secure_hdr->csksig = tmp_sig;
1321
1322 return 0;
1323}
1324
dd13ac54
T
1325static int add_secure_header_v1(struct image_tool_params *params, uint8_t *image_ptr,
1326 size_t image_size, uint8_t *header_ptr, size_t headersz,
6eb20bbf 1327 struct secure_hdr_v1 *secure_hdr)
a1b6b0a9
MS
1328{
1329 struct image_cfg_element *e_jtagdelay;
1330 struct image_cfg_element *e_boxid;
1331 struct image_cfg_element *e_flashid;
1332 RSA *csk = NULL;
a1b6b0a9
MS
1333 struct sig_v1 tmp_sig;
1334 bool specialized_img = image_get_spezialized_img();
1335
1336 kwb_msg("Create secure header content\n");
1337
1338 e_jtagdelay = image_find_option(IMAGE_CFG_JTAG_DELAY);
1339 e_boxid = image_find_option(IMAGE_CFG_BOX_ID);
1340 e_flashid = image_find_option(IMAGE_CFG_FLASH_ID);
1341
1342 if (kwb_load_csk(params, &csk) < 0)
1343 return 1;
1344
1345 secure_hdr->headertype = OPT_HDR_V1_SECURE_TYPE;
1346 secure_hdr->headersz_msb = 0;
1347 secure_hdr->headersz_lsb = cpu_to_le16(sizeof(struct secure_hdr_v1));
1348 if (e_jtagdelay)
1349 secure_hdr->jtag_delay = e_jtagdelay->jtag_delay;
1350 if (e_boxid && specialized_img)
1351 secure_hdr->boxid = cpu_to_le32(e_boxid->boxid);
1352 if (e_flashid && specialized_img)
1353 secure_hdr->flashid = cpu_to_le32(e_flashid->flashid);
1354
1355 if (kwb_sign_csk_with_kak(params, secure_hdr, csk))
1356 return 1;
1357
a1b6b0a9
MS
1358 if (kwb_sign_and_verify(csk, image_ptr, image_size,
1359 &secure_hdr->imgsig, "image") < 0)
1360 return 1;
1361
dd13ac54 1362 if (kwb_sign_and_verify(csk, header_ptr, headersz, &tmp_sig, "header") < 0)
a1b6b0a9
MS
1363 return 1;
1364
1365 secure_hdr->hdrsig = tmp_sig;
1366
1367 kwb_dump_fuse_cmds(secure_hdr);
1368
1369 return 0;
1370}
a1b6b0a9 1371
9ac1def0
T
1372static void finish_register_set_header_v1(uint8_t **cur, uint8_t **next_ext,
1373 struct register_set_hdr_v1 *register_set_hdr,
1374 int *datai, uint8_t delay)
1375{
1376 int size = sizeof(struct register_set_hdr_v1) + 8 * (*datai) + 4;
1377
1378 register_set_hdr->headertype = OPT_HDR_V1_REGISTER_TYPE;
1379 register_set_hdr->headersz_lsb = cpu_to_le16(size & 0xFFFF);
1380 register_set_hdr->headersz_msb = size >> 16;
1381 register_set_hdr->data[*datai].last_entry.delay = delay;
1382 *cur += size;
1383 **next_ext = 1;
1384 *next_ext = &register_set_hdr->data[*datai].last_entry.next;
1385 *datai = 0;
1386}
1387
4acd2d24 1388static void *image_create_v1(size_t *imagesz, struct image_tool_params *params,
a1b6b0a9 1389 uint8_t *ptr, int payloadsz)
4acd2d24 1390{
79066ef8 1391 struct image_cfg_element *e;
4acd2d24 1392 struct main_hdr_v1 *main_hdr;
2b0980c2 1393 struct opt_hdr_v1 *ohdr;
02ba70ad 1394 struct register_set_hdr_v1 *register_set_hdr;
a1b6b0a9 1395 struct secure_hdr_v1 *secure_hdr = NULL;
4acd2d24 1396 size_t headersz;
885fba15 1397 uint8_t *image, *cur;
4acd2d24 1398 int hasext = 0;
a1b6b0a9 1399 uint8_t *next_ext = NULL;
9ac1def0 1400 int cfgi, datai;
3db9c417 1401 uint8_t delay;
4acd2d24
SR
1402
1403 /*
1404 * Calculate the size of the header and the size of the
1405 * payload
1406 */
e93cf53f 1407 headersz = image_headersz_v1(&hasext);
4acd2d24
SR
1408 if (headersz == 0)
1409 return NULL;
1410
1411 image = malloc(headersz);
1412 if (!image) {
1413 fprintf(stderr, "Cannot allocate memory for image\n");
1414 return NULL;
1415 }
aa0c7a86 1416
4acd2d24
SR
1417 memset(image, 0, headersz);
1418
885fba15 1419 main_hdr = (struct main_hdr_v1 *)image;
a1b6b0a9
MS
1420 cur = image;
1421 cur += sizeof(struct main_hdr_v1);
1422 next_ext = &main_hdr->ext;
4acd2d24
SR
1423
1424 /* Fill the main header */
a8840dce 1425 main_hdr->blocksize =
e23ad5d5 1426 cpu_to_le32(payloadsz);
a8840dce 1427 main_hdr->headersz_lsb = cpu_to_le16(headersz & 0xFFFF);
4acd2d24 1428 main_hdr->headersz_msb = (headersz & 0xFFFF0000) >> 16;
cc3443ff 1429 main_hdr->destaddr = cpu_to_le32(params->addr);
a8840dce
RP
1430 main_hdr->execaddr = cpu_to_le32(params->ep);
1431 main_hdr->srcaddr = cpu_to_le32(headersz);
4acd2d24
SR
1432 main_hdr->ext = hasext;
1433 main_hdr->version = 1;
d1547b36
T
1434 main_hdr->blockid = image_get_bootfrom();
1435
4acd2d24
SR
1436 e = image_find_option(IMAGE_CFG_NAND_BLKSZ);
1437 if (e)
1438 main_hdr->nandblocksize = e->nandblksz / (64 * 1024);
2fdba4f6
T
1439 e = image_find_option(IMAGE_CFG_NAND_PAGESZ);
1440 if (e)
1441 main_hdr->nandpagesize = cpu_to_le16(e->nandpagesz);
4acd2d24
SR
1442 e = image_find_option(IMAGE_CFG_NAND_BADBLK_LOCATION);
1443 if (e)
1444 main_hdr->nandbadblklocation = e->nandbadblklocation;
4bdb5479
CP
1445 e = image_find_option(IMAGE_CFG_BAUDRATE);
1446 if (e)
12f2c03f
T
1447 main_hdr->options |= baudrate_to_option(e->baudrate);
1448 e = image_find_option(IMAGE_CFG_UART_PORT);
1449 if (e)
1450 main_hdr->options |= (e->uart_port & 3) << 3;
1451 e = image_find_option(IMAGE_CFG_UART_MPP);
1452 if (e)
1453 main_hdr->options |= (e->uart_mpp & 7) << 5;
2611c05e
CP
1454 e = image_find_option(IMAGE_CFG_DEBUG);
1455 if (e)
1456 main_hdr->flags = e->debug ? 0x1 : 0;
4acd2d24 1457
501a54a2 1458 /*
954c94aa 1459 * For SATA srcaddr is specified in number of sectors.
501a54a2
T
1460 * This expects the sector size to be 512 bytes.
1461 * Header size is already aligned.
1462 */
1463 if (main_hdr->blockid == IBR_HDR_SATA_ID)
954c94aa 1464 main_hdr->srcaddr = cpu_to_le32(headersz / 512);
501a54a2 1465
501a54a2
T
1466 /* For PCIe srcaddr is not used and must be set to 0xFFFFFFFF. */
1467 if (main_hdr->blockid == IBR_HDR_PEX_ID)
1468 main_hdr->srcaddr = cpu_to_le32(0xFFFFFFFF);
1469
a1b6b0a9
MS
1470 if (image_get_csk_index() >= 0) {
1471 /*
1472 * only reserve the space here; we fill the header later since
1473 * we need the header to be complete to compute the signatures
1474 */
1475 secure_hdr = (struct secure_hdr_v1 *)cur;
1476 cur += sizeof(struct secure_hdr_v1);
d9fb82c5 1477 *next_ext = 1;
a1b6b0a9
MS
1478 next_ext = &secure_hdr->next;
1479 }
a1b6b0a9 1480
02ba70ad 1481 datai = 0;
02ba70ad
T
1482 for (cfgi = 0; cfgi < cfgn; cfgi++) {
1483 e = &image_cfg[cfgi];
f63c583f 1484 if (e->type != IMAGE_CFG_DATA &&
3db9c417
T
1485 e->type != IMAGE_CFG_DATA_DELAY &&
1486 e->type != IMAGE_CFG_BINARY)
02ba70ad 1487 continue;
3db9c417 1488
d737d5d2
T
1489 if (datai == 0)
1490 register_set_hdr = (struct register_set_hdr_v1 *)cur;
3db9c417
T
1491
1492 /* If delay is not specified, use the smallest possible value. */
1493 if (e->type == IMAGE_CFG_DATA_DELAY)
1494 delay = e->regdata_delay;
1495 else
1496 delay = REGISTER_SET_HDR_OPT_DELAY_MS(0);
1497
1498 /*
1499 * DATA_DELAY command is the last entry in the register set
1500 * header and BINARY command inserts new binary header.
1501 * Therefore BINARY command requires to finish register set
1502 * header if some DATA command was specified. And DATA_DELAY
1503 * command automatically finish register set header even when
1504 * there was no DATA command.
1505 */
1506 if (e->type == IMAGE_CFG_DATA_DELAY ||
1507 (e->type == IMAGE_CFG_BINARY && datai != 0))
9ac1def0 1508 finish_register_set_header_v1(&cur, &next_ext, register_set_hdr,
3db9c417
T
1509 &datai, delay);
1510
1511 if (e->type == IMAGE_CFG_DATA) {
1512 register_set_hdr->data[datai].entry.address =
1513 cpu_to_le32(e->regdata.raddr);
1514 register_set_hdr->data[datai].entry.value =
1515 cpu_to_le32(e->regdata.rdata);
1516 datai++;
1517 }
1518
1519 if (e->type == IMAGE_CFG_BINARY) {
1520 if (add_binary_header_v1(&cur, &next_ext, e, main_hdr))
1521 return NULL;
f63c583f 1522 }
02ba70ad
T
1523 }
1524 if (datai != 0) {
9ac1def0 1525 /* Set delay to the smallest possible value. */
3db9c417 1526 delay = REGISTER_SET_HDR_OPT_DELAY_MS(0);
9ac1def0 1527 finish_register_set_header_v1(&cur, &next_ext, register_set_hdr,
3db9c417 1528 &datai, delay);
d9fb82c5 1529 }
4acd2d24 1530
dd13ac54
T
1531 if (secure_hdr && add_secure_header_v1(params, ptr + headersz, payloadsz,
1532 image, headersz, secure_hdr))
a1b6b0a9 1533 return NULL;
a1b6b0a9 1534
4acd2d24 1535 *imagesz = headersz;
2b0980c2
T
1536
1537 /* Fill the real header size without padding into the main header */
1538 headersz = sizeof(*main_hdr);
1539 for_each_opt_hdr_v1 (ohdr, main_hdr)
1540 headersz += opt_hdr_v1_size(ohdr);
1541 main_hdr->headersz_lsb = cpu_to_le16(headersz & 0xFFFF);
1542 main_hdr->headersz_msb = (headersz & 0xFFFF0000) >> 16;
1543
9203c738
PB
1544 /* Calculate and set the header checksum */
1545 main_hdr->checksum = image_checksum8(main_hdr, headersz);
1546
4acd2d24
SR
1547 return image;
1548}
1549
6eb20bbf 1550static int recognize_keyword(char *keyword)
4991b4f7
MS
1551{
1552 int kw_id;
1553
1554 for (kw_id = 1; kw_id < IMAGE_CFG_COUNT; ++kw_id)
1555 if (!strcmp(keyword, id_strs[kw_id]))
1556 return kw_id;
1557
1558 return 0;
1559}
1560
4acd2d24
SR
1561static int image_create_config_parse_oneline(char *line,
1562 struct image_cfg_element *el)
1563{
4991b4f7
MS
1564 char *keyword, *saveptr, *value1, *value2;
1565 char delimiters[] = " \t";
1566 int keyword_id, ret, argi;
1567 char *unknown_msg = "Ignoring unknown line '%s'\n";
1568
1569 keyword = strtok_r(line, delimiters, &saveptr);
1570 keyword_id = recognize_keyword(keyword);
1571
1572 if (!keyword_id) {
1573 fprintf(stderr, unknown_msg, line);
1574 return 0;
1575 }
4acd2d24 1576
4991b4f7 1577 el->type = keyword_id;
94490a4a 1578
4991b4f7
MS
1579 value1 = strtok_r(NULL, delimiters, &saveptr);
1580
1581 if (!value1) {
1582 fprintf(stderr, "Parameter missing in line '%s'\n", line);
1583 return -1;
1584 }
1585
1586 switch (keyword_id) {
1587 case IMAGE_CFG_VERSION:
1588 el->version = atoi(value1);
1589 break;
af49605b
T
1590 case IMAGE_CFG_CPU:
1591 if (strcmp(value1, "FEROCEON") == 0)
1592 el->cpu_sheeva = 0;
1593 else if (strcmp(value1, "SHEEVA") == 0)
1594 el->cpu_sheeva = 1;
1595 else if (strcmp(value1, "A9") == 0)
1596 el->cpu_sheeva = 0;
1597 else {
1598 fprintf(stderr, "Invalid CPU %s\n", value1);
1599 return -1;
1600 }
1601 break;
4991b4f7
MS
1602 case IMAGE_CFG_BOOT_FROM:
1603 ret = image_boot_mode_id(value1);
94490a4a 1604
f411b8f2 1605 if (ret < 0) {
4991b4f7 1606 fprintf(stderr, "Invalid boot media '%s'\n", value1);
4acd2d24
SR
1607 return -1;
1608 }
f411b8f2 1609 el->bootfrom = ret;
4991b4f7
MS
1610 break;
1611 case IMAGE_CFG_NAND_BLKSZ:
1612 el->nandblksz = strtoul(value1, NULL, 16);
1613 break;
1614 case IMAGE_CFG_NAND_BADBLK_LOCATION:
1615 el->nandbadblklocation = strtoul(value1, NULL, 16);
1616 break;
1617 case IMAGE_CFG_NAND_ECC_MODE:
1618 ret = image_nand_ecc_mode_id(value1);
94490a4a 1619
f411b8f2 1620 if (ret < 0) {
4991b4f7 1621 fprintf(stderr, "Invalid NAND ECC mode '%s'\n", value1);
4acd2d24
SR
1622 return -1;
1623 }
f411b8f2 1624 el->nandeccmode = ret;
4991b4f7
MS
1625 break;
1626 case IMAGE_CFG_NAND_PAGESZ:
1627 el->nandpagesz = strtoul(value1, NULL, 16);
1628 break;
1629 case IMAGE_CFG_BINARY:
1630 argi = 0;
1631
1632 el->binary.file = strdup(value1);
4acd2d24 1633 while (1) {
4991b4f7 1634 char *value = strtok_r(NULL, delimiters, &saveptr);
0aca27ea 1635 char *endptr;
4991b4f7 1636
4acd2d24
SR
1637 if (!value)
1638 break;
0aca27ea
T
1639
1640 if (!strcmp(value, "LOAD_ADDRESS")) {
1641 value = strtok_r(NULL, delimiters, &saveptr);
1642 if (!value) {
1643 fprintf(stderr,
1644 "Missing address argument for BINARY LOAD_ADDRESS\n");
1645 return -1;
1646 }
1647 el->binary.loadaddr = strtoul(value, &endptr, 16);
1648 if (*endptr) {
1649 fprintf(stderr,
1650 "Invalid argument '%s' for BINARY LOAD_ADDRESS\n",
1651 value);
1652 return -1;
1653 }
1654 value = strtok_r(NULL, delimiters, &saveptr);
1655 if (value) {
1656 fprintf(stderr,
1657 "Unexpected argument '%s' after BINARY LOAD_ADDRESS\n",
1658 value);
1659 return -1;
1660 }
1661 break;
1662 }
1663
1664 el->binary.args[argi] = strtoul(value, &endptr, 16);
1665 if (*endptr) {
1666 fprintf(stderr, "Invalid argument '%s' for BINARY\n", value);
1667 return -1;
1668 }
4acd2d24
SR
1669 argi++;
1670 if (argi >= BINARY_MAX_ARGS) {
1671 fprintf(stderr,
4991b4f7 1672 "Too many arguments for BINARY\n");
4acd2d24 1673 return -1;
aa0c7a86 1674 }
aa0c7a86 1675 }
4acd2d24 1676 el->binary.nargs = argi;
4991b4f7
MS
1677 break;
1678 case IMAGE_CFG_DATA:
1679 value2 = strtok_r(NULL, delimiters, &saveptr);
4acd2d24
SR
1680
1681 if (!value1 || !value2) {
1682 fprintf(stderr,
1683 "Invalid number of arguments for DATA\n");
1684 return -1;
1685 }
1686
4acd2d24
SR
1687 el->regdata.raddr = strtoul(value1, NULL, 16);
1688 el->regdata.rdata = strtoul(value2, NULL, 16);
4991b4f7 1689 break;
f63c583f
T
1690 case IMAGE_CFG_DATA_DELAY:
1691 if (!strcmp(value1, "SDRAM_SETUP"))
1692 el->regdata_delay = REGISTER_SET_HDR_OPT_DELAY_SDRAM_SETUP;
1693 else
1694 el->regdata_delay = REGISTER_SET_HDR_OPT_DELAY_MS(strtoul(value1, NULL, 10));
fdcae261
T
1695 if (el->regdata_delay > 255) {
1696 fprintf(stderr, "Maximal DATA_DELAY is 255\n");
1697 return -1;
1698 }
f63c583f 1699 break;
4991b4f7
MS
1700 case IMAGE_CFG_BAUDRATE:
1701 el->baudrate = strtoul(value1, NULL, 10);
1702 break;
12f2c03f
T
1703 case IMAGE_CFG_UART_PORT:
1704 el->uart_port = strtoul(value1, NULL, 16);
1705 break;
1706 case IMAGE_CFG_UART_MPP:
1707 el->uart_mpp = strtoul(value1, NULL, 16);
1708 break;
4991b4f7
MS
1709 case IMAGE_CFG_DEBUG:
1710 el->debug = strtoul(value1, NULL, 10);
1711 break;
a1b6b0a9
MS
1712 case IMAGE_CFG_KAK:
1713 el->key_name = strdup(value1);
1714 break;
1715 case IMAGE_CFG_CSK:
1716 el->key_name = strdup(value1);
1717 break;
1718 case IMAGE_CFG_CSK_INDEX:
1719 el->csk_idx = strtol(value1, NULL, 0);
1720 break;
1721 case IMAGE_CFG_JTAG_DELAY:
1722 el->jtag_delay = strtoul(value1, NULL, 0);
1723 break;
1724 case IMAGE_CFG_BOX_ID:
1725 el->boxid = strtoul(value1, NULL, 0);
1726 break;
1727 case IMAGE_CFG_FLASH_ID:
1728 el->flashid = strtoul(value1, NULL, 0);
1729 break;
1730 case IMAGE_CFG_SEC_SPECIALIZED_IMG:
1731 el->sec_specialized_img = true;
1732 break;
1733 case IMAGE_CFG_SEC_COMMON_IMG:
1734 el->sec_specialized_img = false;
1735 break;
1736 case IMAGE_CFG_SEC_BOOT_DEV:
1737 el->sec_boot_dev = strtoul(value1, NULL, 0);
1738 break;
1739 case IMAGE_CFG_SEC_FUSE_DUMP:
1740 el->name = strdup(value1);
1741 break;
4991b4f7
MS
1742 default:
1743 fprintf(stderr, unknown_msg, line);
aa0c7a86 1744 }
aa0c7a86 1745
4acd2d24
SR
1746 return 0;
1747}
aa0c7a86
PW
1748
1749/*
4acd2d24
SR
1750 * Parse the configuration file 'fcfg' into the array of configuration
1751 * elements 'image_cfg', and return the number of configuration
1752 * elements in 'cfgn'.
aa0c7a86 1753 */
4acd2d24
SR
1754static int image_create_config_parse(FILE *fcfg)
1755{
1756 int ret;
1757 int cfgi = 0;
1758
1759 /* Parse the configuration file */
1760 while (!feof(fcfg)) {
1761 char *line;
1762 char buf[256];
1763
1764 /* Read the current line */
1765 memset(buf, 0, sizeof(buf));
1766 line = fgets(buf, sizeof(buf), fcfg);
1767 if (!line)
1768 break;
1769
1770 /* Ignore useless lines */
1771 if (line[0] == '\n' || line[0] == '#')
1772 continue;
1773
1774 /* Strip final newline */
1775 if (line[strlen(line) - 1] == '\n')
1776 line[strlen(line) - 1] = 0;
1777
1778 /* Parse the current line */
1779 ret = image_create_config_parse_oneline(line,
1780 &image_cfg[cfgi]);
1781 if (ret)
1782 return ret;
1783
1784 cfgi++;
1785
1786 if (cfgi >= IMAGE_CFG_ELEMENT_MAX) {
1787 fprintf(stderr,
1788 "Too many configuration elements in .cfg file\n");
1789 return -1;
1790 }
1791 }
1792
1793 cfgn = cfgi;
1794 return 0;
1795}
1796
1797static int image_get_version(void)
1798{
1799 struct image_cfg_element *e;
1800
1801 e = image_find_option(IMAGE_CFG_VERSION);
1802 if (!e)
1803 return -1;
1804
1805 return e->version;
1806}
1807
4acd2d24 1808static void kwbimage_set_header(void *ptr, struct stat *sbuf, int ifd,
f86ed6a8 1809 struct image_tool_params *params)
aa0c7a86 1810{
4acd2d24
SR
1811 FILE *fcfg;
1812 void *image = NULL;
1813 int version;
93e9371f 1814 size_t headersz = 0;
e23ad5d5 1815 size_t datasz;
aa0c7a86 1816 uint32_t checksum;
e23ad5d5 1817 struct stat s;
4acd2d24 1818 int ret;
aa0c7a86 1819
e23ad5d5
T
1820 /*
1821 * Do not use sbuf->st_size as it contains size with padding.
1822 * We need original image data size, so stat original file.
1823 */
1824 if (stat(params->datafile, &s)) {
1825 fprintf(stderr, "Could not stat data file %s: %s\n",
1826 params->datafile, strerror(errno));
1827 exit(EXIT_FAILURE);
1828 }
1829 datasz = ALIGN(s.st_size, 4);
1830
4acd2d24
SR
1831 fcfg = fopen(params->imagename, "r");
1832 if (!fcfg) {
1833 fprintf(stderr, "Could not open input file %s\n",
1834 params->imagename);
1835 exit(EXIT_FAILURE);
1836 }
1837
1838 image_cfg = malloc(IMAGE_CFG_ELEMENT_MAX *
1839 sizeof(struct image_cfg_element));
1840 if (!image_cfg) {
1841 fprintf(stderr, "Cannot allocate memory\n");
1842 fclose(fcfg);
1843 exit(EXIT_FAILURE);
1844 }
1845
1846 memset(image_cfg, 0,
1847 IMAGE_CFG_ELEMENT_MAX * sizeof(struct image_cfg_element));
1848 rewind(fcfg);
1849
1850 ret = image_create_config_parse(fcfg);
1851 fclose(fcfg);
1852 if (ret) {
1853 free(image_cfg);
1854 exit(EXIT_FAILURE);
1855 }
1856
1857 version = image_get_version();
934a529f
SR
1858 switch (version) {
1859 /*
1860 * Fallback to version 0 if no version is provided in the
1861 * cfg file
1862 */
1863 case -1:
1864 case 0:
e23ad5d5 1865 image = image_create_v0(&headersz, params, datasz + 4);
934a529f
SR
1866 break;
1867
1868 case 1:
e23ad5d5 1869 image = image_create_v1(&headersz, params, ptr, datasz + 4);
934a529f
SR
1870 break;
1871
1872 default:
1873 fprintf(stderr, "Unsupported version %d\n", version);
1874 free(image_cfg);
1875 exit(EXIT_FAILURE);
1876 }
4acd2d24
SR
1877
1878 if (!image) {
1879 fprintf(stderr, "Could not create image\n");
1880 free(image_cfg);
1881 exit(EXIT_FAILURE);
1882 }
1883
1884 free(image_cfg);
aa0c7a86 1885
e23ad5d5 1886 /* Build and add image data checksum */
37cb9c15 1887 checksum = cpu_to_le32(image_checksum32((uint8_t *)ptr + headersz,
e23ad5d5
T
1888 datasz));
1889 memcpy((uint8_t *)ptr + headersz + datasz, &checksum, sizeof(uint32_t));
aa0c7a86 1890
4acd2d24
SR
1891 /* Finally copy the header into the image area */
1892 memcpy(ptr, image, headersz);
aa0c7a86 1893
4acd2d24 1894 free(image);
aa0c7a86
PW
1895}
1896
4acd2d24 1897static void kwbimage_print_header(const void *ptr)
aa0c7a86 1898{
4acd2d24 1899 struct main_hdr_v0 *mhdr = (struct main_hdr_v0 *)ptr;
f76ae257 1900 struct bin_hdr_v0 *bhdr;
732c930b 1901 struct opt_hdr_v1 *ohdr;
4acd2d24
SR
1902
1903 printf("Image Type: MVEBU Boot from %s Image\n",
1904 image_boot_mode_name(mhdr->blockid));
acb0b38d 1905 printf("Image version:%d\n", kwbimage_version(ptr));
34dcf952 1906
732c930b
MB
1907 for_each_opt_hdr_v1 (ohdr, mhdr) {
1908 if (ohdr->headertype == OPT_HDR_V1_BINARY_TYPE) {
c934c9a6 1909 printf("BIN Img Size: ");
732c930b
MB
1910 genimg_print_size(opt_hdr_v1_size(ohdr) - 12 -
1911 4 * ohdr->data[0]);
63cf0d72
T
1912 printf("BIN Img Offs: ");
1913 genimg_print_size(((uint8_t *)ohdr - (uint8_t *)mhdr) +
1914 8 + 4 * ohdr->data[0]);
34dcf952
T
1915 }
1916 }
732c930b 1917
f76ae257
T
1918 for_each_bin_hdr_v0(bhdr, mhdr) {
1919 printf("BIN Img Size: ");
1920 genimg_print_size(le32_to_cpu(bhdr->size));
1921 printf("BIN Img Addr: %08x\n", le32_to_cpu(bhdr->destaddr));
1922 printf("BIN Img Entr: %08x\n", le32_to_cpu(bhdr->execaddr));
1923 }
1924
26f195c7 1925 printf("Data Size: ");
9f39f199 1926 genimg_print_size(le32_to_cpu(mhdr->blocksize) - sizeof(uint32_t));
443894a8
T
1927 printf("Data Offset: ");
1928 if (mhdr->blockid == IBR_HDR_SATA_ID)
1929 printf("%u Sector%s (LBA)\n", le32_to_cpu(mhdr->srcaddr),
1930 le32_to_cpu(mhdr->srcaddr) != 1 ? "s" : "");
1931 else
1932 genimg_print_size(le32_to_cpu(mhdr->srcaddr));
9f39f199
T
1933 printf("Load Address: %08x\n", le32_to_cpu(mhdr->destaddr));
1934 printf("Entry Point: %08x\n", le32_to_cpu(mhdr->execaddr));
aa0c7a86
PW
1935}
1936
4acd2d24 1937static int kwbimage_check_image_types(uint8_t type)
aa0c7a86
PW
1938{
1939 if (type == IH_TYPE_KWBIMAGE)
1940 return EXIT_SUCCESS;
94490a4a
MS
1941
1942 return EXIT_FAILURE;
aa0c7a86
PW
1943}
1944
4acd2d24
SR
1945static int kwbimage_verify_header(unsigned char *ptr, int image_size,
1946 struct image_tool_params *params)
1947{
fe2fd73d 1948 size_t header_size = kwbheader_size(ptr);
700ea98b
T
1949 uint8_t blockid;
1950 uint32_t offset;
1951 uint32_t size;
fe2fd73d 1952 uint8_t csum;
6cd5678c 1953
cbd0043e
T
1954 if (header_size > 192*1024)
1955 return -FDT_ERR_BADSTRUCTURE;
1956
6cd5678c
AG
1957 if (header_size > image_size)
1958 return -FDT_ERR_BADSTRUCTURE;
4acd2d24 1959
db7cd4ed 1960 if (!main_hdr_checksum_ok(ptr))
4acd2d24
SR
1961 return -FDT_ERR_BADSTRUCTURE;
1962
1963 /* Only version 0 extended header has checksum */
acb0b38d 1964 if (kwbimage_version(ptr) == 0) {
fe2c0e25 1965 struct main_hdr_v0 *mhdr = (struct main_hdr_v0 *)ptr;
f76ae257
T
1966 struct ext_hdr_v0 *ext_hdr;
1967 struct bin_hdr_v0 *bhdr;
e89016c4 1968
f76ae257 1969 for_each_ext_hdr_v0(ext_hdr, ptr) {
fe2fd73d
MB
1970 csum = image_checksum8(ext_hdr, sizeof(*ext_hdr) - 1);
1971 if (csum != ext_hdr->checksum)
fe2c0e25
T
1972 return -FDT_ERR_BADSTRUCTURE;
1973 }
700ea98b 1974
f76ae257
T
1975 for_each_bin_hdr_v0(bhdr, ptr) {
1976 csum = image_checksum8(bhdr, (uint8_t *)&bhdr->checksum - (uint8_t *)bhdr - 1);
1977 if (csum != bhdr->checksum)
1978 return -FDT_ERR_BADSTRUCTURE;
1979
1980 if (bhdr->offset > sizeof(*bhdr) || bhdr->offset % 4 != 0)
1981 return -FDT_ERR_BADSTRUCTURE;
1982
1983 if (bhdr->offset + bhdr->size + 4 > sizeof(*bhdr) || bhdr->size % 4 != 0)
1984 return -FDT_ERR_BADSTRUCTURE;
1985
1986 if (image_checksum32((uint8_t *)bhdr + bhdr->offset, bhdr->size) !=
1987 *(uint32_t *)((uint8_t *)bhdr + bhdr->offset + bhdr->size))
1988 return -FDT_ERR_BADSTRUCTURE;
1989 }
1990
700ea98b
T
1991 blockid = mhdr->blockid;
1992 offset = le32_to_cpu(mhdr->srcaddr);
1993 size = le32_to_cpu(mhdr->blocksize);
acb0b38d 1994 } else if (kwbimage_version(ptr) == 1) {
9380445f 1995 struct main_hdr_v1 *mhdr = (struct main_hdr_v1 *)ptr;
732c930b
MB
1996 const uint8_t *mhdr_end;
1997 struct opt_hdr_v1 *ohdr;
9380445f 1998
732c930b
MB
1999 mhdr_end = (uint8_t *)mhdr + header_size;
2000 for_each_opt_hdr_v1 (ohdr, ptr)
2001 if (!opt_hdr_v1_valid_size(ohdr, mhdr_end))
2002 return -FDT_ERR_BADSTRUCTURE;
e0c243c3 2003
700ea98b 2004 blockid = mhdr->blockid;
e0c243c3 2005 offset = le32_to_cpu(mhdr->srcaddr);
700ea98b
T
2006 size = le32_to_cpu(mhdr->blocksize);
2007 } else {
2008 return -FDT_ERR_BADSTRUCTURE;
2009 }
e0c243c3 2010
700ea98b
T
2011 /*
2012 * For SATA srcaddr is specified in number of sectors.
954c94aa 2013 * This expects that sector size is 512 bytes.
700ea98b 2014 */
954c94aa 2015 if (blockid == IBR_HDR_SATA_ID)
700ea98b 2016 offset *= 512;
e0c243c3 2017
700ea98b
T
2018 /*
2019 * For PCIe srcaddr is always set to 0xFFFFFFFF.
2020 * This expects that data starts after all headers.
2021 */
2022 if (blockid == IBR_HDR_PEX_ID && offset == 0xFFFFFFFF)
2023 offset = header_size;
e0c243c3 2024
700ea98b
T
2025 if (offset > image_size || offset % 4 != 0)
2026 return -FDT_ERR_BADSTRUCTURE;
e0c243c3 2027
700ea98b
T
2028 if (size < 4 || offset + size > image_size || size % 4 != 0)
2029 return -FDT_ERR_BADSTRUCTURE;
e0c243c3 2030
700ea98b
T
2031 if (image_checksum32(ptr + offset, size - 4) !=
2032 *(uint32_t *)(ptr + offset + size - 4))
b984056f 2033 return -FDT_ERR_BADSTRUCTURE;
9380445f 2034
4acd2d24
SR
2035 return 0;
2036}
2037
2038static int kwbimage_generate(struct image_tool_params *params,
2039 struct image_type_params *tparams)
2040{
6cbf7eda 2041 FILE *fcfg;
37cb9c15 2042 struct stat s;
4acd2d24 2043 int alloc_len;
c934aad0 2044 int bootfrom;
6cbf7eda 2045 int version;
4acd2d24 2046 void *hdr;
6cbf7eda 2047 int ret;
4acd2d24 2048
6cbf7eda
PW
2049 fcfg = fopen(params->imagename, "r");
2050 if (!fcfg) {
2051 fprintf(stderr, "Could not open input file %s\n",
2052 params->imagename);
2053 exit(EXIT_FAILURE);
2054 }
2055
37cb9c15
T
2056 if (stat(params->datafile, &s)) {
2057 fprintf(stderr, "Could not stat data file %s: %s\n",
2058 params->datafile, strerror(errno));
2059 exit(EXIT_FAILURE);
2060 }
2061
6cbf7eda
PW
2062 image_cfg = malloc(IMAGE_CFG_ELEMENT_MAX *
2063 sizeof(struct image_cfg_element));
2064 if (!image_cfg) {
2065 fprintf(stderr, "Cannot allocate memory\n");
2066 fclose(fcfg);
2067 exit(EXIT_FAILURE);
2068 }
2069
2070 memset(image_cfg, 0,
2071 IMAGE_CFG_ELEMENT_MAX * sizeof(struct image_cfg_element));
2072 rewind(fcfg);
2073
2074 ret = image_create_config_parse(fcfg);
2075 fclose(fcfg);
2076 if (ret) {
2077 free(image_cfg);
2078 exit(EXIT_FAILURE);
2079 }
2080
c934aad0 2081 bootfrom = image_get_bootfrom();
6cbf7eda
PW
2082 version = image_get_version();
2083 switch (version) {
2084 /*
2085 * Fallback to version 0 if no version is provided in the
2086 * cfg file
2087 */
2088 case -1:
2089 case 0:
851114be 2090 alloc_len = image_headersz_v0(NULL);
6cbf7eda
PW
2091 break;
2092
2093 case 1:
e93cf53f 2094 alloc_len = image_headersz_v1(NULL);
252e7c3a
T
2095 if (!alloc_len) {
2096 free(image_cfg);
2097 exit(EXIT_FAILURE);
2098 }
78d997f9
T
2099 if (alloc_len > 192*1024) {
2100 fprintf(stderr, "Header is too big (%u bytes), maximal kwbimage header size is %u bytes\n", alloc_len, 192*1024);
2101 free(image_cfg);
2102 exit(EXIT_FAILURE);
2103 }
6cbf7eda
PW
2104 break;
2105
2106 default:
2107 fprintf(stderr, "Unsupported version %d\n", version);
2108 free(image_cfg);
2109 exit(EXIT_FAILURE);
4acd2d24
SR
2110 }
2111
6cbf7eda
PW
2112 free(image_cfg);
2113
4acd2d24
SR
2114 hdr = malloc(alloc_len);
2115 if (!hdr) {
2116 fprintf(stderr, "%s: malloc return failure: %s\n",
2117 params->cmdname, strerror(errno));
2118 exit(EXIT_FAILURE);
2119 }
2120
2121 memset(hdr, 0, alloc_len);
2122 tparams->header_size = alloc_len;
2123 tparams->hdr = hdr;
2124
77720859
SR
2125 /*
2126 * The resulting image needs to be 4-byte aligned. At least
2127 * the Marvell hdrparser tool complains if its unaligned.
37cb9c15 2128 * After the image data is stored 4-byte checksum.
188099ed 2129 * Final UART image must be aligned to 128 bytes.
c934aad0 2130 * Final SPI and NAND images must be aligned to 256 bytes.
501a54a2 2131 * Final SATA and SDIO images must be aligned to 512 bytes.
77720859 2132 */
c934aad0
T
2133 if (bootfrom == IBR_HDR_SPI_ID || bootfrom == IBR_HDR_NAND_ID)
2134 return 4 + (256 - (alloc_len + s.st_size + 4) % 256) % 256;
501a54a2
T
2135 else if (bootfrom == IBR_HDR_SATA_ID || bootfrom == IBR_HDR_SDIO_ID)
2136 return 4 + (512 - (alloc_len + s.st_size + 4) % 512) % 512;
188099ed
T
2137 else if (bootfrom == IBR_HDR_UART_ID)
2138 return 4 + (128 - (alloc_len + s.st_size + 4) % 128) % 128;
c934aad0
T
2139 else
2140 return 4 + (4 - s.st_size % 4) % 4;
4acd2d24
SR
2141}
2142
1a8e6b63
T
2143static int kwbimage_generate_config(void *ptr, struct image_tool_params *params)
2144{
2145 struct main_hdr_v0 *mhdr0 = (struct main_hdr_v0 *)ptr;
2146 struct main_hdr_v1 *mhdr = (struct main_hdr_v1 *)ptr;
2147 size_t header_size = kwbheader_size(ptr);
2148 struct register_set_hdr_v1 *regset_hdr;
2149 struct ext_hdr_v0_reg *regdata;
2150 struct ext_hdr_v0 *ehdr0;
f76ae257 2151 struct bin_hdr_v0 *bhdr0;
1a8e6b63 2152 struct opt_hdr_v1 *ohdr;
908801dc 2153 int regset_count;
f76ae257 2154 int params_count;
1a8e6b63 2155 unsigned offset;
f76ae257 2156 int is_v0_ext;
1a8e6b63
T
2157 int cur_idx;
2158 int version;
2159 FILE *f;
2160 int i;
2161
2162 f = fopen(params->outfile, "w");
2163 if (!f) {
2164 fprintf(stderr, "Can't open \"%s\": %s\n", params->outfile, strerror(errno));
2165 return -1;
2166 }
2167
2168 version = kwbimage_version(ptr);
2169
f76ae257
T
2170 is_v0_ext = 0;
2171 if (version == 0) {
2172 if (mhdr0->ext > 1 || mhdr0->bin ||
2173 ((ehdr0 = ext_hdr_v0_first(ptr)) &&
2174 (ehdr0->match_addr || ehdr0->match_mask || ehdr0->match_value)))
2175 is_v0_ext = 1;
2176 }
2177
1a8e6b63
T
2178 if (version != 0)
2179 fprintf(f, "VERSION %d\n", version);
2180
2181 fprintf(f, "BOOT_FROM %s\n", image_boot_mode_name(mhdr->blockid) ?: "<unknown>");
2182
2183 if (version == 0 && mhdr->blockid == IBR_HDR_NAND_ID)
2184 fprintf(f, "NAND_ECC_MODE %s\n", image_nand_ecc_mode_name(mhdr0->nandeccmode));
2185
2186 if (mhdr->blockid == IBR_HDR_NAND_ID)
aab9b063 2187 fprintf(f, "NAND_PAGE_SIZE 0x%x\n", (unsigned)le16_to_cpu(mhdr->nandpagesize));
1a8e6b63 2188
0a3a392c 2189 if (mhdr->blockid == IBR_HDR_NAND_ID && (version != 0 || is_v0_ext || mhdr->nandblocksize != 0)) {
226abde8
T
2190 if (mhdr->nandblocksize != 0) /* block size explicitly set in 64 kB unit */
2191 fprintf(f, "NAND_BLKSZ 0x%x\n", (unsigned)mhdr->nandblocksize * 64*1024);
2192 else if (le16_to_cpu(mhdr->nandpagesize) > 512)
2193 fprintf(f, "NAND_BLKSZ 0x10000\n"); /* large page NAND flash = 64 kB block size */
2194 else
2195 fprintf(f, "NAND_BLKSZ 0x4000\n"); /* small page NAND flash = 16 kB block size */
2196 }
f76ae257 2197
e060779e 2198 if (mhdr->blockid == IBR_HDR_NAND_ID && (version != 0 || is_v0_ext))
1a8e6b63 2199 fprintf(f, "NAND_BADBLK_LOCATION 0x%x\n", (unsigned)mhdr->nandbadblklocation);
1a8e6b63
T
2200
2201 if (version == 0 && mhdr->blockid == IBR_HDR_SATA_ID)
2202 fprintf(f, "SATA_PIO_MODE %u\n", (unsigned)mhdr0->satapiomode);
2203
2204 /*
2205 * Addresses and sizes which are specified by mkimage command line
2206 * arguments and not in kwbimage config file
2207 */
2208
2209 if (version != 0)
2210 fprintf(f, "#HEADER_SIZE 0x%x\n",
2211 ((unsigned)mhdr->headersz_msb << 8) | le16_to_cpu(mhdr->headersz_lsb));
2212
2213 fprintf(f, "#SRC_ADDRESS 0x%x\n", le32_to_cpu(mhdr->srcaddr));
2214 fprintf(f, "#BLOCK_SIZE 0x%x\n", le32_to_cpu(mhdr->blocksize));
2215 fprintf(f, "#DEST_ADDRESS 0x%08x\n", le32_to_cpu(mhdr->destaddr));
2216 fprintf(f, "#EXEC_ADDRESS 0x%08x\n", le32_to_cpu(mhdr->execaddr));
2217
2218 if (version != 0) {
2219 if (options_to_baudrate(mhdr->options))
2220 fprintf(f, "BAUDRATE %u\n", options_to_baudrate(mhdr->options));
2221 if (options_to_baudrate(mhdr->options) ||
2222 ((mhdr->options >> 3) & 0x3) || ((mhdr->options >> 5) & 0x7)) {
2223 fprintf(f, "UART_PORT %u\n", (unsigned)((mhdr->options >> 3) & 0x3));
2224 fprintf(f, "UART_MPP 0x%x\n", (unsigned)((mhdr->options >> 5) & 0x7));
2225 }
2226 if (mhdr->flags & 0x1)
2227 fprintf(f, "DEBUG 1\n");
2228 }
2229
2230 cur_idx = 1;
2231 for_each_opt_hdr_v1(ohdr, ptr) {
2232 if (ohdr->headertype == OPT_HDR_V1_SECURE_TYPE) {
2233 fprintf(f, "#SECURE_HEADER\n");
2234 } else if (ohdr->headertype == OPT_HDR_V1_BINARY_TYPE) {
2235 fprintf(f, "BINARY binary%d.bin", cur_idx);
2236 for (i = 0; i < ohdr->data[0]; i++)
2237 fprintf(f, " 0x%x", le32_to_cpu(((uint32_t *)ohdr->data)[i + 1]));
2238 offset = (unsigned)((uint8_t *)ohdr - (uint8_t *)mhdr) + 8 + 4 * ohdr->data[0];
2239 fprintf(f, " LOAD_ADDRESS 0x%08x\n", 0x40000000 + offset);
2240 fprintf(f, " # for CPU SHEEVA: LOAD_ADDRESS 0x%08x\n", 0x40004000 + offset);
2241 cur_idx++;
2242 } else if (ohdr->headertype == OPT_HDR_V1_REGISTER_TYPE) {
2243 regset_hdr = (struct register_set_hdr_v1 *)ohdr;
908801dc
T
2244 if (opt_hdr_v1_size(ohdr) > sizeof(*ohdr))
2245 regset_count = (opt_hdr_v1_size(ohdr) - sizeof(*ohdr)) /
2246 sizeof(regset_hdr->data[0].entry);
2247 else
2248 regset_count = 0;
2249 for (i = 0; i < regset_count; i++)
1a8e6b63
T
2250 fprintf(f, "DATA 0x%08x 0x%08x\n",
2251 le32_to_cpu(regset_hdr->data[i].entry.address),
2252 le32_to_cpu(regset_hdr->data[i].entry.value));
908801dc
T
2253 if (regset_count > 0) {
2254 if (regset_hdr->data[regset_count-1].last_entry.delay !=
2255 REGISTER_SET_HDR_OPT_DELAY_SDRAM_SETUP)
1a8e6b63 2256 fprintf(f, "DATA_DELAY %u\n",
908801dc 2257 (unsigned)regset_hdr->data[regset_count-1].last_entry.delay);
1a8e6b63
T
2258 else
2259 fprintf(f, "DATA_DELAY SDRAM_SETUP\n");
2260 }
2261 }
2262 }
2263
f76ae257
T
2264 if (version == 0 && !is_v0_ext && le16_to_cpu(mhdr0->ddrinitdelay))
2265 fprintf(f, "DDR_INIT_DELAY %u\n", (unsigned)le16_to_cpu(mhdr0->ddrinitdelay));
2266
2267 for_each_ext_hdr_v0(ehdr0, ptr) {
2268 if (is_v0_ext) {
2269 fprintf(f, "\nMATCH ADDRESS 0x%08x MASK 0x%08x VALUE 0x%08x\n",
2270 le32_to_cpu(ehdr0->match_addr),
2271 le32_to_cpu(ehdr0->match_mask),
2272 le32_to_cpu(ehdr0->match_value));
2273 if (ehdr0->rsvd1[0] || ehdr0->rsvd1[1] || ehdr0->rsvd1[2] ||
2274 ehdr0->rsvd1[3] || ehdr0->rsvd1[4] || ehdr0->rsvd1[5] ||
2275 ehdr0->rsvd1[6] || ehdr0->rsvd1[7])
2276 fprintf(f, "#DDR_RSVD1 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x\n",
2277 ehdr0->rsvd1[0], ehdr0->rsvd1[1], ehdr0->rsvd1[2],
2278 ehdr0->rsvd1[3], ehdr0->rsvd1[4], ehdr0->rsvd1[5],
2279 ehdr0->rsvd1[6], ehdr0->rsvd1[7]);
2280 if (ehdr0->rsvd2[0] || ehdr0->rsvd2[1] || ehdr0->rsvd2[2] ||
2281 ehdr0->rsvd2[3] || ehdr0->rsvd2[4] || ehdr0->rsvd2[5] ||
2282 ehdr0->rsvd2[6])
2283 fprintf(f, "#DDR_RSVD2 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x 0x%x\n",
2284 ehdr0->rsvd2[0], ehdr0->rsvd2[1], ehdr0->rsvd2[2],
2285 ehdr0->rsvd2[3], ehdr0->rsvd2[4], ehdr0->rsvd2[5],
2286 ehdr0->rsvd2[6]);
2287 if (ehdr0->ddrwritetype)
2288 fprintf(f, "DDR_WRITE_TYPE %u\n", (unsigned)ehdr0->ddrwritetype);
2289 if (ehdr0->ddrresetmpp)
2290 fprintf(f, "DDR_RESET_MPP 0x%x\n", (unsigned)ehdr0->ddrresetmpp);
2291 if (ehdr0->ddrclkenmpp)
2292 fprintf(f, "DDR_CLKEN_MPP 0x%x\n", (unsigned)ehdr0->ddrclkenmpp);
2293 if (ehdr0->ddrinitdelay)
2294 fprintf(f, "DDR_INIT_DELAY %u\n", (unsigned)ehdr0->ddrinitdelay);
2295 }
2296
1a8e6b63
T
2297 if (ehdr0->offset) {
2298 for (regdata = (struct ext_hdr_v0_reg *)((uint8_t *)ptr + ehdr0->offset);
a2389213
T
2299 (uint8_t *)regdata < (uint8_t *)ptr + header_size &&
2300 (regdata->raddr || regdata->rdata);
1a8e6b63
T
2301 regdata++)
2302 fprintf(f, "DATA 0x%08x 0x%08x\n", le32_to_cpu(regdata->raddr),
2303 le32_to_cpu(regdata->rdata));
a2389213
T
2304 if ((uint8_t *)regdata != (uint8_t *)ptr + ehdr0->offset)
2305 fprintf(f, "DATA 0x0 0x0\n");
1a8e6b63 2306 }
f76ae257
T
2307
2308 if (le32_to_cpu(ehdr0->enddelay))
2309 fprintf(f, "DATA_DELAY %u\n", le32_to_cpu(ehdr0->enddelay));
2310 else if (is_v0_ext)
2311 fprintf(f, "DATA_DELAY SDRAM_SETUP\n");
1a8e6b63
T
2312 }
2313
f76ae257
T
2314 cur_idx = 1;
2315 for_each_bin_hdr_v0(bhdr0, ptr) {
2316 fprintf(f, "\nMATCH ADDRESS 0x%08x MASK 0x%08x VALUE 0x%08x\n",
2317 le32_to_cpu(bhdr0->match_addr),
2318 le32_to_cpu(bhdr0->match_mask),
2319 le32_to_cpu(bhdr0->match_value));
2320
2321 fprintf(f, "BINARY binary%d.bin", cur_idx);
2322 params_count = fls4(bhdr0->params_flags & 0xF);
2323 for (i = 0; i < params_count; i++)
2324 fprintf(f, " 0x%x", (bhdr0->params[i] & (1 << i)) ? bhdr0->params[i] : 0);
2325 fprintf(f, " LOAD_ADDRESS 0x%08x", le32_to_cpu(bhdr0->destaddr));
2326 fprintf(f, " EXEC_ADDRESS 0x%08x", le32_to_cpu(bhdr0->execaddr));
2327 fprintf(f, "\n");
2328
2329 fprintf(f, "#BINARY_OFFSET 0x%x\n", le32_to_cpu(bhdr0->offset));
2330 fprintf(f, "#BINARY_SIZE 0x%x\n", le32_to_cpu(bhdr0->size));
2331
2332 if (bhdr0->rsvd1)
2333 fprintf(f, "#BINARY_RSVD1 0x%x\n", (unsigned)bhdr0->rsvd1);
2334 if (bhdr0->rsvd2)
2335 fprintf(f, "#BINARY_RSVD2 0x%x\n", (unsigned)bhdr0->rsvd2);
2336
2337 cur_idx++;
2338 }
1a8e6b63
T
2339
2340 /* Undocumented reserved fields */
2341
2342 if (version == 0 && (mhdr0->rsvd1[0] || mhdr0->rsvd1[1] || mhdr0->rsvd1[2]))
2343 fprintf(f, "#RSVD1 0x%x 0x%x 0x%x\n", (unsigned)mhdr0->rsvd1[0],
2344 (unsigned)mhdr0->rsvd1[1], (unsigned)mhdr0->rsvd1[2]);
2345
1a8e6b63
T
2346 if (version == 0 && le16_to_cpu(mhdr0->rsvd2))
2347 fprintf(f, "#RSVD2 0x%x\n", (unsigned)le16_to_cpu(mhdr0->rsvd2));
2348
2349 if (version != 0 && mhdr->reserved4)
2350 fprintf(f, "#RESERVED4 0x%x\n", (unsigned)mhdr->reserved4);
2351
2352 if (version != 0 && mhdr->reserved5)
2353 fprintf(f, "#RESERVED5 0x%x\n", (unsigned)le16_to_cpu(mhdr->reserved5));
2354
2355 fclose(f);
2356
2357 return 0;
2358}
2359
aa6943ca
T
2360static int kwbimage_extract_subimage(void *ptr, struct image_tool_params *params)
2361{
2362 struct main_hdr_v1 *mhdr = (struct main_hdr_v1 *)ptr;
fe2fd73d 2363 size_t header_size = kwbheader_size(ptr);
f76ae257 2364 struct bin_hdr_v0 *bhdr;
732c930b 2365 struct opt_hdr_v1 *ohdr;
aa6943ca 2366 int idx = params->pflag;
1972c7e3 2367 int cur_idx;
aa6943ca
T
2368 uint32_t offset;
2369 ulong image;
2370 ulong size;
2371
1a8e6b63
T
2372 /* Generate kwbimage config file when '-p -1' is specified */
2373 if (idx == -1)
2374 return kwbimage_generate_config(ptr, params);
2375
1972c7e3
T
2376 image = 0;
2377 size = 0;
2378
2379 if (idx == 0) {
2380 /* Extract data image when -p is not specified or when '-p 0' is specified */
2381 offset = le32_to_cpu(mhdr->srcaddr);
aa6943ca 2382
954c94aa 2383 if (mhdr->blockid == IBR_HDR_SATA_ID)
1972c7e3 2384 offset *= 512;
732c930b 2385
1972c7e3
T
2386 if (mhdr->blockid == IBR_HDR_PEX_ID && offset == 0xFFFFFFFF)
2387 offset = header_size;
aa6943ca 2388
1972c7e3
T
2389 image = (ulong)((uint8_t *)ptr + offset);
2390 size = le32_to_cpu(mhdr->blocksize) - 4;
2391 } else {
2392 /* Extract N-th binary header executabe image when other '-p N' is specified */
2393 cur_idx = 1;
2394 for_each_opt_hdr_v1(ohdr, ptr) {
2395 if (ohdr->headertype != OPT_HDR_V1_BINARY_TYPE)
2396 continue;
aa6943ca 2397
1972c7e3
T
2398 if (idx == cur_idx) {
2399 image = (ulong)&ohdr->data[4 + 4 * ohdr->data[0]];
2400 size = opt_hdr_v1_size(ohdr) - 12 - 4 * ohdr->data[0];
2401 break;
2402 }
aa6943ca 2403
1972c7e3
T
2404 ++cur_idx;
2405 }
f76ae257
T
2406 for_each_bin_hdr_v0(bhdr, ptr) {
2407 if (idx == cur_idx) {
2408 image = (ulong)bhdr + bhdr->offset;
2409 size = bhdr->size;
2410 break;
2411 }
2412 ++cur_idx;
2413 }
aa6943ca 2414
1972c7e3
T
2415 if (!image) {
2416 fprintf(stderr, "Argument -p %d is invalid\n", idx);
2417 fprintf(stderr, "Available subimages:\n");
2418 fprintf(stderr, " -p -1 - kwbimage config file\n");
2419 fprintf(stderr, " -p 0 - data image\n");
2420 if (cur_idx - 1 > 0)
2421 fprintf(stderr, " -p N - Nth binary header image (totally: %d)\n",
2422 cur_idx - 1);
2423 return -1;
2424 }
2425 }
aa6943ca 2426
aa6943ca
T
2427 return imagetool_save_subimage(params->outfile, image, size);
2428}
2429
4acd2d24
SR
2430/*
2431 * Report Error if xflag is set in addition to default
2432 */
2433static int kwbimage_check_params(struct image_tool_params *params)
2434{
e65ea147 2435 if (!params->lflag && !params->iflag && !params->pflag &&
32860b00 2436 (!params->imagename || !strlen(params->imagename))) {
94490a4a
MS
2437 char *msg = "Configuration file for kwbimage creation omitted";
2438
2439 fprintf(stderr, "Error:%s - %s\n", params->cmdname, msg);
56087c1b 2440 return 1;
4acd2d24
SR
2441 }
2442
2443 return (params->dflag && (params->fflag || params->lflag)) ||
0201244c 2444 (params->fflag) ||
4acd2d24 2445 (params->lflag && (params->dflag || params->fflag)) ||
aa6943ca 2446 (params->xflag);
4acd2d24
SR
2447}
2448
aa0c7a86
PW
2449/*
2450 * kwbimage type parameters definition
2451 */
a93648d1
GMF
2452U_BOOT_IMAGE_TYPE(
2453 kwbimage,
2454 "Marvell MVEBU Boot Image support",
2455 0,
2456 NULL,
2457 kwbimage_check_params,
2458 kwbimage_verify_header,
2459 kwbimage_print_header,
2460 kwbimage_set_header,
aa6943ca 2461 kwbimage_extract_subimage,
a93648d1
GMF
2462 kwbimage_check_image_types,
2463 NULL,
2464 kwbimage_generate
2465);