1 // SPDX-License-Identifier: GPL-2.0+
3 * Image manipulator for Marvell SoCs
4 * supports Kirkwood, Dove, Armada 370, Armada XP, Armada 375, Armada 38x and
7 * (C) Copyright 2013 Thomas Petazzoni
8 * <thomas.petazzoni@free-electrons.com>
11 #define OPENSSL_API_COMPAT 0x10101000L
13 #include "imagetool.h"
20 #include <openssl/bn.h>
21 #include <openssl/rsa.h>
22 #include <openssl/pem.h>
23 #include <openssl/err.h>
24 #include <openssl/evp.h>
26 #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
27 (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL)
28 static void RSA_get0_key(const RSA *r,
29 const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
39 #elif !defined(LIBRESSL_VERSION_NUMBER)
40 void EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx)
42 EVP_MD_CTX_reset(ctx);
46 static struct image_cfg_element *image_cfg;
48 static int verbose_mode;
62 struct boot_mode boot_modes[] = {
63 { IBR_HDR_I2C_ID, "i2c" },
64 { IBR_HDR_SPI_ID, "spi" },
65 { IBR_HDR_NAND_ID, "nand" },
66 { IBR_HDR_SATA_ID, "sata" },
67 { IBR_HDR_PEX_ID, "pex" },
68 { IBR_HDR_UART_ID, "uart" },
69 { IBR_HDR_SDIO_ID, "sdio" },
73 struct nand_ecc_mode {
78 struct nand_ecc_mode nand_ecc_modes[] = {
79 { IBR_HDR_ECC_DEFAULT, "default" },
80 { IBR_HDR_ECC_FORCED_HAMMING, "hamming" },
81 { IBR_HDR_ECC_FORCED_RS, "rs" },
82 { IBR_HDR_ECC_DISABLED, "disabled" },
86 /* Used to identify an undefined execution or destination address */
87 #define ADDR_INVALID ((uint32_t)-1)
89 #define BINARY_MAX_ARGS 255
91 /* In-memory representation of a line of the configuration file */
94 IMAGE_CFG_VERSION = 0x1,
99 IMAGE_CFG_NAND_BADBLK_LOCATION,
100 IMAGE_CFG_NAND_ECC_MODE,
101 IMAGE_CFG_NAND_PAGESZ,
105 IMAGE_CFG_DATA_DELAY,
113 IMAGE_CFG_JTAG_DELAY,
116 IMAGE_CFG_SEC_COMMON_IMG,
117 IMAGE_CFG_SEC_SPECIALIZED_IMG,
118 IMAGE_CFG_SEC_BOOT_DEV,
119 IMAGE_CFG_SEC_FUSE_DUMP,
124 static const char * const id_strs[] = {
125 [IMAGE_CFG_VERSION] = "VERSION",
126 [IMAGE_CFG_BOOT_FROM] = "BOOT_FROM",
127 [IMAGE_CFG_DEST_ADDR] = "DEST_ADDR",
128 [IMAGE_CFG_EXEC_ADDR] = "EXEC_ADDR",
129 [IMAGE_CFG_NAND_BLKSZ] = "NAND_BLKSZ",
130 [IMAGE_CFG_NAND_BADBLK_LOCATION] = "NAND_BADBLK_LOCATION",
131 [IMAGE_CFG_NAND_ECC_MODE] = "NAND_ECC_MODE",
132 [IMAGE_CFG_NAND_PAGESZ] = "NAND_PAGE_SIZE",
133 [IMAGE_CFG_CPU] = "CPU",
134 [IMAGE_CFG_BINARY] = "BINARY",
135 [IMAGE_CFG_DATA] = "DATA",
136 [IMAGE_CFG_DATA_DELAY] = "DATA_DELAY",
137 [IMAGE_CFG_BAUDRATE] = "BAUDRATE",
138 [IMAGE_CFG_UART_PORT] = "UART_PORT",
139 [IMAGE_CFG_UART_MPP] = "UART_MPP",
140 [IMAGE_CFG_DEBUG] = "DEBUG",
141 [IMAGE_CFG_KAK] = "KAK",
142 [IMAGE_CFG_CSK] = "CSK",
143 [IMAGE_CFG_CSK_INDEX] = "CSK_INDEX",
144 [IMAGE_CFG_JTAG_DELAY] = "JTAG_DELAY",
145 [IMAGE_CFG_BOX_ID] = "BOX_ID",
146 [IMAGE_CFG_FLASH_ID] = "FLASH_ID",
147 [IMAGE_CFG_SEC_COMMON_IMG] = "SEC_COMMON_IMG",
148 [IMAGE_CFG_SEC_SPECIALIZED_IMG] = "SEC_SPECIALIZED_IMG",
149 [IMAGE_CFG_SEC_BOOT_DEV] = "SEC_BOOT_DEV",
150 [IMAGE_CFG_SEC_FUSE_DUMP] = "SEC_FUSE_DUMP"
153 struct image_cfg_element {
154 enum image_cfg_type type;
156 unsigned int version;
157 unsigned int cpu_sheeva;
158 unsigned int bootfrom;
161 unsigned int loadaddr;
162 unsigned int args[BINARY_MAX_ARGS];
165 unsigned int dstaddr;
166 unsigned int execaddr;
167 unsigned int nandblksz;
168 unsigned int nandbadblklocation;
169 unsigned int nandeccmode;
170 unsigned int nandpagesz;
171 struct ext_hdr_v0_reg regdata;
172 unsigned int regdata_delay;
173 unsigned int baudrate;
174 unsigned int uart_port;
175 unsigned int uart_mpp;
177 const char *key_name;
182 bool sec_specialized_img;
183 unsigned int sec_boot_dev;
188 #define IMAGE_CFG_ELEMENT_MAX 256
191 * Utility functions to manipulate boot mode and ecc modes (convert
192 * them back and forth between description strings and the
193 * corresponding numerical identifiers).
196 static const char *image_boot_mode_name(unsigned int id)
200 for (i = 0; boot_modes[i].name; i++)
201 if (boot_modes[i].id == id)
202 return boot_modes[i].name;
206 static int image_boot_mode_id(const char *boot_mode_name)
210 for (i = 0; boot_modes[i].name; i++)
211 if (!strcmp(boot_modes[i].name, boot_mode_name))
212 return boot_modes[i].id;
217 static const char *image_nand_ecc_mode_name(unsigned int id)
221 for (i = 0; nand_ecc_modes[i].name; i++)
222 if (nand_ecc_modes[i].id == id)
223 return nand_ecc_modes[i].name;
228 static int image_nand_ecc_mode_id(const char *nand_ecc_mode_name)
232 for (i = 0; nand_ecc_modes[i].name; i++)
233 if (!strcmp(nand_ecc_modes[i].name, nand_ecc_mode_name))
234 return nand_ecc_modes[i].id;
238 static struct image_cfg_element *
239 image_find_option(unsigned int optiontype)
243 for (i = 0; i < cfgn; i++) {
244 if (image_cfg[i].type == optiontype)
245 return &image_cfg[i];
252 image_count_options(unsigned int optiontype)
255 unsigned int count = 0;
257 for (i = 0; i < cfgn; i++)
258 if (image_cfg[i].type == optiontype)
264 static int image_get_csk_index(void)
266 struct image_cfg_element *e;
268 e = image_find_option(IMAGE_CFG_CSK_INDEX);
275 static bool image_get_spezialized_img(void)
277 struct image_cfg_element *e;
279 e = image_find_option(IMAGE_CFG_SEC_SPECIALIZED_IMG);
283 return e->sec_specialized_img;
286 static int image_get_bootfrom(void)
288 struct image_cfg_element *e;
290 e = image_find_option(IMAGE_CFG_BOOT_FROM);
292 /* fallback to SPI if no BOOT_FROM is not provided */
293 return IBR_HDR_SPI_ID;
298 static int image_is_cpu_sheeva(void)
300 struct image_cfg_element *e;
302 e = image_find_option(IMAGE_CFG_CPU);
306 return e->cpu_sheeva;
310 * Compute a 8-bit checksum of a memory area. This algorithm follows
311 * the requirements of the Marvell SoC BootROM specifications.
313 static uint8_t image_checksum8(void *start, uint32_t len)
318 /* check len and return zero checksum if invalid */
331 * Verify checksum over a complete header that includes the checksum field.
332 * Return 1 when OK, otherwise 0.
334 static int main_hdr_checksum_ok(void *hdr)
336 /* Offsets of checksum in v0 and v1 headers are the same */
337 struct main_hdr_v0 *main_hdr = (struct main_hdr_v0 *)hdr;
340 checksum = image_checksum8(hdr, kwbheader_size_for_csum(hdr));
341 /* Calculated checksum includes the header checksum field. Compensate
344 checksum -= main_hdr->checksum;
346 return checksum == main_hdr->checksum;
349 static uint32_t image_checksum32(void *start, uint32_t len)
354 /* check len and return zero checksum if invalid */
358 if (len % sizeof(uint32_t)) {
359 fprintf(stderr, "Length %d is not in multiple of %zu\n",
360 len, sizeof(uint32_t));
367 len -= sizeof(uint32_t);
373 static unsigned int options_to_baudrate(uint8_t options)
375 switch (options & 0x7) {
376 case MAIN_HDR_V1_OPT_BAUD_2400:
378 case MAIN_HDR_V1_OPT_BAUD_4800:
380 case MAIN_HDR_V1_OPT_BAUD_9600:
382 case MAIN_HDR_V1_OPT_BAUD_19200:
384 case MAIN_HDR_V1_OPT_BAUD_38400:
386 case MAIN_HDR_V1_OPT_BAUD_57600:
388 case MAIN_HDR_V1_OPT_BAUD_115200:
390 case MAIN_HDR_V1_OPT_BAUD_DEFAULT:
396 static uint8_t baudrate_to_option(unsigned int baudrate)
400 return MAIN_HDR_V1_OPT_BAUD_2400;
402 return MAIN_HDR_V1_OPT_BAUD_4800;
404 return MAIN_HDR_V1_OPT_BAUD_9600;
406 return MAIN_HDR_V1_OPT_BAUD_19200;
408 return MAIN_HDR_V1_OPT_BAUD_38400;
410 return MAIN_HDR_V1_OPT_BAUD_57600;
412 return MAIN_HDR_V1_OPT_BAUD_115200;
414 return MAIN_HDR_V1_OPT_BAUD_DEFAULT;
418 static void kwb_msg(const char *fmt, ...)
424 vfprintf(stdout, fmt, ap);
429 static int openssl_err(const char *msg)
431 unsigned long ssl_err = ERR_get_error();
433 fprintf(stderr, "%s", msg);
434 fprintf(stderr, ": %s\n",
435 ERR_error_string(ssl_err, 0));
440 static int kwb_load_rsa_key(const char *keydir, const char *name, RSA **p_rsa)
449 snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
450 f = fopen(path, "r");
452 fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
453 path, strerror(errno));
457 rsa = PEM_read_RSAPrivateKey(f, 0, NULL, "");
459 openssl_err("Failure reading private key");
469 static int kwb_load_cfg_key(struct image_tool_params *params,
470 unsigned int cfg_option, const char *key_name,
473 struct image_cfg_element *e_key;
479 e_key = image_find_option(cfg_option);
481 fprintf(stderr, "%s not configured\n", key_name);
485 res = kwb_load_rsa_key(params->keydir, e_key->key_name, &key);
487 fprintf(stderr, "Failed to load %s\n", key_name);
496 static int kwb_load_kak(struct image_tool_params *params, RSA **p_kak)
498 return kwb_load_cfg_key(params, IMAGE_CFG_KAK, "KAK", p_kak);
501 static int kwb_load_csk(struct image_tool_params *params, RSA **p_csk)
503 return kwb_load_cfg_key(params, IMAGE_CFG_CSK, "CSK", p_csk);
506 static int kwb_compute_pubkey_hash(struct pubkey_der_v1 *pk,
507 struct hash_v1 *hash)
510 unsigned int key_size;
511 unsigned int hash_size;
514 if (!pk || !hash || pk->key[0] != 0x30 || pk->key[1] != 0x82)
517 key_size = (pk->key[2] << 8) + pk->key[3] + 4;
519 ctx = EVP_MD_CTX_create();
521 return openssl_err("EVP context creation failed");
523 EVP_MD_CTX_init(ctx);
524 if (!EVP_DigestInit(ctx, EVP_sha256())) {
525 ret = openssl_err("Digest setup failed");
529 if (!EVP_DigestUpdate(ctx, pk->key, key_size)) {
530 ret = openssl_err("Hashing data failed");
534 if (!EVP_DigestFinal(ctx, hash->hash, &hash_size)) {
535 ret = openssl_err("Could not obtain hash");
539 EVP_MD_CTX_cleanup(ctx);
542 EVP_MD_CTX_destroy(ctx);
546 static int kwb_import_pubkey(RSA **key, struct pubkey_der_v1 *src, char *keyname)
549 const unsigned char *ptr;
555 rsa = d2i_RSAPublicKey(key, &ptr, sizeof(src->key));
557 openssl_err("error decoding public key");
563 fprintf(stderr, "Failed to decode %s pubkey\n", keyname);
567 static int kwb_export_pubkey(RSA *key, struct pubkey_der_v1 *dst, FILE *hashf,
570 int size_exp, size_mod, size_seq;
571 const BIGNUM *key_e, *key_n;
573 char *errmsg = "Failed to encode %s\n";
575 RSA_get0_key(key, NULL, &key_e, NULL);
576 RSA_get0_key(key, &key_n, NULL, NULL);
578 if (!key || !key_e || !key_n || !dst) {
579 fprintf(stderr, "export pk failed: (%p, %p, %p, %p)",
580 key, key_e, key_n, dst);
581 fprintf(stderr, errmsg, keyname);
586 * According to the specs, the key should be PKCS#1 DER encoded.
587 * But unfortunately the really required encoding seems to be different;
588 * it violates DER...! (But it still conformes to BER.)
589 * (Length always in long form w/ 2 byte length code; no leading zero
590 * when MSB of first byte is set...)
591 * So we cannot use the encoding func provided by OpenSSL and have to
592 * do the encoding manually.
595 size_exp = BN_num_bytes(key_e);
596 size_mod = BN_num_bytes(key_n);
597 size_seq = 4 + size_mod + 4 + size_exp;
599 if (size_mod > 256) {
600 fprintf(stderr, "export pk failed: wrong mod size: %d\n",
602 fprintf(stderr, errmsg, keyname);
606 if (4 + size_seq > sizeof(dst->key)) {
607 fprintf(stderr, "export pk failed: seq too large (%d, %zu)\n",
608 4 + size_seq, sizeof(dst->key));
609 fprintf(stderr, errmsg, keyname);
615 /* PKCS#1 (RFC3447) RSAPublicKey structure */
616 *cur++ = 0x30; /* SEQUENCE */
618 *cur++ = (size_seq >> 8) & 0xFF;
619 *cur++ = size_seq & 0xFF;
621 *cur++ = 0x02; /* INTEGER */
623 *cur++ = (size_mod >> 8) & 0xFF;
624 *cur++ = size_mod & 0xFF;
625 BN_bn2bin(key_n, cur);
628 *cur++ = 0x02; /* INTEGER */
630 *cur++ = (size_exp >> 8) & 0xFF;
631 *cur++ = size_exp & 0xFF;
632 BN_bn2bin(key_e, cur);
635 struct hash_v1 pk_hash;
639 ret = kwb_compute_pubkey_hash(dst, &pk_hash);
641 fprintf(stderr, errmsg, keyname);
645 fprintf(hashf, "SHA256 = ");
646 for (i = 0 ; i < sizeof(pk_hash.hash); ++i)
647 fprintf(hashf, "%02X", pk_hash.hash[i]);
648 fprintf(hashf, "\n");
654 static int kwb_sign(RSA *key, void *data, int datasz, struct sig_v1 *sig,
659 unsigned int sig_size;
663 evp_key = EVP_PKEY_new();
665 return openssl_err("EVP_PKEY object creation failed");
667 if (!EVP_PKEY_set1_RSA(evp_key, key)) {
668 ret = openssl_err("EVP key setup failed");
672 size = EVP_PKEY_size(evp_key);
673 if (size > sizeof(sig->sig)) {
674 fprintf(stderr, "Buffer to small for signature (%d bytes)\n",
680 ctx = EVP_MD_CTX_create();
682 ret = openssl_err("EVP context creation failed");
685 EVP_MD_CTX_init(ctx);
686 if (!EVP_SignInit(ctx, EVP_sha256())) {
687 ret = openssl_err("Signer setup failed");
691 if (!EVP_SignUpdate(ctx, data, datasz)) {
692 ret = openssl_err("Signing data failed");
696 if (!EVP_SignFinal(ctx, sig->sig, &sig_size, evp_key)) {
697 ret = openssl_err("Could not obtain signature");
701 EVP_MD_CTX_cleanup(ctx);
702 EVP_MD_CTX_destroy(ctx);
703 EVP_PKEY_free(evp_key);
708 EVP_MD_CTX_destroy(ctx);
710 EVP_PKEY_free(evp_key);
711 fprintf(stderr, "Failed to create %s signature\n", signame);
715 static int kwb_verify(RSA *key, void *data, int datasz, struct sig_v1 *sig,
723 evp_key = EVP_PKEY_new();
725 return openssl_err("EVP_PKEY object creation failed");
727 if (!EVP_PKEY_set1_RSA(evp_key, key)) {
728 ret = openssl_err("EVP key setup failed");
732 size = EVP_PKEY_size(evp_key);
733 if (size > sizeof(sig->sig)) {
734 fprintf(stderr, "Invalid signature size (%d bytes)\n",
740 ctx = EVP_MD_CTX_create();
742 ret = openssl_err("EVP context creation failed");
745 EVP_MD_CTX_init(ctx);
746 if (!EVP_VerifyInit(ctx, EVP_sha256())) {
747 ret = openssl_err("Verifier setup failed");
751 if (!EVP_VerifyUpdate(ctx, data, datasz)) {
752 ret = openssl_err("Hashing data failed");
756 if (EVP_VerifyFinal(ctx, sig->sig, sizeof(sig->sig), evp_key) != 1) {
757 ret = openssl_err("Could not verify signature");
761 EVP_MD_CTX_cleanup(ctx);
762 EVP_MD_CTX_destroy(ctx);
763 EVP_PKEY_free(evp_key);
768 EVP_MD_CTX_destroy(ctx);
770 EVP_PKEY_free(evp_key);
771 fprintf(stderr, "Failed to verify %s signature\n", signame);
775 static int kwb_sign_and_verify(RSA *key, void *data, int datasz,
776 struct sig_v1 *sig, char *signame)
778 if (kwb_sign(key, data, datasz, sig, signame) < 0)
781 if (kwb_verify(key, data, datasz, sig, signame) < 0)
788 static int kwb_dump_fuse_cmds_38x(FILE *out, struct secure_hdr_v1 *sec_hdr)
790 struct hash_v1 kak_pub_hash;
791 struct image_cfg_element *e;
792 unsigned int fuse_line;
798 if (!out || !sec_hdr)
801 ret = kwb_compute_pubkey_hash(&sec_hdr->kak, &kak_pub_hash);
805 fprintf(out, "# burn KAK pub key hash\n");
806 ptr = kak_pub_hash.hash;
807 for (fuse_line = 26; fuse_line <= 30; ++fuse_line) {
808 fprintf(out, "fuse prog -y %u 0 ", fuse_line);
810 for (i = 4; i-- > 0;)
811 fprintf(out, "%02hx", (ushort)ptr[i]);
815 if (fuse_line < 30) {
816 for (i = 3; i-- > 0;)
817 fprintf(out, "%02hx", (ushort)ptr[i]);
820 fprintf(out, "000000");
823 fprintf(out, " 1\n");
826 fprintf(out, "# burn CSK selection\n");
828 idx = image_get_csk_index();
829 if (idx < 0 || idx > 15) {
834 for (fuse_line = 31; fuse_line < 31 + idx; ++fuse_line)
835 fprintf(out, "fuse prog -y %u 0 00000001 00000000 1\n",
838 fprintf(out, "# CSK index is 0; no mods needed\n");
841 e = image_find_option(IMAGE_CFG_BOX_ID);
843 fprintf(out, "# set box ID\n");
844 fprintf(out, "fuse prog -y 48 0 %08x 00000000 1\n", e->boxid);
847 e = image_find_option(IMAGE_CFG_FLASH_ID);
849 fprintf(out, "# set flash ID\n");
850 fprintf(out, "fuse prog -y 47 0 %08x 00000000 1\n", e->flashid);
853 fprintf(out, "# enable secure mode ");
854 fprintf(out, "(must be the last fuse line written)\n");
857 e = image_find_option(IMAGE_CFG_SEC_BOOT_DEV);
859 fprintf(stderr, "ERROR: secured mode boot device not given\n");
864 if (e->sec_boot_dev > 0xff) {
865 fprintf(stderr, "ERROR: secured mode boot device invalid\n");
870 val |= (e->sec_boot_dev << 8);
872 fprintf(out, "fuse prog -y 24 0 %08x 0103e0a9 1\n", val);
874 fprintf(out, "# lock (unused) fuse lines (0-23)s\n");
875 for (fuse_line = 0; fuse_line < 24; ++fuse_line)
876 fprintf(out, "fuse prog -y %u 2 1\n", fuse_line);
878 fprintf(out, "# OK, that's all :-)\n");
884 static int kwb_dump_fuse_cmds(struct secure_hdr_v1 *sec_hdr)
887 struct image_cfg_element *e;
889 e = image_find_option(IMAGE_CFG_SEC_FUSE_DUMP);
893 if (!strcmp(e->name, "a38x")) {
894 FILE *out = fopen("kwb_fuses_a38x.txt", "w+");
897 fprintf(stderr, "Couldn't open eFuse settings: '%s': %s\n",
898 "kwb_fuses_a38x.txt", strerror(errno));
902 kwb_dump_fuse_cmds_38x(out, sec_hdr);
913 static size_t image_headersz_align(size_t headersz, uint8_t blockid)
916 * Header needs to be 4-byte aligned, which is already ensured by code
917 * above. Moreover UART images must have header aligned to 128 bytes
918 * (xmodem block size), NAND images to 256 bytes (ECC calculation),
919 * and SATA and SDIO images to 512 bytes (storage block size).
920 * Note that SPI images do not have to have header size aligned
921 * to 256 bytes because it is possible to read from SPI storage from
922 * any offset (read offset does not have to be aligned to block size).
924 if (blockid == IBR_HDR_UART_ID)
925 return ALIGN(headersz, 128);
926 else if (blockid == IBR_HDR_NAND_ID)
927 return ALIGN(headersz, 256);
928 else if (blockid == IBR_HDR_SATA_ID || blockid == IBR_HDR_SDIO_ID)
929 return ALIGN(headersz, 512);
934 static size_t image_headersz_v0(int *hasext)
938 headersz = sizeof(struct main_hdr_v0);
939 if (image_count_options(IMAGE_CFG_DATA) > 0) {
940 headersz += sizeof(struct ext_hdr_v0);
945 return image_headersz_align(headersz, image_get_bootfrom());
948 static void *image_create_v0(size_t *imagesz, struct image_tool_params *params,
951 struct image_cfg_element *e;
953 struct main_hdr_v0 *main_hdr;
958 * Calculate the size of the header and the size of the
961 headersz = image_headersz_v0(&has_ext);
963 image = malloc(headersz);
965 fprintf(stderr, "Cannot allocate memory for image\n");
969 memset(image, 0, headersz);
971 main_hdr = (struct main_hdr_v0 *)image;
973 /* Fill in the main header */
974 main_hdr->blocksize =
975 cpu_to_le32(payloadsz);
976 main_hdr->srcaddr = cpu_to_le32(headersz);
977 main_hdr->ext = has_ext;
978 main_hdr->version = 0;
979 main_hdr->destaddr = cpu_to_le32(params->addr);
980 main_hdr->execaddr = cpu_to_le32(params->ep);
981 main_hdr->blockid = image_get_bootfrom();
983 e = image_find_option(IMAGE_CFG_NAND_ECC_MODE);
985 main_hdr->nandeccmode = e->nandeccmode;
986 e = image_find_option(IMAGE_CFG_NAND_PAGESZ);
988 main_hdr->nandpagesize = cpu_to_le16(e->nandpagesz);
989 main_hdr->checksum = image_checksum8(image,
990 sizeof(struct main_hdr_v0));
993 * For SATA srcaddr is specified in number of sectors starting from
994 * sector 0. The main header is stored at sector number 1.
995 * This expects the sector size to be 512 bytes.
996 * Header size is already aligned.
998 if (main_hdr->blockid == IBR_HDR_SATA_ID)
999 main_hdr->srcaddr = cpu_to_le32(headersz / 512 + 1);
1002 * For SDIO srcaddr is specified in number of sectors starting from
1003 * sector 0. The main header is stored at sector number 0.
1004 * This expects sector size to be 512 bytes.
1005 * Header size is already aligned.
1007 if (main_hdr->blockid == IBR_HDR_SDIO_ID)
1008 main_hdr->srcaddr = cpu_to_le32(headersz / 512);
1010 /* For PCIe srcaddr is not used and must be set to 0xFFFFFFFF. */
1011 if (main_hdr->blockid == IBR_HDR_PEX_ID)
1012 main_hdr->srcaddr = cpu_to_le32(0xFFFFFFFF);
1014 /* Generate the ext header */
1016 struct ext_hdr_v0 *ext_hdr;
1019 ext_hdr = (struct ext_hdr_v0 *)
1020 (image + sizeof(struct main_hdr_v0));
1021 ext_hdr->offset = cpu_to_le32(0x40);
1023 for (cfgi = 0, datai = 0; cfgi < cfgn; cfgi++) {
1024 e = &image_cfg[cfgi];
1025 if (e->type != IMAGE_CFG_DATA)
1028 ext_hdr->rcfg[datai].raddr =
1029 cpu_to_le32(e->regdata.raddr);
1030 ext_hdr->rcfg[datai].rdata =
1031 cpu_to_le32(e->regdata.rdata);
1035 ext_hdr->checksum = image_checksum8(ext_hdr,
1036 sizeof(struct ext_hdr_v0));
1039 *imagesz = headersz;
1043 static size_t image_headersz_v1(int *hasext)
1045 struct image_cfg_element *e;
1054 * Calculate the size of the header and the size of the
1057 headersz = sizeof(struct main_hdr_v1);
1059 if (image_get_csk_index() >= 0) {
1060 headersz += sizeof(struct secure_hdr_v1);
1065 cpu_sheeva = image_is_cpu_sheeva();
1068 for (cfgi = 0; cfgi < cfgn; cfgi++) {
1069 e = &image_cfg[cfgi];
1071 if (e->type == IMAGE_CFG_DATA)
1074 if (e->type == IMAGE_CFG_DATA_DELAY ||
1075 (e->type == IMAGE_CFG_BINARY && count > 0)) {
1076 headersz += sizeof(struct register_set_hdr_v1) + 8 * count + 4;
1080 if (e->type != IMAGE_CFG_BINARY)
1083 ret = stat(e->binary.file, &s);
1088 memset(cwd, 0, sizeof(cwd));
1089 if (!getcwd(cwd, sizeof(cwd))) {
1090 dir = "current working directory";
1091 perror("getcwd() failed");
1095 "Didn't find the file '%s' in '%s' which is mandatory to generate the image\n"
1096 "This file generally contains the DDR3 training code, and should be extracted from an existing bootable\n"
1097 "image for your board. Use 'dumpimage -T kwbimage -p 0' to extract it from an existing image.\n",
1098 e->binary.file, dir);
1102 headersz += sizeof(struct opt_hdr_v1) + sizeof(uint32_t) +
1103 (e->binary.nargs) * sizeof(uint32_t);
1105 if (e->binary.loadaddr) {
1107 * BootROM loads kwbimage header (in which the
1108 * executable code is also stored) to address
1109 * 0x40004000 or 0x40000000. Thus there is
1110 * restriction for the load address of the N-th
1113 unsigned int base_addr, low_addr, high_addr;
1115 base_addr = cpu_sheeva ? 0x40004000 : 0x40000000;
1116 low_addr = base_addr + headersz;
1117 high_addr = low_addr +
1118 (BINARY_MAX_ARGS - e->binary.nargs) * sizeof(uint32_t);
1120 if (cpu_sheeva && e->binary.loadaddr % 16) {
1122 "Invalid LOAD_ADDRESS 0x%08x for BINARY %s with %d args.\n"
1123 "Address for CPU SHEEVA must be 16-byte aligned.\n",
1124 e->binary.loadaddr, e->binary.file, e->binary.nargs);
1128 if (e->binary.loadaddr % 4 || e->binary.loadaddr < low_addr ||
1129 e->binary.loadaddr > high_addr) {
1131 "Invalid LOAD_ADDRESS 0x%08x for BINARY %s with %d args.\n"
1132 "Address must be 4-byte aligned and in range 0x%08x-0x%08x.\n",
1133 e->binary.loadaddr, e->binary.file,
1134 e->binary.nargs, low_addr, high_addr);
1137 headersz = e->binary.loadaddr - base_addr;
1138 } else if (cpu_sheeva) {
1139 headersz = ALIGN(headersz, 16);
1141 headersz = ALIGN(headersz, 4);
1144 headersz += ALIGN(s.st_size, 4) + sizeof(uint32_t);
1150 headersz += sizeof(struct register_set_hdr_v1) + 8 * count + 4;
1152 return image_headersz_align(headersz, image_get_bootfrom());
1155 static int add_binary_header_v1(uint8_t **cur, uint8_t **next_ext,
1156 struct image_cfg_element *binarye,
1157 struct main_hdr_v1 *main_hdr)
1159 struct opt_hdr_v1 *hdr = (struct opt_hdr_v1 *)*cur;
1171 hdr->headertype = OPT_HDR_V1_BINARY_TYPE;
1173 bin = fopen(binarye->binary.file, "r");
1175 fprintf(stderr, "Cannot open binary file %s\n",
1176 binarye->binary.file);
1180 if (fstat(fileno(bin), &s)) {
1181 fprintf(stderr, "Cannot stat binary file %s\n",
1182 binarye->binary.file);
1186 *cur += sizeof(struct opt_hdr_v1);
1188 args = (uint32_t *)*cur;
1189 *args = cpu_to_le32(binarye->binary.nargs);
1191 for (argi = 0; argi < binarye->binary.nargs; argi++)
1192 args[argi] = cpu_to_le32(binarye->binary.args[argi]);
1194 *cur += (binarye->binary.nargs + 1) * sizeof(uint32_t);
1197 * ARM executable code inside the BIN header on platforms with Sheeva
1198 * CPU (A370 and AXP) must always be aligned with the 128-bit boundary.
1199 * In the case when this code is not position independent (e.g. ARM
1200 * SPL), it must be placed at fixed load and execute address.
1201 * This requirement can be met by inserting dummy arguments into
1202 * BIN header, if needed.
1204 cpu_sheeva = image_is_cpu_sheeva();
1205 base_addr = cpu_sheeva ? 0x40004000 : 0x40000000;
1206 offset = *cur - (uint8_t *)main_hdr;
1207 if (binarye->binary.loadaddr)
1208 add_args = (binarye->binary.loadaddr - base_addr - offset) / sizeof(uint32_t);
1209 else if (cpu_sheeva)
1210 add_args = ((16 - offset % 16) % 16) / sizeof(uint32_t);
1214 *(args - 1) = cpu_to_le32(binarye->binary.nargs + add_args);
1215 *cur += add_args * sizeof(uint32_t);
1218 ret = fread(*cur, s.st_size, 1, bin);
1221 "Could not read binary image %s\n",
1222 binarye->binary.file);
1228 *cur += ALIGN(s.st_size, 4);
1230 *((uint32_t *)*cur) = 0x00000000;
1234 *cur += sizeof(uint32_t);
1236 binhdrsz = sizeof(struct opt_hdr_v1) +
1237 (binarye->binary.nargs + add_args + 2) * sizeof(uint32_t) +
1238 ALIGN(s.st_size, 4);
1239 hdr->headersz_lsb = cpu_to_le16(binhdrsz & 0xFFFF);
1240 hdr->headersz_msb = (binhdrsz & 0xFFFF0000) >> 16;
1250 static int export_pub_kak_hash(RSA *kak, struct secure_hdr_v1 *secure_hdr)
1255 hashf = fopen("pub_kak_hash.txt", "w");
1257 fprintf(stderr, "Couldn't open hash file: '%s': %s\n",
1258 "pub_kak_hash.txt", strerror(errno));
1262 res = kwb_export_pubkey(kak, &secure_hdr->kak, hashf, "KAK");
1266 return res < 0 ? 1 : 0;
1269 static int kwb_sign_csk_with_kak(struct image_tool_params *params,
1270 struct secure_hdr_v1 *secure_hdr, RSA *csk)
1273 RSA *kak_pub = NULL;
1274 int csk_idx = image_get_csk_index();
1275 struct sig_v1 tmp_sig;
1277 if (csk_idx < 0 || csk_idx > 15) {
1278 fprintf(stderr, "Invalid CSK index %d\n", csk_idx);
1282 if (kwb_load_kak(params, &kak) < 0)
1285 if (export_pub_kak_hash(kak, secure_hdr))
1288 if (kwb_import_pubkey(&kak_pub, &secure_hdr->kak, "KAK") < 0)
1291 if (kwb_export_pubkey(csk, &secure_hdr->csk[csk_idx], NULL, "CSK") < 0)
1294 if (kwb_sign_and_verify(kak, &secure_hdr->csk,
1295 sizeof(secure_hdr->csk) +
1296 sizeof(secure_hdr->csksig),
1297 &tmp_sig, "CSK") < 0)
1300 if (kwb_verify(kak_pub, &secure_hdr->csk,
1301 sizeof(secure_hdr->csk) +
1302 sizeof(secure_hdr->csksig),
1303 &tmp_sig, "CSK (2)") < 0)
1306 secure_hdr->csksig = tmp_sig;
1311 static int add_secure_header_v1(struct image_tool_params *params, uint8_t *ptr,
1312 int payloadsz, size_t headersz, uint8_t *image,
1313 struct secure_hdr_v1 *secure_hdr)
1315 struct image_cfg_element *e_jtagdelay;
1316 struct image_cfg_element *e_boxid;
1317 struct image_cfg_element *e_flashid;
1319 unsigned char *image_ptr;
1321 struct sig_v1 tmp_sig;
1322 bool specialized_img = image_get_spezialized_img();
1324 kwb_msg("Create secure header content\n");
1326 e_jtagdelay = image_find_option(IMAGE_CFG_JTAG_DELAY);
1327 e_boxid = image_find_option(IMAGE_CFG_BOX_ID);
1328 e_flashid = image_find_option(IMAGE_CFG_FLASH_ID);
1330 if (kwb_load_csk(params, &csk) < 0)
1333 secure_hdr->headertype = OPT_HDR_V1_SECURE_TYPE;
1334 secure_hdr->headersz_msb = 0;
1335 secure_hdr->headersz_lsb = cpu_to_le16(sizeof(struct secure_hdr_v1));
1337 secure_hdr->jtag_delay = e_jtagdelay->jtag_delay;
1338 if (e_boxid && specialized_img)
1339 secure_hdr->boxid = cpu_to_le32(e_boxid->boxid);
1340 if (e_flashid && specialized_img)
1341 secure_hdr->flashid = cpu_to_le32(e_flashid->flashid);
1343 if (kwb_sign_csk_with_kak(params, secure_hdr, csk))
1346 image_ptr = ptr + headersz;
1347 image_size = payloadsz - headersz;
1349 if (kwb_sign_and_verify(csk, image_ptr, image_size,
1350 &secure_hdr->imgsig, "image") < 0)
1353 if (kwb_sign_and_verify(csk, image, headersz, &tmp_sig, "header") < 0)
1356 secure_hdr->hdrsig = tmp_sig;
1358 kwb_dump_fuse_cmds(secure_hdr);
1363 static void finish_register_set_header_v1(uint8_t **cur, uint8_t **next_ext,
1364 struct register_set_hdr_v1 *register_set_hdr,
1365 int *datai, uint8_t delay)
1367 int size = sizeof(struct register_set_hdr_v1) + 8 * (*datai) + 4;
1369 register_set_hdr->headertype = OPT_HDR_V1_REGISTER_TYPE;
1370 register_set_hdr->headersz_lsb = cpu_to_le16(size & 0xFFFF);
1371 register_set_hdr->headersz_msb = size >> 16;
1372 register_set_hdr->data[*datai].last_entry.delay = delay;
1375 *next_ext = ®ister_set_hdr->data[*datai].last_entry.next;
1379 static void *image_create_v1(size_t *imagesz, struct image_tool_params *params,
1380 uint8_t *ptr, int payloadsz)
1382 struct image_cfg_element *e;
1383 struct main_hdr_v1 *main_hdr;
1384 struct opt_hdr_v1 *ohdr;
1385 struct register_set_hdr_v1 *register_set_hdr;
1386 struct secure_hdr_v1 *secure_hdr = NULL;
1388 uint8_t *image, *cur;
1390 uint8_t *next_ext = NULL;
1395 * Calculate the size of the header and the size of the
1398 headersz = image_headersz_v1(&hasext);
1402 image = malloc(headersz);
1404 fprintf(stderr, "Cannot allocate memory for image\n");
1408 memset(image, 0, headersz);
1410 main_hdr = (struct main_hdr_v1 *)image;
1412 cur += sizeof(struct main_hdr_v1);
1413 next_ext = &main_hdr->ext;
1415 /* Fill the main header */
1416 main_hdr->blocksize =
1417 cpu_to_le32(payloadsz);
1418 main_hdr->headersz_lsb = cpu_to_le16(headersz & 0xFFFF);
1419 main_hdr->headersz_msb = (headersz & 0xFFFF0000) >> 16;
1420 main_hdr->destaddr = cpu_to_le32(params->addr);
1421 main_hdr->execaddr = cpu_to_le32(params->ep);
1422 main_hdr->srcaddr = cpu_to_le32(headersz);
1423 main_hdr->ext = hasext;
1424 main_hdr->version = 1;
1425 main_hdr->blockid = image_get_bootfrom();
1427 e = image_find_option(IMAGE_CFG_NAND_BLKSZ);
1429 main_hdr->nandblocksize = e->nandblksz / (64 * 1024);
1430 e = image_find_option(IMAGE_CFG_NAND_PAGESZ);
1432 main_hdr->nandpagesize = cpu_to_le16(e->nandpagesz);
1433 e = image_find_option(IMAGE_CFG_NAND_BADBLK_LOCATION);
1435 main_hdr->nandbadblklocation = e->nandbadblklocation;
1436 e = image_find_option(IMAGE_CFG_BAUDRATE);
1438 main_hdr->options |= baudrate_to_option(e->baudrate);
1439 e = image_find_option(IMAGE_CFG_UART_PORT);
1441 main_hdr->options |= (e->uart_port & 3) << 3;
1442 e = image_find_option(IMAGE_CFG_UART_MPP);
1444 main_hdr->options |= (e->uart_mpp & 7) << 5;
1445 e = image_find_option(IMAGE_CFG_DEBUG);
1447 main_hdr->flags = e->debug ? 0x1 : 0;
1450 * For SATA srcaddr is specified in number of sectors starting from
1451 * sector 0. The main header is stored at sector number 1.
1452 * This expects the sector size to be 512 bytes.
1453 * Header size is already aligned.
1455 if (main_hdr->blockid == IBR_HDR_SATA_ID)
1456 main_hdr->srcaddr = cpu_to_le32(headersz / 512 + 1);
1459 * For SDIO srcaddr is specified in number of sectors starting from
1460 * sector 0. The main header is stored at sector number 0.
1461 * This expects sector size to be 512 bytes.
1462 * Header size is already aligned.
1464 if (main_hdr->blockid == IBR_HDR_SDIO_ID)
1465 main_hdr->srcaddr = cpu_to_le32(headersz / 512);
1467 /* For PCIe srcaddr is not used and must be set to 0xFFFFFFFF. */
1468 if (main_hdr->blockid == IBR_HDR_PEX_ID)
1469 main_hdr->srcaddr = cpu_to_le32(0xFFFFFFFF);
1471 if (image_get_csk_index() >= 0) {
1473 * only reserve the space here; we fill the header later since
1474 * we need the header to be complete to compute the signatures
1476 secure_hdr = (struct secure_hdr_v1 *)cur;
1477 cur += sizeof(struct secure_hdr_v1);
1479 next_ext = &secure_hdr->next;
1483 for (cfgi = 0; cfgi < cfgn; cfgi++) {
1484 e = &image_cfg[cfgi];
1485 if (e->type != IMAGE_CFG_DATA &&
1486 e->type != IMAGE_CFG_DATA_DELAY &&
1487 e->type != IMAGE_CFG_BINARY)
1491 register_set_hdr = (struct register_set_hdr_v1 *)cur;
1493 /* If delay is not specified, use the smallest possible value. */
1494 if (e->type == IMAGE_CFG_DATA_DELAY)
1495 delay = e->regdata_delay;
1497 delay = REGISTER_SET_HDR_OPT_DELAY_MS(0);
1500 * DATA_DELAY command is the last entry in the register set
1501 * header and BINARY command inserts new binary header.
1502 * Therefore BINARY command requires to finish register set
1503 * header if some DATA command was specified. And DATA_DELAY
1504 * command automatically finish register set header even when
1505 * there was no DATA command.
1507 if (e->type == IMAGE_CFG_DATA_DELAY ||
1508 (e->type == IMAGE_CFG_BINARY && datai != 0))
1509 finish_register_set_header_v1(&cur, &next_ext, register_set_hdr,
1512 if (e->type == IMAGE_CFG_DATA) {
1513 register_set_hdr->data[datai].entry.address =
1514 cpu_to_le32(e->regdata.raddr);
1515 register_set_hdr->data[datai].entry.value =
1516 cpu_to_le32(e->regdata.rdata);
1520 if (e->type == IMAGE_CFG_BINARY) {
1521 if (add_binary_header_v1(&cur, &next_ext, e, main_hdr))
1526 /* Set delay to the smallest possible value. */
1527 delay = REGISTER_SET_HDR_OPT_DELAY_MS(0);
1528 finish_register_set_header_v1(&cur, &next_ext, register_set_hdr,
1532 if (secure_hdr && add_secure_header_v1(params, ptr, payloadsz + headersz,
1533 headersz, image, secure_hdr))
1536 *imagesz = headersz;
1538 /* Fill the real header size without padding into the main header */
1539 headersz = sizeof(*main_hdr);
1540 for_each_opt_hdr_v1 (ohdr, main_hdr)
1541 headersz += opt_hdr_v1_size(ohdr);
1542 main_hdr->headersz_lsb = cpu_to_le16(headersz & 0xFFFF);
1543 main_hdr->headersz_msb = (headersz & 0xFFFF0000) >> 16;
1545 /* Calculate and set the header checksum */
1546 main_hdr->checksum = image_checksum8(main_hdr, headersz);
1551 static int recognize_keyword(char *keyword)
1555 for (kw_id = 1; kw_id < IMAGE_CFG_COUNT; ++kw_id)
1556 if (!strcmp(keyword, id_strs[kw_id]))
1562 static int image_create_config_parse_oneline(char *line,
1563 struct image_cfg_element *el)
1565 char *keyword, *saveptr, *value1, *value2;
1566 char delimiters[] = " \t";
1567 int keyword_id, ret, argi;
1568 char *unknown_msg = "Ignoring unknown line '%s'\n";
1570 keyword = strtok_r(line, delimiters, &saveptr);
1571 keyword_id = recognize_keyword(keyword);
1574 fprintf(stderr, unknown_msg, line);
1578 el->type = keyword_id;
1580 value1 = strtok_r(NULL, delimiters, &saveptr);
1583 fprintf(stderr, "Parameter missing in line '%s'\n", line);
1587 switch (keyword_id) {
1588 case IMAGE_CFG_VERSION:
1589 el->version = atoi(value1);
1592 if (strcmp(value1, "FEROCEON") == 0)
1594 else if (strcmp(value1, "SHEEVA") == 0)
1596 else if (strcmp(value1, "A9") == 0)
1599 fprintf(stderr, "Invalid CPU %s\n", value1);
1603 case IMAGE_CFG_BOOT_FROM:
1604 ret = image_boot_mode_id(value1);
1607 fprintf(stderr, "Invalid boot media '%s'\n", value1);
1612 case IMAGE_CFG_NAND_BLKSZ:
1613 el->nandblksz = strtoul(value1, NULL, 16);
1615 case IMAGE_CFG_NAND_BADBLK_LOCATION:
1616 el->nandbadblklocation = strtoul(value1, NULL, 16);
1618 case IMAGE_CFG_NAND_ECC_MODE:
1619 ret = image_nand_ecc_mode_id(value1);
1622 fprintf(stderr, "Invalid NAND ECC mode '%s'\n", value1);
1625 el->nandeccmode = ret;
1627 case IMAGE_CFG_NAND_PAGESZ:
1628 el->nandpagesz = strtoul(value1, NULL, 16);
1630 case IMAGE_CFG_BINARY:
1633 el->binary.file = strdup(value1);
1635 char *value = strtok_r(NULL, delimiters, &saveptr);
1641 if (!strcmp(value, "LOAD_ADDRESS")) {
1642 value = strtok_r(NULL, delimiters, &saveptr);
1645 "Missing address argument for BINARY LOAD_ADDRESS\n");
1648 el->binary.loadaddr = strtoul(value, &endptr, 16);
1651 "Invalid argument '%s' for BINARY LOAD_ADDRESS\n",
1655 value = strtok_r(NULL, delimiters, &saveptr);
1658 "Unexpected argument '%s' after BINARY LOAD_ADDRESS\n",
1665 el->binary.args[argi] = strtoul(value, &endptr, 16);
1667 fprintf(stderr, "Invalid argument '%s' for BINARY\n", value);
1671 if (argi >= BINARY_MAX_ARGS) {
1673 "Too many arguments for BINARY\n");
1677 el->binary.nargs = argi;
1679 case IMAGE_CFG_DATA:
1680 value2 = strtok_r(NULL, delimiters, &saveptr);
1682 if (!value1 || !value2) {
1684 "Invalid number of arguments for DATA\n");
1688 el->regdata.raddr = strtoul(value1, NULL, 16);
1689 el->regdata.rdata = strtoul(value2, NULL, 16);
1691 case IMAGE_CFG_DATA_DELAY:
1692 if (!strcmp(value1, "SDRAM_SETUP"))
1693 el->regdata_delay = REGISTER_SET_HDR_OPT_DELAY_SDRAM_SETUP;
1695 el->regdata_delay = REGISTER_SET_HDR_OPT_DELAY_MS(strtoul(value1, NULL, 10));
1696 if (el->regdata_delay > 255) {
1697 fprintf(stderr, "Maximal DATA_DELAY is 255\n");
1701 case IMAGE_CFG_BAUDRATE:
1702 el->baudrate = strtoul(value1, NULL, 10);
1704 case IMAGE_CFG_UART_PORT:
1705 el->uart_port = strtoul(value1, NULL, 16);
1707 case IMAGE_CFG_UART_MPP:
1708 el->uart_mpp = strtoul(value1, NULL, 16);
1710 case IMAGE_CFG_DEBUG:
1711 el->debug = strtoul(value1, NULL, 10);
1714 el->key_name = strdup(value1);
1717 el->key_name = strdup(value1);
1719 case IMAGE_CFG_CSK_INDEX:
1720 el->csk_idx = strtol(value1, NULL, 0);
1722 case IMAGE_CFG_JTAG_DELAY:
1723 el->jtag_delay = strtoul(value1, NULL, 0);
1725 case IMAGE_CFG_BOX_ID:
1726 el->boxid = strtoul(value1, NULL, 0);
1728 case IMAGE_CFG_FLASH_ID:
1729 el->flashid = strtoul(value1, NULL, 0);
1731 case IMAGE_CFG_SEC_SPECIALIZED_IMG:
1732 el->sec_specialized_img = true;
1734 case IMAGE_CFG_SEC_COMMON_IMG:
1735 el->sec_specialized_img = false;
1737 case IMAGE_CFG_SEC_BOOT_DEV:
1738 el->sec_boot_dev = strtoul(value1, NULL, 0);
1740 case IMAGE_CFG_SEC_FUSE_DUMP:
1741 el->name = strdup(value1);
1744 fprintf(stderr, unknown_msg, line);
1751 * Parse the configuration file 'fcfg' into the array of configuration
1752 * elements 'image_cfg', and return the number of configuration
1753 * elements in 'cfgn'.
1755 static int image_create_config_parse(FILE *fcfg)
1760 /* Parse the configuration file */
1761 while (!feof(fcfg)) {
1765 /* Read the current line */
1766 memset(buf, 0, sizeof(buf));
1767 line = fgets(buf, sizeof(buf), fcfg);
1771 /* Ignore useless lines */
1772 if (line[0] == '\n' || line[0] == '#')
1775 /* Strip final newline */
1776 if (line[strlen(line) - 1] == '\n')
1777 line[strlen(line) - 1] = 0;
1779 /* Parse the current line */
1780 ret = image_create_config_parse_oneline(line,
1787 if (cfgi >= IMAGE_CFG_ELEMENT_MAX) {
1789 "Too many configuration elements in .cfg file\n");
1798 static int image_get_version(void)
1800 struct image_cfg_element *e;
1802 e = image_find_option(IMAGE_CFG_VERSION);
1809 static void kwbimage_set_header(void *ptr, struct stat *sbuf, int ifd,
1810 struct image_tool_params *params)
1815 size_t headersz = 0;
1822 * Do not use sbuf->st_size as it contains size with padding.
1823 * We need original image data size, so stat original file.
1825 if (stat(params->datafile, &s)) {
1826 fprintf(stderr, "Could not stat data file %s: %s\n",
1827 params->datafile, strerror(errno));
1830 datasz = ALIGN(s.st_size, 4);
1832 fcfg = fopen(params->imagename, "r");
1834 fprintf(stderr, "Could not open input file %s\n",
1839 image_cfg = malloc(IMAGE_CFG_ELEMENT_MAX *
1840 sizeof(struct image_cfg_element));
1842 fprintf(stderr, "Cannot allocate memory\n");
1847 memset(image_cfg, 0,
1848 IMAGE_CFG_ELEMENT_MAX * sizeof(struct image_cfg_element));
1851 ret = image_create_config_parse(fcfg);
1858 version = image_get_version();
1861 * Fallback to version 0 if no version is provided in the
1866 image = image_create_v0(&headersz, params, datasz + 4);
1870 image = image_create_v1(&headersz, params, ptr, datasz + 4);
1874 fprintf(stderr, "Unsupported version %d\n", version);
1880 fprintf(stderr, "Could not create image\n");
1887 /* Build and add image data checksum */
1888 checksum = cpu_to_le32(image_checksum32((uint8_t *)ptr + headersz,
1890 memcpy((uint8_t *)ptr + headersz + datasz, &checksum, sizeof(uint32_t));
1892 /* Finally copy the header into the image area */
1893 memcpy(ptr, image, headersz);
1898 static void kwbimage_print_header(const void *ptr)
1900 struct main_hdr_v0 *mhdr = (struct main_hdr_v0 *)ptr;
1901 struct opt_hdr_v1 *ohdr;
1903 printf("Image Type: MVEBU Boot from %s Image\n",
1904 image_boot_mode_name(mhdr->blockid));
1905 printf("Image version:%d\n", kwbimage_version(ptr));
1907 for_each_opt_hdr_v1 (ohdr, mhdr) {
1908 if (ohdr->headertype == OPT_HDR_V1_BINARY_TYPE) {
1909 printf("BIN Img Size: ");
1910 genimg_print_size(opt_hdr_v1_size(ohdr) - 12 -
1912 printf("BIN Img Offs: %08x\n",
1913 (unsigned)((uint8_t *)ohdr - (uint8_t *)mhdr) +
1914 8 + 4 * ohdr->data[0]);
1918 printf("Data Size: ");
1919 genimg_print_size(mhdr->blocksize - sizeof(uint32_t));
1920 printf("Load Address: %08x\n", mhdr->destaddr);
1921 printf("Entry Point: %08x\n", mhdr->execaddr);
1924 static int kwbimage_check_image_types(uint8_t type)
1926 if (type == IH_TYPE_KWBIMAGE)
1927 return EXIT_SUCCESS;
1929 return EXIT_FAILURE;
1932 static int kwbimage_verify_header(unsigned char *ptr, int image_size,
1933 struct image_tool_params *params)
1935 size_t header_size = kwbheader_size(ptr);
1941 if (header_size > image_size)
1942 return -FDT_ERR_BADSTRUCTURE;
1944 if (!main_hdr_checksum_ok(ptr))
1945 return -FDT_ERR_BADSTRUCTURE;
1947 /* Only version 0 extended header has checksum */
1948 if (kwbimage_version(ptr) == 0) {
1949 struct main_hdr_v0 *mhdr = (struct main_hdr_v0 *)ptr;
1952 struct ext_hdr_v0 *ext_hdr = (void *)(mhdr + 1);
1954 csum = image_checksum8(ext_hdr, sizeof(*ext_hdr) - 1);
1955 if (csum != ext_hdr->checksum)
1956 return -FDT_ERR_BADSTRUCTURE;
1959 blockid = mhdr->blockid;
1960 offset = le32_to_cpu(mhdr->srcaddr);
1961 size = le32_to_cpu(mhdr->blocksize);
1962 } else if (kwbimage_version(ptr) == 1) {
1963 struct main_hdr_v1 *mhdr = (struct main_hdr_v1 *)ptr;
1964 const uint8_t *mhdr_end;
1965 struct opt_hdr_v1 *ohdr;
1967 mhdr_end = (uint8_t *)mhdr + header_size;
1968 for_each_opt_hdr_v1 (ohdr, ptr)
1969 if (!opt_hdr_v1_valid_size(ohdr, mhdr_end))
1970 return -FDT_ERR_BADSTRUCTURE;
1972 blockid = mhdr->blockid;
1973 offset = le32_to_cpu(mhdr->srcaddr);
1974 size = le32_to_cpu(mhdr->blocksize);
1976 return -FDT_ERR_BADSTRUCTURE;
1980 * For SATA srcaddr is specified in number of sectors.
1981 * The main header is must be stored at sector number 1.
1982 * This expects that sector size is 512 bytes and recalculates
1983 * data offset to bytes relative to the main header.
1985 if (blockid == IBR_HDR_SATA_ID) {
1987 return -FDT_ERR_BADSTRUCTURE;
1993 * For SDIO srcaddr is specified in number of sectors.
1994 * This expects that sector size is 512 bytes and recalculates
1995 * data offset to bytes.
1997 if (blockid == IBR_HDR_SDIO_ID)
2001 * For PCIe srcaddr is always set to 0xFFFFFFFF.
2002 * This expects that data starts after all headers.
2004 if (blockid == IBR_HDR_PEX_ID && offset == 0xFFFFFFFF)
2005 offset = header_size;
2007 if (offset > image_size || offset % 4 != 0)
2008 return -FDT_ERR_BADSTRUCTURE;
2010 if (size < 4 || offset + size > image_size || size % 4 != 0)
2011 return -FDT_ERR_BADSTRUCTURE;
2013 if (image_checksum32(ptr + offset, size - 4) !=
2014 *(uint32_t *)(ptr + offset + size - 4))
2015 return -FDT_ERR_BADSTRUCTURE;
2020 static int kwbimage_generate(struct image_tool_params *params,
2021 struct image_type_params *tparams)
2031 fcfg = fopen(params->imagename, "r");
2033 fprintf(stderr, "Could not open input file %s\n",
2038 if (stat(params->datafile, &s)) {
2039 fprintf(stderr, "Could not stat data file %s: %s\n",
2040 params->datafile, strerror(errno));
2044 image_cfg = malloc(IMAGE_CFG_ELEMENT_MAX *
2045 sizeof(struct image_cfg_element));
2047 fprintf(stderr, "Cannot allocate memory\n");
2052 memset(image_cfg, 0,
2053 IMAGE_CFG_ELEMENT_MAX * sizeof(struct image_cfg_element));
2056 ret = image_create_config_parse(fcfg);
2063 bootfrom = image_get_bootfrom();
2064 version = image_get_version();
2067 * Fallback to version 0 if no version is provided in the
2072 alloc_len = image_headersz_v0(NULL);
2076 alloc_len = image_headersz_v1(NULL);
2081 if (alloc_len > 192*1024) {
2082 fprintf(stderr, "Header is too big (%u bytes), maximal kwbimage header size is %u bytes\n", alloc_len, 192*1024);
2089 fprintf(stderr, "Unsupported version %d\n", version);
2096 hdr = malloc(alloc_len);
2098 fprintf(stderr, "%s: malloc return failure: %s\n",
2099 params->cmdname, strerror(errno));
2103 memset(hdr, 0, alloc_len);
2104 tparams->header_size = alloc_len;
2108 * The resulting image needs to be 4-byte aligned. At least
2109 * the Marvell hdrparser tool complains if its unaligned.
2110 * After the image data is stored 4-byte checksum.
2111 * Final UART image must be aligned to 128 bytes.
2112 * Final SPI and NAND images must be aligned to 256 bytes.
2113 * Final SATA and SDIO images must be aligned to 512 bytes.
2115 if (bootfrom == IBR_HDR_SPI_ID || bootfrom == IBR_HDR_NAND_ID)
2116 return 4 + (256 - (alloc_len + s.st_size + 4) % 256) % 256;
2117 else if (bootfrom == IBR_HDR_SATA_ID || bootfrom == IBR_HDR_SDIO_ID)
2118 return 4 + (512 - (alloc_len + s.st_size + 4) % 512) % 512;
2119 else if (bootfrom == IBR_HDR_UART_ID)
2120 return 4 + (128 - (alloc_len + s.st_size + 4) % 128) % 128;
2122 return 4 + (4 - s.st_size % 4) % 4;
2125 static int kwbimage_generate_config(void *ptr, struct image_tool_params *params)
2127 struct main_hdr_v0 *mhdr0 = (struct main_hdr_v0 *)ptr;
2128 struct main_hdr_v1 *mhdr = (struct main_hdr_v1 *)ptr;
2129 size_t header_size = kwbheader_size(ptr);
2130 struct register_set_hdr_v1 *regset_hdr;
2131 struct ext_hdr_v0_reg *regdata;
2132 struct ext_hdr_v0 *ehdr0;
2133 struct opt_hdr_v1 *ohdr;
2140 f = fopen(params->outfile, "w");
2142 fprintf(stderr, "Can't open \"%s\": %s\n", params->outfile, strerror(errno));
2146 version = kwbimage_version(ptr);
2149 fprintf(f, "VERSION %d\n", version);
2151 fprintf(f, "BOOT_FROM %s\n", image_boot_mode_name(mhdr->blockid) ?: "<unknown>");
2153 if (version == 0 && mhdr->blockid == IBR_HDR_NAND_ID)
2154 fprintf(f, "NAND_ECC_MODE %s\n", image_nand_ecc_mode_name(mhdr0->nandeccmode));
2156 if (mhdr->blockid == IBR_HDR_NAND_ID)
2157 fprintf(f, "NAND_PAGE_SIZE 0x%x\n", (unsigned)mhdr->nandpagesize);
2159 if (version != 0 && mhdr->blockid == IBR_HDR_NAND_ID) {
2160 fprintf(f, "NAND_BLKSZ 0x%x\n", (unsigned)mhdr->nandblocksize);
2161 fprintf(f, "NAND_BADBLK_LOCATION 0x%x\n", (unsigned)mhdr->nandbadblklocation);
2164 if (version == 0 && mhdr->blockid == IBR_HDR_SATA_ID)
2165 fprintf(f, "SATA_PIO_MODE %u\n", (unsigned)mhdr0->satapiomode);
2168 * Addresses and sizes which are specified by mkimage command line
2169 * arguments and not in kwbimage config file
2173 fprintf(f, "#HEADER_SIZE 0x%x\n",
2174 ((unsigned)mhdr->headersz_msb << 8) | le16_to_cpu(mhdr->headersz_lsb));
2176 fprintf(f, "#SRC_ADDRESS 0x%x\n", le32_to_cpu(mhdr->srcaddr));
2177 fprintf(f, "#BLOCK_SIZE 0x%x\n", le32_to_cpu(mhdr->blocksize));
2178 fprintf(f, "#DEST_ADDRESS 0x%08x\n", le32_to_cpu(mhdr->destaddr));
2179 fprintf(f, "#EXEC_ADDRESS 0x%08x\n", le32_to_cpu(mhdr->execaddr));
2182 if (options_to_baudrate(mhdr->options))
2183 fprintf(f, "BAUDRATE %u\n", options_to_baudrate(mhdr->options));
2184 if (options_to_baudrate(mhdr->options) ||
2185 ((mhdr->options >> 3) & 0x3) || ((mhdr->options >> 5) & 0x7)) {
2186 fprintf(f, "UART_PORT %u\n", (unsigned)((mhdr->options >> 3) & 0x3));
2187 fprintf(f, "UART_MPP 0x%x\n", (unsigned)((mhdr->options >> 5) & 0x7));
2189 if (mhdr->flags & 0x1)
2190 fprintf(f, "DEBUG 1\n");
2194 for_each_opt_hdr_v1(ohdr, ptr) {
2195 if (ohdr->headertype == OPT_HDR_V1_SECURE_TYPE) {
2196 fprintf(f, "#SECURE_HEADER\n");
2197 } else if (ohdr->headertype == OPT_HDR_V1_BINARY_TYPE) {
2198 fprintf(f, "BINARY binary%d.bin", cur_idx);
2199 for (i = 0; i < ohdr->data[0]; i++)
2200 fprintf(f, " 0x%x", le32_to_cpu(((uint32_t *)ohdr->data)[i + 1]));
2201 offset = (unsigned)((uint8_t *)ohdr - (uint8_t *)mhdr) + 8 + 4 * ohdr->data[0];
2202 fprintf(f, " LOAD_ADDRESS 0x%08x\n", 0x40000000 + offset);
2203 fprintf(f, " # for CPU SHEEVA: LOAD_ADDRESS 0x%08x\n", 0x40004000 + offset);
2205 } else if (ohdr->headertype == OPT_HDR_V1_REGISTER_TYPE) {
2206 regset_hdr = (struct register_set_hdr_v1 *)ohdr;
2208 i < opt_hdr_v1_size(ohdr) - sizeof(struct opt_hdr_v1) -
2209 sizeof(regset_hdr->data[0].last_entry);
2211 fprintf(f, "DATA 0x%08x 0x%08x\n",
2212 le32_to_cpu(regset_hdr->data[i].entry.address),
2213 le32_to_cpu(regset_hdr->data[i].entry.value));
2214 if (opt_hdr_v1_size(ohdr) - sizeof(struct opt_hdr_v1) >=
2215 sizeof(regset_hdr->data[0].last_entry)) {
2216 if (regset_hdr->data[0].last_entry.delay)
2217 fprintf(f, "DATA_DELAY %u\n",
2218 (unsigned)regset_hdr->data[0].last_entry.delay);
2220 fprintf(f, "DATA_DELAY SDRAM_SETUP\n");
2225 if (version == 0 && mhdr0->ext) {
2226 ehdr0 = (struct ext_hdr_v0 *)(mhdr0 + 1);
2227 if (ehdr0->offset) {
2228 for (regdata = (struct ext_hdr_v0_reg *)((uint8_t *)ptr + ehdr0->offset);
2229 (uint8_t *)regdata < (uint8_t *)ptr + header_size && regdata->raddr &&
2232 fprintf(f, "DATA 0x%08x 0x%08x\n", le32_to_cpu(regdata->raddr),
2233 le32_to_cpu(regdata->rdata));
2237 if (version == 0 && le16_to_cpu(mhdr0->ddrinitdelay))
2238 fprintf(f, "DDR_INIT_DELAY %u\n", (unsigned)le16_to_cpu(mhdr0->ddrinitdelay));
2240 /* Undocumented reserved fields */
2242 if (version == 0 && (mhdr0->rsvd1[0] || mhdr0->rsvd1[1] || mhdr0->rsvd1[2]))
2243 fprintf(f, "#RSVD1 0x%x 0x%x 0x%x\n", (unsigned)mhdr0->rsvd1[0],
2244 (unsigned)mhdr0->rsvd1[1], (unsigned)mhdr0->rsvd1[2]);
2246 if (version == 0 && mhdr0->rsvd3)
2247 fprintf(f, "#RSVD3 0x%x\n", (unsigned)mhdr0->rsvd3);
2249 if (version == 0 && le16_to_cpu(mhdr0->rsvd2))
2250 fprintf(f, "#RSVD2 0x%x\n", (unsigned)le16_to_cpu(mhdr0->rsvd2));
2252 if (version != 0 && mhdr->reserved4)
2253 fprintf(f, "#RESERVED4 0x%x\n", (unsigned)mhdr->reserved4);
2255 if (version != 0 && mhdr->reserved5)
2256 fprintf(f, "#RESERVED5 0x%x\n", (unsigned)le16_to_cpu(mhdr->reserved5));
2263 static int kwbimage_extract_subimage(void *ptr, struct image_tool_params *params)
2265 struct main_hdr_v1 *mhdr = (struct main_hdr_v1 *)ptr;
2266 size_t header_size = kwbheader_size(ptr);
2267 struct opt_hdr_v1 *ohdr;
2268 int idx = params->pflag;
2274 /* Generate kwbimage config file when '-p -1' is specified */
2276 return kwbimage_generate_config(ptr, params);
2282 /* Extract data image when -p is not specified or when '-p 0' is specified */
2283 offset = le32_to_cpu(mhdr->srcaddr);
2285 if (mhdr->blockid == IBR_HDR_SATA_ID) {
2290 if (mhdr->blockid == IBR_HDR_SDIO_ID)
2293 if (mhdr->blockid == IBR_HDR_PEX_ID && offset == 0xFFFFFFFF)
2294 offset = header_size;
2296 image = (ulong)((uint8_t *)ptr + offset);
2297 size = le32_to_cpu(mhdr->blocksize) - 4;
2299 /* Extract N-th binary header executabe image when other '-p N' is specified */
2301 for_each_opt_hdr_v1(ohdr, ptr) {
2302 if (ohdr->headertype != OPT_HDR_V1_BINARY_TYPE)
2305 if (idx == cur_idx) {
2306 image = (ulong)&ohdr->data[4 + 4 * ohdr->data[0]];
2307 size = opt_hdr_v1_size(ohdr) - 12 - 4 * ohdr->data[0];
2315 fprintf(stderr, "Argument -p %d is invalid\n", idx);
2316 fprintf(stderr, "Available subimages:\n");
2317 fprintf(stderr, " -p -1 - kwbimage config file\n");
2318 fprintf(stderr, " -p 0 - data image\n");
2319 if (cur_idx - 1 > 0)
2320 fprintf(stderr, " -p N - Nth binary header image (totally: %d)\n",
2326 return imagetool_save_subimage(params->outfile, image, size);
2330 * Report Error if xflag is set in addition to default
2332 static int kwbimage_check_params(struct image_tool_params *params)
2334 if (!params->lflag && !params->iflag &&
2335 (!params->imagename || !strlen(params->imagename))) {
2336 char *msg = "Configuration file for kwbimage creation omitted";
2338 fprintf(stderr, "Error:%s - %s\n", params->cmdname, msg);
2342 return (params->dflag && (params->fflag || params->lflag)) ||
2343 (params->fflag && (params->dflag || params->lflag)) ||
2344 (params->lflag && (params->dflag || params->fflag)) ||
2349 * kwbimage type parameters definition
2353 "Marvell MVEBU Boot Image support",
2356 kwbimage_check_params,
2357 kwbimage_verify_header,
2358 kwbimage_print_header,
2359 kwbimage_set_header,
2360 kwbimage_extract_subimage,
2361 kwbimage_check_image_types,