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 int image_nand_ecc_mode_id(const char *nand_ecc_mode_name)
221 for (i = 0; nand_ecc_modes[i].name; i++)
222 if (!strcmp(nand_ecc_modes[i].name, nand_ecc_mode_name))
223 return nand_ecc_modes[i].id;
227 static struct image_cfg_element *
228 image_find_option(unsigned int optiontype)
232 for (i = 0; i < cfgn; i++) {
233 if (image_cfg[i].type == optiontype)
234 return &image_cfg[i];
241 image_count_options(unsigned int optiontype)
244 unsigned int count = 0;
246 for (i = 0; i < cfgn; i++)
247 if (image_cfg[i].type == optiontype)
253 static int image_get_csk_index(void)
255 struct image_cfg_element *e;
257 e = image_find_option(IMAGE_CFG_CSK_INDEX);
264 static bool image_get_spezialized_img(void)
266 struct image_cfg_element *e;
268 e = image_find_option(IMAGE_CFG_SEC_SPECIALIZED_IMG);
272 return e->sec_specialized_img;
275 static int image_get_bootfrom(void)
277 struct image_cfg_element *e;
279 e = image_find_option(IMAGE_CFG_BOOT_FROM);
281 /* fallback to SPI if no BOOT_FROM is not provided */
282 return IBR_HDR_SPI_ID;
287 static int image_is_cpu_sheeva(void)
289 struct image_cfg_element *e;
291 e = image_find_option(IMAGE_CFG_CPU);
295 return e->cpu_sheeva;
299 * Compute a 8-bit checksum of a memory area. This algorithm follows
300 * the requirements of the Marvell SoC BootROM specifications.
302 static uint8_t image_checksum8(void *start, uint32_t len)
307 /* check len and return zero checksum if invalid */
320 * Verify checksum over a complete header that includes the checksum field.
321 * Return 1 when OK, otherwise 0.
323 static int main_hdr_checksum_ok(void *hdr)
325 /* Offsets of checksum in v0 and v1 headers are the same */
326 struct main_hdr_v0 *main_hdr = (struct main_hdr_v0 *)hdr;
329 checksum = image_checksum8(hdr, kwbheader_size_for_csum(hdr));
330 /* Calculated checksum includes the header checksum field. Compensate
333 checksum -= main_hdr->checksum;
335 return checksum == main_hdr->checksum;
338 static uint32_t image_checksum32(void *start, uint32_t len)
343 /* check len and return zero checksum if invalid */
347 if (len % sizeof(uint32_t)) {
348 fprintf(stderr, "Length %d is not in multiple of %zu\n",
349 len, sizeof(uint32_t));
356 len -= sizeof(uint32_t);
362 static uint8_t baudrate_to_option(unsigned int baudrate)
366 return MAIN_HDR_V1_OPT_BAUD_2400;
368 return MAIN_HDR_V1_OPT_BAUD_4800;
370 return MAIN_HDR_V1_OPT_BAUD_9600;
372 return MAIN_HDR_V1_OPT_BAUD_19200;
374 return MAIN_HDR_V1_OPT_BAUD_38400;
376 return MAIN_HDR_V1_OPT_BAUD_57600;
378 return MAIN_HDR_V1_OPT_BAUD_115200;
380 return MAIN_HDR_V1_OPT_BAUD_DEFAULT;
384 static void kwb_msg(const char *fmt, ...)
390 vfprintf(stdout, fmt, ap);
395 static int openssl_err(const char *msg)
397 unsigned long ssl_err = ERR_get_error();
399 fprintf(stderr, "%s", msg);
400 fprintf(stderr, ": %s\n",
401 ERR_error_string(ssl_err, 0));
406 static int kwb_load_rsa_key(const char *keydir, const char *name, RSA **p_rsa)
415 snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
416 f = fopen(path, "r");
418 fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
419 path, strerror(errno));
423 rsa = PEM_read_RSAPrivateKey(f, 0, NULL, "");
425 openssl_err("Failure reading private key");
435 static int kwb_load_cfg_key(struct image_tool_params *params,
436 unsigned int cfg_option, const char *key_name,
439 struct image_cfg_element *e_key;
445 e_key = image_find_option(cfg_option);
447 fprintf(stderr, "%s not configured\n", key_name);
451 res = kwb_load_rsa_key(params->keydir, e_key->key_name, &key);
453 fprintf(stderr, "Failed to load %s\n", key_name);
462 static int kwb_load_kak(struct image_tool_params *params, RSA **p_kak)
464 return kwb_load_cfg_key(params, IMAGE_CFG_KAK, "KAK", p_kak);
467 static int kwb_load_csk(struct image_tool_params *params, RSA **p_csk)
469 return kwb_load_cfg_key(params, IMAGE_CFG_CSK, "CSK", p_csk);
472 static int kwb_compute_pubkey_hash(struct pubkey_der_v1 *pk,
473 struct hash_v1 *hash)
476 unsigned int key_size;
477 unsigned int hash_size;
480 if (!pk || !hash || pk->key[0] != 0x30 || pk->key[1] != 0x82)
483 key_size = (pk->key[2] << 8) + pk->key[3] + 4;
485 ctx = EVP_MD_CTX_create();
487 return openssl_err("EVP context creation failed");
489 EVP_MD_CTX_init(ctx);
490 if (!EVP_DigestInit(ctx, EVP_sha256())) {
491 ret = openssl_err("Digest setup failed");
495 if (!EVP_DigestUpdate(ctx, pk->key, key_size)) {
496 ret = openssl_err("Hashing data failed");
500 if (!EVP_DigestFinal(ctx, hash->hash, &hash_size)) {
501 ret = openssl_err("Could not obtain hash");
505 EVP_MD_CTX_cleanup(ctx);
508 EVP_MD_CTX_destroy(ctx);
512 static int kwb_import_pubkey(RSA **key, struct pubkey_der_v1 *src, char *keyname)
515 const unsigned char *ptr;
521 rsa = d2i_RSAPublicKey(key, &ptr, sizeof(src->key));
523 openssl_err("error decoding public key");
529 fprintf(stderr, "Failed to decode %s pubkey\n", keyname);
533 static int kwb_export_pubkey(RSA *key, struct pubkey_der_v1 *dst, FILE *hashf,
536 int size_exp, size_mod, size_seq;
537 const BIGNUM *key_e, *key_n;
539 char *errmsg = "Failed to encode %s\n";
541 RSA_get0_key(key, NULL, &key_e, NULL);
542 RSA_get0_key(key, &key_n, NULL, NULL);
544 if (!key || !key_e || !key_n || !dst) {
545 fprintf(stderr, "export pk failed: (%p, %p, %p, %p)",
546 key, key_e, key_n, dst);
547 fprintf(stderr, errmsg, keyname);
552 * According to the specs, the key should be PKCS#1 DER encoded.
553 * But unfortunately the really required encoding seems to be different;
554 * it violates DER...! (But it still conformes to BER.)
555 * (Length always in long form w/ 2 byte length code; no leading zero
556 * when MSB of first byte is set...)
557 * So we cannot use the encoding func provided by OpenSSL and have to
558 * do the encoding manually.
561 size_exp = BN_num_bytes(key_e);
562 size_mod = BN_num_bytes(key_n);
563 size_seq = 4 + size_mod + 4 + size_exp;
565 if (size_mod > 256) {
566 fprintf(stderr, "export pk failed: wrong mod size: %d\n",
568 fprintf(stderr, errmsg, keyname);
572 if (4 + size_seq > sizeof(dst->key)) {
573 fprintf(stderr, "export pk failed: seq too large (%d, %zu)\n",
574 4 + size_seq, sizeof(dst->key));
575 fprintf(stderr, errmsg, keyname);
581 /* PKCS#1 (RFC3447) RSAPublicKey structure */
582 *cur++ = 0x30; /* SEQUENCE */
584 *cur++ = (size_seq >> 8) & 0xFF;
585 *cur++ = size_seq & 0xFF;
587 *cur++ = 0x02; /* INTEGER */
589 *cur++ = (size_mod >> 8) & 0xFF;
590 *cur++ = size_mod & 0xFF;
591 BN_bn2bin(key_n, cur);
594 *cur++ = 0x02; /* INTEGER */
596 *cur++ = (size_exp >> 8) & 0xFF;
597 *cur++ = size_exp & 0xFF;
598 BN_bn2bin(key_e, cur);
601 struct hash_v1 pk_hash;
605 ret = kwb_compute_pubkey_hash(dst, &pk_hash);
607 fprintf(stderr, errmsg, keyname);
611 fprintf(hashf, "SHA256 = ");
612 for (i = 0 ; i < sizeof(pk_hash.hash); ++i)
613 fprintf(hashf, "%02X", pk_hash.hash[i]);
614 fprintf(hashf, "\n");
620 static int kwb_sign(RSA *key, void *data, int datasz, struct sig_v1 *sig,
625 unsigned int sig_size;
629 evp_key = EVP_PKEY_new();
631 return openssl_err("EVP_PKEY object creation failed");
633 if (!EVP_PKEY_set1_RSA(evp_key, key)) {
634 ret = openssl_err("EVP key setup failed");
638 size = EVP_PKEY_size(evp_key);
639 if (size > sizeof(sig->sig)) {
640 fprintf(stderr, "Buffer to small for signature (%d bytes)\n",
646 ctx = EVP_MD_CTX_create();
648 ret = openssl_err("EVP context creation failed");
651 EVP_MD_CTX_init(ctx);
652 if (!EVP_SignInit(ctx, EVP_sha256())) {
653 ret = openssl_err("Signer setup failed");
657 if (!EVP_SignUpdate(ctx, data, datasz)) {
658 ret = openssl_err("Signing data failed");
662 if (!EVP_SignFinal(ctx, sig->sig, &sig_size, evp_key)) {
663 ret = openssl_err("Could not obtain signature");
667 EVP_MD_CTX_cleanup(ctx);
668 EVP_MD_CTX_destroy(ctx);
669 EVP_PKEY_free(evp_key);
674 EVP_MD_CTX_destroy(ctx);
676 EVP_PKEY_free(evp_key);
677 fprintf(stderr, "Failed to create %s signature\n", signame);
681 static int kwb_verify(RSA *key, void *data, int datasz, struct sig_v1 *sig,
689 evp_key = EVP_PKEY_new();
691 return openssl_err("EVP_PKEY object creation failed");
693 if (!EVP_PKEY_set1_RSA(evp_key, key)) {
694 ret = openssl_err("EVP key setup failed");
698 size = EVP_PKEY_size(evp_key);
699 if (size > sizeof(sig->sig)) {
700 fprintf(stderr, "Invalid signature size (%d bytes)\n",
706 ctx = EVP_MD_CTX_create();
708 ret = openssl_err("EVP context creation failed");
711 EVP_MD_CTX_init(ctx);
712 if (!EVP_VerifyInit(ctx, EVP_sha256())) {
713 ret = openssl_err("Verifier setup failed");
717 if (!EVP_VerifyUpdate(ctx, data, datasz)) {
718 ret = openssl_err("Hashing data failed");
722 if (EVP_VerifyFinal(ctx, sig->sig, sizeof(sig->sig), evp_key) != 1) {
723 ret = openssl_err("Could not verify signature");
727 EVP_MD_CTX_cleanup(ctx);
728 EVP_MD_CTX_destroy(ctx);
729 EVP_PKEY_free(evp_key);
734 EVP_MD_CTX_destroy(ctx);
736 EVP_PKEY_free(evp_key);
737 fprintf(stderr, "Failed to verify %s signature\n", signame);
741 static int kwb_sign_and_verify(RSA *key, void *data, int datasz,
742 struct sig_v1 *sig, char *signame)
744 if (kwb_sign(key, data, datasz, sig, signame) < 0)
747 if (kwb_verify(key, data, datasz, sig, signame) < 0)
754 static int kwb_dump_fuse_cmds_38x(FILE *out, struct secure_hdr_v1 *sec_hdr)
756 struct hash_v1 kak_pub_hash;
757 struct image_cfg_element *e;
758 unsigned int fuse_line;
764 if (!out || !sec_hdr)
767 ret = kwb_compute_pubkey_hash(&sec_hdr->kak, &kak_pub_hash);
771 fprintf(out, "# burn KAK pub key hash\n");
772 ptr = kak_pub_hash.hash;
773 for (fuse_line = 26; fuse_line <= 30; ++fuse_line) {
774 fprintf(out, "fuse prog -y %u 0 ", fuse_line);
776 for (i = 4; i-- > 0;)
777 fprintf(out, "%02hx", (ushort)ptr[i]);
781 if (fuse_line < 30) {
782 for (i = 3; i-- > 0;)
783 fprintf(out, "%02hx", (ushort)ptr[i]);
786 fprintf(out, "000000");
789 fprintf(out, " 1\n");
792 fprintf(out, "# burn CSK selection\n");
794 idx = image_get_csk_index();
795 if (idx < 0 || idx > 15) {
800 for (fuse_line = 31; fuse_line < 31 + idx; ++fuse_line)
801 fprintf(out, "fuse prog -y %u 0 00000001 00000000 1\n",
804 fprintf(out, "# CSK index is 0; no mods needed\n");
807 e = image_find_option(IMAGE_CFG_BOX_ID);
809 fprintf(out, "# set box ID\n");
810 fprintf(out, "fuse prog -y 48 0 %08x 00000000 1\n", e->boxid);
813 e = image_find_option(IMAGE_CFG_FLASH_ID);
815 fprintf(out, "# set flash ID\n");
816 fprintf(out, "fuse prog -y 47 0 %08x 00000000 1\n", e->flashid);
819 fprintf(out, "# enable secure mode ");
820 fprintf(out, "(must be the last fuse line written)\n");
823 e = image_find_option(IMAGE_CFG_SEC_BOOT_DEV);
825 fprintf(stderr, "ERROR: secured mode boot device not given\n");
830 if (e->sec_boot_dev > 0xff) {
831 fprintf(stderr, "ERROR: secured mode boot device invalid\n");
836 val |= (e->sec_boot_dev << 8);
838 fprintf(out, "fuse prog -y 24 0 %08x 0103e0a9 1\n", val);
840 fprintf(out, "# lock (unused) fuse lines (0-23)s\n");
841 for (fuse_line = 0; fuse_line < 24; ++fuse_line)
842 fprintf(out, "fuse prog -y %u 2 1\n", fuse_line);
844 fprintf(out, "# OK, that's all :-)\n");
850 static int kwb_dump_fuse_cmds(struct secure_hdr_v1 *sec_hdr)
853 struct image_cfg_element *e;
855 e = image_find_option(IMAGE_CFG_SEC_FUSE_DUMP);
859 if (!strcmp(e->name, "a38x")) {
860 FILE *out = fopen("kwb_fuses_a38x.txt", "w+");
863 fprintf(stderr, "Couldn't open eFuse settings: '%s': %s\n",
864 "kwb_fuses_a38x.txt", strerror(errno));
868 kwb_dump_fuse_cmds_38x(out, sec_hdr);
879 static size_t image_headersz_align(size_t headersz, uint8_t blockid)
882 * Header needs to be 4-byte aligned, which is already ensured by code
883 * above. Moreover UART images must have header aligned to 128 bytes
884 * (xmodem block size), NAND images to 256 bytes (ECC calculation),
885 * and SATA and SDIO images to 512 bytes (storage block size).
886 * Note that SPI images do not have to have header size aligned
887 * to 256 bytes because it is possible to read from SPI storage from
888 * any offset (read offset does not have to be aligned to block size).
890 if (blockid == IBR_HDR_UART_ID)
891 return ALIGN(headersz, 128);
892 else if (blockid == IBR_HDR_NAND_ID)
893 return ALIGN(headersz, 256);
894 else if (blockid == IBR_HDR_SATA_ID || blockid == IBR_HDR_SDIO_ID)
895 return ALIGN(headersz, 512);
900 static size_t image_headersz_v0(int *hasext)
904 headersz = sizeof(struct main_hdr_v0);
905 if (image_count_options(IMAGE_CFG_DATA) > 0) {
906 headersz += sizeof(struct ext_hdr_v0);
911 return image_headersz_align(headersz, image_get_bootfrom());
914 static void *image_create_v0(size_t *imagesz, struct image_tool_params *params,
917 struct image_cfg_element *e;
919 struct main_hdr_v0 *main_hdr;
924 * Calculate the size of the header and the size of the
927 headersz = image_headersz_v0(&has_ext);
929 image = malloc(headersz);
931 fprintf(stderr, "Cannot allocate memory for image\n");
935 memset(image, 0, headersz);
937 main_hdr = (struct main_hdr_v0 *)image;
939 /* Fill in the main header */
940 main_hdr->blocksize =
941 cpu_to_le32(payloadsz);
942 main_hdr->srcaddr = cpu_to_le32(headersz);
943 main_hdr->ext = has_ext;
944 main_hdr->version = 0;
945 main_hdr->destaddr = cpu_to_le32(params->addr);
946 main_hdr->execaddr = cpu_to_le32(params->ep);
947 main_hdr->blockid = image_get_bootfrom();
949 e = image_find_option(IMAGE_CFG_NAND_ECC_MODE);
951 main_hdr->nandeccmode = e->nandeccmode;
952 e = image_find_option(IMAGE_CFG_NAND_PAGESZ);
954 main_hdr->nandpagesize = cpu_to_le16(e->nandpagesz);
955 main_hdr->checksum = image_checksum8(image,
956 sizeof(struct main_hdr_v0));
959 * For SATA srcaddr is specified in number of sectors starting from
960 * sector 0. The main header is stored at sector number 1.
961 * This expects the sector size to be 512 bytes.
962 * Header size is already aligned.
964 if (main_hdr->blockid == IBR_HDR_SATA_ID)
965 main_hdr->srcaddr = cpu_to_le32(headersz / 512 + 1);
968 * For SDIO srcaddr is specified in number of sectors starting from
969 * sector 0. The main header is stored at sector number 0.
970 * This expects sector size to be 512 bytes.
971 * Header size is already aligned.
973 if (main_hdr->blockid == IBR_HDR_SDIO_ID)
974 main_hdr->srcaddr = cpu_to_le32(headersz / 512);
976 /* For PCIe srcaddr is not used and must be set to 0xFFFFFFFF. */
977 if (main_hdr->blockid == IBR_HDR_PEX_ID)
978 main_hdr->srcaddr = cpu_to_le32(0xFFFFFFFF);
980 /* Generate the ext header */
982 struct ext_hdr_v0 *ext_hdr;
985 ext_hdr = (struct ext_hdr_v0 *)
986 (image + sizeof(struct main_hdr_v0));
987 ext_hdr->offset = cpu_to_le32(0x40);
989 for (cfgi = 0, datai = 0; cfgi < cfgn; cfgi++) {
990 e = &image_cfg[cfgi];
991 if (e->type != IMAGE_CFG_DATA)
994 ext_hdr->rcfg[datai].raddr =
995 cpu_to_le32(e->regdata.raddr);
996 ext_hdr->rcfg[datai].rdata =
997 cpu_to_le32(e->regdata.rdata);
1001 ext_hdr->checksum = image_checksum8(ext_hdr,
1002 sizeof(struct ext_hdr_v0));
1005 *imagesz = headersz;
1009 static size_t image_headersz_v1(int *hasext)
1011 struct image_cfg_element *e;
1020 * Calculate the size of the header and the size of the
1023 headersz = sizeof(struct main_hdr_v1);
1025 if (image_get_csk_index() >= 0) {
1026 headersz += sizeof(struct secure_hdr_v1);
1031 cpu_sheeva = image_is_cpu_sheeva();
1034 for (cfgi = 0; cfgi < cfgn; cfgi++) {
1035 e = &image_cfg[cfgi];
1037 if (e->type == IMAGE_CFG_DATA)
1040 if (e->type == IMAGE_CFG_DATA_DELAY ||
1041 (e->type == IMAGE_CFG_BINARY && count > 0)) {
1042 headersz += sizeof(struct register_set_hdr_v1) + 8 * count + 4;
1046 if (e->type != IMAGE_CFG_BINARY)
1049 ret = stat(e->binary.file, &s);
1054 memset(cwd, 0, sizeof(cwd));
1055 if (!getcwd(cwd, sizeof(cwd))) {
1056 dir = "current working directory";
1057 perror("getcwd() failed");
1061 "Didn't find the file '%s' in '%s' which is mandatory to generate the image\n"
1062 "This file generally contains the DDR3 training code, and should be extracted from an existing bootable\n"
1063 "image for your board. Use 'dumpimage -T kwbimage -p 0' to extract it from an existing image.\n",
1064 e->binary.file, dir);
1068 headersz += sizeof(struct opt_hdr_v1) + sizeof(uint32_t) +
1069 (e->binary.nargs) * sizeof(uint32_t);
1071 if (e->binary.loadaddr) {
1073 * BootROM loads kwbimage header (in which the
1074 * executable code is also stored) to address
1075 * 0x40004000 or 0x40000000. Thus there is
1076 * restriction for the load address of the N-th
1079 unsigned int base_addr, low_addr, high_addr;
1081 base_addr = cpu_sheeva ? 0x40004000 : 0x40000000;
1082 low_addr = base_addr + headersz;
1083 high_addr = low_addr +
1084 (BINARY_MAX_ARGS - e->binary.nargs) * sizeof(uint32_t);
1086 if (cpu_sheeva && e->binary.loadaddr % 16) {
1088 "Invalid LOAD_ADDRESS 0x%08x for BINARY %s with %d args.\n"
1089 "Address for CPU SHEEVA must be 16-byte aligned.\n",
1090 e->binary.loadaddr, e->binary.file, e->binary.nargs);
1094 if (e->binary.loadaddr % 4 || e->binary.loadaddr < low_addr ||
1095 e->binary.loadaddr > high_addr) {
1097 "Invalid LOAD_ADDRESS 0x%08x for BINARY %s with %d args.\n"
1098 "Address must be 4-byte aligned and in range 0x%08x-0x%08x.\n",
1099 e->binary.loadaddr, e->binary.file,
1100 e->binary.nargs, low_addr, high_addr);
1103 headersz = e->binary.loadaddr - base_addr;
1104 } else if (cpu_sheeva) {
1105 headersz = ALIGN(headersz, 16);
1107 headersz = ALIGN(headersz, 4);
1110 headersz += ALIGN(s.st_size, 4) + sizeof(uint32_t);
1116 headersz += sizeof(struct register_set_hdr_v1) + 8 * count + 4;
1118 return image_headersz_align(headersz, image_get_bootfrom());
1121 static int add_binary_header_v1(uint8_t **cur, uint8_t **next_ext,
1122 struct image_cfg_element *binarye,
1123 struct main_hdr_v1 *main_hdr)
1125 struct opt_hdr_v1 *hdr = (struct opt_hdr_v1 *)*cur;
1137 hdr->headertype = OPT_HDR_V1_BINARY_TYPE;
1139 bin = fopen(binarye->binary.file, "r");
1141 fprintf(stderr, "Cannot open binary file %s\n",
1142 binarye->binary.file);
1146 if (fstat(fileno(bin), &s)) {
1147 fprintf(stderr, "Cannot stat binary file %s\n",
1148 binarye->binary.file);
1152 *cur += sizeof(struct opt_hdr_v1);
1154 args = (uint32_t *)*cur;
1155 *args = cpu_to_le32(binarye->binary.nargs);
1157 for (argi = 0; argi < binarye->binary.nargs; argi++)
1158 args[argi] = cpu_to_le32(binarye->binary.args[argi]);
1160 *cur += (binarye->binary.nargs + 1) * sizeof(uint32_t);
1163 * ARM executable code inside the BIN header on platforms with Sheeva
1164 * CPU (A370 and AXP) must always be aligned with the 128-bit boundary.
1165 * In the case when this code is not position independent (e.g. ARM
1166 * SPL), it must be placed at fixed load and execute address.
1167 * This requirement can be met by inserting dummy arguments into
1168 * BIN header, if needed.
1170 cpu_sheeva = image_is_cpu_sheeva();
1171 base_addr = cpu_sheeva ? 0x40004000 : 0x40000000;
1172 offset = *cur - (uint8_t *)main_hdr;
1173 if (binarye->binary.loadaddr)
1174 add_args = (binarye->binary.loadaddr - base_addr - offset) / sizeof(uint32_t);
1175 else if (cpu_sheeva)
1176 add_args = ((16 - offset % 16) % 16) / sizeof(uint32_t);
1180 *(args - 1) = cpu_to_le32(binarye->binary.nargs + add_args);
1181 *cur += add_args * sizeof(uint32_t);
1184 ret = fread(*cur, s.st_size, 1, bin);
1187 "Could not read binary image %s\n",
1188 binarye->binary.file);
1194 *cur += ALIGN(s.st_size, 4);
1196 *((uint32_t *)*cur) = 0x00000000;
1200 *cur += sizeof(uint32_t);
1202 binhdrsz = sizeof(struct opt_hdr_v1) +
1203 (binarye->binary.nargs + add_args + 2) * sizeof(uint32_t) +
1204 ALIGN(s.st_size, 4);
1205 hdr->headersz_lsb = cpu_to_le16(binhdrsz & 0xFFFF);
1206 hdr->headersz_msb = (binhdrsz & 0xFFFF0000) >> 16;
1216 static int export_pub_kak_hash(RSA *kak, struct secure_hdr_v1 *secure_hdr)
1221 hashf = fopen("pub_kak_hash.txt", "w");
1223 fprintf(stderr, "Couldn't open hash file: '%s': %s\n",
1224 "pub_kak_hash.txt", strerror(errno));
1228 res = kwb_export_pubkey(kak, &secure_hdr->kak, hashf, "KAK");
1232 return res < 0 ? 1 : 0;
1235 static int kwb_sign_csk_with_kak(struct image_tool_params *params,
1236 struct secure_hdr_v1 *secure_hdr, RSA *csk)
1239 RSA *kak_pub = NULL;
1240 int csk_idx = image_get_csk_index();
1241 struct sig_v1 tmp_sig;
1243 if (csk_idx < 0 || csk_idx > 15) {
1244 fprintf(stderr, "Invalid CSK index %d\n", csk_idx);
1248 if (kwb_load_kak(params, &kak) < 0)
1251 if (export_pub_kak_hash(kak, secure_hdr))
1254 if (kwb_import_pubkey(&kak_pub, &secure_hdr->kak, "KAK") < 0)
1257 if (kwb_export_pubkey(csk, &secure_hdr->csk[csk_idx], NULL, "CSK") < 0)
1260 if (kwb_sign_and_verify(kak, &secure_hdr->csk,
1261 sizeof(secure_hdr->csk) +
1262 sizeof(secure_hdr->csksig),
1263 &tmp_sig, "CSK") < 0)
1266 if (kwb_verify(kak_pub, &secure_hdr->csk,
1267 sizeof(secure_hdr->csk) +
1268 sizeof(secure_hdr->csksig),
1269 &tmp_sig, "CSK (2)") < 0)
1272 secure_hdr->csksig = tmp_sig;
1277 static int add_secure_header_v1(struct image_tool_params *params, uint8_t *ptr,
1278 int payloadsz, size_t headersz, uint8_t *image,
1279 struct secure_hdr_v1 *secure_hdr)
1281 struct image_cfg_element *e_jtagdelay;
1282 struct image_cfg_element *e_boxid;
1283 struct image_cfg_element *e_flashid;
1285 unsigned char *image_ptr;
1287 struct sig_v1 tmp_sig;
1288 bool specialized_img = image_get_spezialized_img();
1290 kwb_msg("Create secure header content\n");
1292 e_jtagdelay = image_find_option(IMAGE_CFG_JTAG_DELAY);
1293 e_boxid = image_find_option(IMAGE_CFG_BOX_ID);
1294 e_flashid = image_find_option(IMAGE_CFG_FLASH_ID);
1296 if (kwb_load_csk(params, &csk) < 0)
1299 secure_hdr->headertype = OPT_HDR_V1_SECURE_TYPE;
1300 secure_hdr->headersz_msb = 0;
1301 secure_hdr->headersz_lsb = cpu_to_le16(sizeof(struct secure_hdr_v1));
1303 secure_hdr->jtag_delay = e_jtagdelay->jtag_delay;
1304 if (e_boxid && specialized_img)
1305 secure_hdr->boxid = cpu_to_le32(e_boxid->boxid);
1306 if (e_flashid && specialized_img)
1307 secure_hdr->flashid = cpu_to_le32(e_flashid->flashid);
1309 if (kwb_sign_csk_with_kak(params, secure_hdr, csk))
1312 image_ptr = ptr + headersz;
1313 image_size = payloadsz - headersz;
1315 if (kwb_sign_and_verify(csk, image_ptr, image_size,
1316 &secure_hdr->imgsig, "image") < 0)
1319 if (kwb_sign_and_verify(csk, image, headersz, &tmp_sig, "header") < 0)
1322 secure_hdr->hdrsig = tmp_sig;
1324 kwb_dump_fuse_cmds(secure_hdr);
1329 static void finish_register_set_header_v1(uint8_t **cur, uint8_t **next_ext,
1330 struct register_set_hdr_v1 *register_set_hdr,
1331 int *datai, uint8_t delay)
1333 int size = sizeof(struct register_set_hdr_v1) + 8 * (*datai) + 4;
1335 register_set_hdr->headertype = OPT_HDR_V1_REGISTER_TYPE;
1336 register_set_hdr->headersz_lsb = cpu_to_le16(size & 0xFFFF);
1337 register_set_hdr->headersz_msb = size >> 16;
1338 register_set_hdr->data[*datai].last_entry.delay = delay;
1341 *next_ext = ®ister_set_hdr->data[*datai].last_entry.next;
1345 static void *image_create_v1(size_t *imagesz, struct image_tool_params *params,
1346 uint8_t *ptr, int payloadsz)
1348 struct image_cfg_element *e;
1349 struct main_hdr_v1 *main_hdr;
1350 struct opt_hdr_v1 *ohdr;
1351 struct register_set_hdr_v1 *register_set_hdr;
1352 struct secure_hdr_v1 *secure_hdr = NULL;
1354 uint8_t *image, *cur;
1356 uint8_t *next_ext = NULL;
1361 * Calculate the size of the header and the size of the
1364 headersz = image_headersz_v1(&hasext);
1368 image = malloc(headersz);
1370 fprintf(stderr, "Cannot allocate memory for image\n");
1374 memset(image, 0, headersz);
1376 main_hdr = (struct main_hdr_v1 *)image;
1378 cur += sizeof(struct main_hdr_v1);
1379 next_ext = &main_hdr->ext;
1381 /* Fill the main header */
1382 main_hdr->blocksize =
1383 cpu_to_le32(payloadsz);
1384 main_hdr->headersz_lsb = cpu_to_le16(headersz & 0xFFFF);
1385 main_hdr->headersz_msb = (headersz & 0xFFFF0000) >> 16;
1386 main_hdr->destaddr = cpu_to_le32(params->addr);
1387 main_hdr->execaddr = cpu_to_le32(params->ep);
1388 main_hdr->srcaddr = cpu_to_le32(headersz);
1389 main_hdr->ext = hasext;
1390 main_hdr->version = 1;
1391 main_hdr->blockid = image_get_bootfrom();
1393 e = image_find_option(IMAGE_CFG_NAND_BLKSZ);
1395 main_hdr->nandblocksize = e->nandblksz / (64 * 1024);
1396 e = image_find_option(IMAGE_CFG_NAND_PAGESZ);
1398 main_hdr->nandpagesize = cpu_to_le16(e->nandpagesz);
1399 e = image_find_option(IMAGE_CFG_NAND_BADBLK_LOCATION);
1401 main_hdr->nandbadblklocation = e->nandbadblklocation;
1402 e = image_find_option(IMAGE_CFG_BAUDRATE);
1404 main_hdr->options |= baudrate_to_option(e->baudrate);
1405 e = image_find_option(IMAGE_CFG_UART_PORT);
1407 main_hdr->options |= (e->uart_port & 3) << 3;
1408 e = image_find_option(IMAGE_CFG_UART_MPP);
1410 main_hdr->options |= (e->uart_mpp & 7) << 5;
1411 e = image_find_option(IMAGE_CFG_DEBUG);
1413 main_hdr->flags = e->debug ? 0x1 : 0;
1416 * For SATA srcaddr is specified in number of sectors starting from
1417 * sector 0. The main header is stored at sector number 1.
1418 * This expects the sector size to be 512 bytes.
1419 * Header size is already aligned.
1421 if (main_hdr->blockid == IBR_HDR_SATA_ID)
1422 main_hdr->srcaddr = cpu_to_le32(headersz / 512 + 1);
1425 * For SDIO srcaddr is specified in number of sectors starting from
1426 * sector 0. The main header is stored at sector number 0.
1427 * This expects sector size to be 512 bytes.
1428 * Header size is already aligned.
1430 if (main_hdr->blockid == IBR_HDR_SDIO_ID)
1431 main_hdr->srcaddr = cpu_to_le32(headersz / 512);
1433 /* For PCIe srcaddr is not used and must be set to 0xFFFFFFFF. */
1434 if (main_hdr->blockid == IBR_HDR_PEX_ID)
1435 main_hdr->srcaddr = cpu_to_le32(0xFFFFFFFF);
1437 if (image_get_csk_index() >= 0) {
1439 * only reserve the space here; we fill the header later since
1440 * we need the header to be complete to compute the signatures
1442 secure_hdr = (struct secure_hdr_v1 *)cur;
1443 cur += sizeof(struct secure_hdr_v1);
1445 next_ext = &secure_hdr->next;
1449 for (cfgi = 0; cfgi < cfgn; cfgi++) {
1450 e = &image_cfg[cfgi];
1451 if (e->type != IMAGE_CFG_DATA &&
1452 e->type != IMAGE_CFG_DATA_DELAY &&
1453 e->type != IMAGE_CFG_BINARY)
1457 register_set_hdr = (struct register_set_hdr_v1 *)cur;
1459 /* If delay is not specified, use the smallest possible value. */
1460 if (e->type == IMAGE_CFG_DATA_DELAY)
1461 delay = e->regdata_delay;
1463 delay = REGISTER_SET_HDR_OPT_DELAY_MS(0);
1466 * DATA_DELAY command is the last entry in the register set
1467 * header and BINARY command inserts new binary header.
1468 * Therefore BINARY command requires to finish register set
1469 * header if some DATA command was specified. And DATA_DELAY
1470 * command automatically finish register set header even when
1471 * there was no DATA command.
1473 if (e->type == IMAGE_CFG_DATA_DELAY ||
1474 (e->type == IMAGE_CFG_BINARY && datai != 0))
1475 finish_register_set_header_v1(&cur, &next_ext, register_set_hdr,
1478 if (e->type == IMAGE_CFG_DATA) {
1479 register_set_hdr->data[datai].entry.address =
1480 cpu_to_le32(e->regdata.raddr);
1481 register_set_hdr->data[datai].entry.value =
1482 cpu_to_le32(e->regdata.rdata);
1486 if (e->type == IMAGE_CFG_BINARY) {
1487 if (add_binary_header_v1(&cur, &next_ext, e, main_hdr))
1492 /* Set delay to the smallest possible value. */
1493 delay = REGISTER_SET_HDR_OPT_DELAY_MS(0);
1494 finish_register_set_header_v1(&cur, &next_ext, register_set_hdr,
1498 if (secure_hdr && add_secure_header_v1(params, ptr, payloadsz + headersz,
1499 headersz, image, secure_hdr))
1502 *imagesz = headersz;
1504 /* Fill the real header size without padding into the main header */
1505 headersz = sizeof(*main_hdr);
1506 for_each_opt_hdr_v1 (ohdr, main_hdr)
1507 headersz += opt_hdr_v1_size(ohdr);
1508 main_hdr->headersz_lsb = cpu_to_le16(headersz & 0xFFFF);
1509 main_hdr->headersz_msb = (headersz & 0xFFFF0000) >> 16;
1511 /* Calculate and set the header checksum */
1512 main_hdr->checksum = image_checksum8(main_hdr, headersz);
1517 static int recognize_keyword(char *keyword)
1521 for (kw_id = 1; kw_id < IMAGE_CFG_COUNT; ++kw_id)
1522 if (!strcmp(keyword, id_strs[kw_id]))
1528 static int image_create_config_parse_oneline(char *line,
1529 struct image_cfg_element *el)
1531 char *keyword, *saveptr, *value1, *value2;
1532 char delimiters[] = " \t";
1533 int keyword_id, ret, argi;
1534 char *unknown_msg = "Ignoring unknown line '%s'\n";
1536 keyword = strtok_r(line, delimiters, &saveptr);
1537 keyword_id = recognize_keyword(keyword);
1540 fprintf(stderr, unknown_msg, line);
1544 el->type = keyword_id;
1546 value1 = strtok_r(NULL, delimiters, &saveptr);
1549 fprintf(stderr, "Parameter missing in line '%s'\n", line);
1553 switch (keyword_id) {
1554 case IMAGE_CFG_VERSION:
1555 el->version = atoi(value1);
1558 if (strcmp(value1, "FEROCEON") == 0)
1560 else if (strcmp(value1, "SHEEVA") == 0)
1562 else if (strcmp(value1, "A9") == 0)
1565 fprintf(stderr, "Invalid CPU %s\n", value1);
1569 case IMAGE_CFG_BOOT_FROM:
1570 ret = image_boot_mode_id(value1);
1573 fprintf(stderr, "Invalid boot media '%s'\n", value1);
1578 case IMAGE_CFG_NAND_BLKSZ:
1579 el->nandblksz = strtoul(value1, NULL, 16);
1581 case IMAGE_CFG_NAND_BADBLK_LOCATION:
1582 el->nandbadblklocation = strtoul(value1, NULL, 16);
1584 case IMAGE_CFG_NAND_ECC_MODE:
1585 ret = image_nand_ecc_mode_id(value1);
1588 fprintf(stderr, "Invalid NAND ECC mode '%s'\n", value1);
1591 el->nandeccmode = ret;
1593 case IMAGE_CFG_NAND_PAGESZ:
1594 el->nandpagesz = strtoul(value1, NULL, 16);
1596 case IMAGE_CFG_BINARY:
1599 el->binary.file = strdup(value1);
1601 char *value = strtok_r(NULL, delimiters, &saveptr);
1607 if (!strcmp(value, "LOAD_ADDRESS")) {
1608 value = strtok_r(NULL, delimiters, &saveptr);
1611 "Missing address argument for BINARY LOAD_ADDRESS\n");
1614 el->binary.loadaddr = strtoul(value, &endptr, 16);
1617 "Invalid argument '%s' for BINARY LOAD_ADDRESS\n",
1621 value = strtok_r(NULL, delimiters, &saveptr);
1624 "Unexpected argument '%s' after BINARY LOAD_ADDRESS\n",
1631 el->binary.args[argi] = strtoul(value, &endptr, 16);
1633 fprintf(stderr, "Invalid argument '%s' for BINARY\n", value);
1637 if (argi >= BINARY_MAX_ARGS) {
1639 "Too many arguments for BINARY\n");
1643 el->binary.nargs = argi;
1645 case IMAGE_CFG_DATA:
1646 value2 = strtok_r(NULL, delimiters, &saveptr);
1648 if (!value1 || !value2) {
1650 "Invalid number of arguments for DATA\n");
1654 el->regdata.raddr = strtoul(value1, NULL, 16);
1655 el->regdata.rdata = strtoul(value2, NULL, 16);
1657 case IMAGE_CFG_DATA_DELAY:
1658 if (!strcmp(value1, "SDRAM_SETUP"))
1659 el->regdata_delay = REGISTER_SET_HDR_OPT_DELAY_SDRAM_SETUP;
1661 el->regdata_delay = REGISTER_SET_HDR_OPT_DELAY_MS(strtoul(value1, NULL, 10));
1663 case IMAGE_CFG_BAUDRATE:
1664 el->baudrate = strtoul(value1, NULL, 10);
1666 case IMAGE_CFG_UART_PORT:
1667 el->uart_port = strtoul(value1, NULL, 16);
1669 case IMAGE_CFG_UART_MPP:
1670 el->uart_mpp = strtoul(value1, NULL, 16);
1672 case IMAGE_CFG_DEBUG:
1673 el->debug = strtoul(value1, NULL, 10);
1676 el->key_name = strdup(value1);
1679 el->key_name = strdup(value1);
1681 case IMAGE_CFG_CSK_INDEX:
1682 el->csk_idx = strtol(value1, NULL, 0);
1684 case IMAGE_CFG_JTAG_DELAY:
1685 el->jtag_delay = strtoul(value1, NULL, 0);
1687 case IMAGE_CFG_BOX_ID:
1688 el->boxid = strtoul(value1, NULL, 0);
1690 case IMAGE_CFG_FLASH_ID:
1691 el->flashid = strtoul(value1, NULL, 0);
1693 case IMAGE_CFG_SEC_SPECIALIZED_IMG:
1694 el->sec_specialized_img = true;
1696 case IMAGE_CFG_SEC_COMMON_IMG:
1697 el->sec_specialized_img = false;
1699 case IMAGE_CFG_SEC_BOOT_DEV:
1700 el->sec_boot_dev = strtoul(value1, NULL, 0);
1702 case IMAGE_CFG_SEC_FUSE_DUMP:
1703 el->name = strdup(value1);
1706 fprintf(stderr, unknown_msg, line);
1713 * Parse the configuration file 'fcfg' into the array of configuration
1714 * elements 'image_cfg', and return the number of configuration
1715 * elements in 'cfgn'.
1717 static int image_create_config_parse(FILE *fcfg)
1722 /* Parse the configuration file */
1723 while (!feof(fcfg)) {
1727 /* Read the current line */
1728 memset(buf, 0, sizeof(buf));
1729 line = fgets(buf, sizeof(buf), fcfg);
1733 /* Ignore useless lines */
1734 if (line[0] == '\n' || line[0] == '#')
1737 /* Strip final newline */
1738 if (line[strlen(line) - 1] == '\n')
1739 line[strlen(line) - 1] = 0;
1741 /* Parse the current line */
1742 ret = image_create_config_parse_oneline(line,
1749 if (cfgi >= IMAGE_CFG_ELEMENT_MAX) {
1751 "Too many configuration elements in .cfg file\n");
1760 static int image_get_version(void)
1762 struct image_cfg_element *e;
1764 e = image_find_option(IMAGE_CFG_VERSION);
1771 static void kwbimage_set_header(void *ptr, struct stat *sbuf, int ifd,
1772 struct image_tool_params *params)
1777 size_t headersz = 0;
1784 * Do not use sbuf->st_size as it contains size with padding.
1785 * We need original image data size, so stat original file.
1787 if (stat(params->datafile, &s)) {
1788 fprintf(stderr, "Could not stat data file %s: %s\n",
1789 params->datafile, strerror(errno));
1792 datasz = ALIGN(s.st_size, 4);
1794 fcfg = fopen(params->imagename, "r");
1796 fprintf(stderr, "Could not open input file %s\n",
1801 image_cfg = malloc(IMAGE_CFG_ELEMENT_MAX *
1802 sizeof(struct image_cfg_element));
1804 fprintf(stderr, "Cannot allocate memory\n");
1809 memset(image_cfg, 0,
1810 IMAGE_CFG_ELEMENT_MAX * sizeof(struct image_cfg_element));
1813 ret = image_create_config_parse(fcfg);
1820 version = image_get_version();
1823 * Fallback to version 0 if no version is provided in the
1828 image = image_create_v0(&headersz, params, datasz + 4);
1832 image = image_create_v1(&headersz, params, ptr, datasz + 4);
1836 fprintf(stderr, "Unsupported version %d\n", version);
1842 fprintf(stderr, "Could not create image\n");
1849 /* Build and add image data checksum */
1850 checksum = cpu_to_le32(image_checksum32((uint8_t *)ptr + headersz,
1852 memcpy((uint8_t *)ptr + headersz + datasz, &checksum, sizeof(uint32_t));
1854 /* Finally copy the header into the image area */
1855 memcpy(ptr, image, headersz);
1860 static void kwbimage_print_header(const void *ptr)
1862 struct main_hdr_v0 *mhdr = (struct main_hdr_v0 *)ptr;
1863 struct opt_hdr_v1 *ohdr;
1865 printf("Image Type: MVEBU Boot from %s Image\n",
1866 image_boot_mode_name(mhdr->blockid));
1867 printf("Image version:%d\n", kwbimage_version(ptr));
1869 for_each_opt_hdr_v1 (ohdr, mhdr) {
1870 if (ohdr->headertype == OPT_HDR_V1_BINARY_TYPE) {
1871 printf("BIN Hdr Size: ");
1872 genimg_print_size(opt_hdr_v1_size(ohdr) - 12 -
1877 printf("Data Size: ");
1878 genimg_print_size(mhdr->blocksize - sizeof(uint32_t));
1879 printf("Load Address: %08x\n", mhdr->destaddr);
1880 printf("Entry Point: %08x\n", mhdr->execaddr);
1883 static int kwbimage_check_image_types(uint8_t type)
1885 if (type == IH_TYPE_KWBIMAGE)
1886 return EXIT_SUCCESS;
1888 return EXIT_FAILURE;
1891 static int kwbimage_verify_header(unsigned char *ptr, int image_size,
1892 struct image_tool_params *params)
1894 size_t header_size = kwbheader_size(ptr);
1900 if (header_size > image_size)
1901 return -FDT_ERR_BADSTRUCTURE;
1903 if (!main_hdr_checksum_ok(ptr))
1904 return -FDT_ERR_BADSTRUCTURE;
1906 /* Only version 0 extended header has checksum */
1907 if (kwbimage_version(ptr) == 0) {
1908 struct main_hdr_v0 *mhdr = (struct main_hdr_v0 *)ptr;
1910 if (mhdr->ext & 0x1) {
1911 struct ext_hdr_v0 *ext_hdr = (void *)(mhdr + 1);
1913 csum = image_checksum8(ext_hdr, sizeof(*ext_hdr) - 1);
1914 if (csum != ext_hdr->checksum)
1915 return -FDT_ERR_BADSTRUCTURE;
1918 blockid = mhdr->blockid;
1919 offset = le32_to_cpu(mhdr->srcaddr);
1920 size = le32_to_cpu(mhdr->blocksize);
1921 } else if (kwbimage_version(ptr) == 1) {
1922 struct main_hdr_v1 *mhdr = (struct main_hdr_v1 *)ptr;
1923 const uint8_t *mhdr_end;
1924 struct opt_hdr_v1 *ohdr;
1926 mhdr_end = (uint8_t *)mhdr + header_size;
1927 for_each_opt_hdr_v1 (ohdr, ptr)
1928 if (!opt_hdr_v1_valid_size(ohdr, mhdr_end))
1929 return -FDT_ERR_BADSTRUCTURE;
1931 blockid = mhdr->blockid;
1932 offset = le32_to_cpu(mhdr->srcaddr);
1933 size = le32_to_cpu(mhdr->blocksize);
1935 return -FDT_ERR_BADSTRUCTURE;
1939 * For SATA srcaddr is specified in number of sectors.
1940 * The main header is must be stored at sector number 1.
1941 * This expects that sector size is 512 bytes and recalculates
1942 * data offset to bytes relative to the main header.
1944 if (blockid == IBR_HDR_SATA_ID) {
1946 return -FDT_ERR_BADSTRUCTURE;
1952 * For SDIO srcaddr is specified in number of sectors.
1953 * This expects that sector size is 512 bytes and recalculates
1954 * data offset to bytes.
1956 if (blockid == IBR_HDR_SDIO_ID)
1960 * For PCIe srcaddr is always set to 0xFFFFFFFF.
1961 * This expects that data starts after all headers.
1963 if (blockid == IBR_HDR_PEX_ID && offset == 0xFFFFFFFF)
1964 offset = header_size;
1966 if (offset > image_size || offset % 4 != 0)
1967 return -FDT_ERR_BADSTRUCTURE;
1969 if (size < 4 || offset + size > image_size || size % 4 != 0)
1970 return -FDT_ERR_BADSTRUCTURE;
1972 if (image_checksum32(ptr + offset, size - 4) !=
1973 *(uint32_t *)(ptr + offset + size - 4))
1974 return -FDT_ERR_BADSTRUCTURE;
1979 static int kwbimage_generate(struct image_tool_params *params,
1980 struct image_type_params *tparams)
1990 fcfg = fopen(params->imagename, "r");
1992 fprintf(stderr, "Could not open input file %s\n",
1997 if (stat(params->datafile, &s)) {
1998 fprintf(stderr, "Could not stat data file %s: %s\n",
1999 params->datafile, strerror(errno));
2003 image_cfg = malloc(IMAGE_CFG_ELEMENT_MAX *
2004 sizeof(struct image_cfg_element));
2006 fprintf(stderr, "Cannot allocate memory\n");
2011 memset(image_cfg, 0,
2012 IMAGE_CFG_ELEMENT_MAX * sizeof(struct image_cfg_element));
2015 ret = image_create_config_parse(fcfg);
2022 bootfrom = image_get_bootfrom();
2023 version = image_get_version();
2026 * Fallback to version 0 if no version is provided in the
2031 alloc_len = image_headersz_v0(NULL);
2035 alloc_len = image_headersz_v1(NULL);
2040 if (alloc_len > 192*1024) {
2041 fprintf(stderr, "Header is too big (%u bytes), maximal kwbimage header size is %u bytes\n", alloc_len, 192*1024);
2048 fprintf(stderr, "Unsupported version %d\n", version);
2055 hdr = malloc(alloc_len);
2057 fprintf(stderr, "%s: malloc return failure: %s\n",
2058 params->cmdname, strerror(errno));
2062 memset(hdr, 0, alloc_len);
2063 tparams->header_size = alloc_len;
2067 * The resulting image needs to be 4-byte aligned. At least
2068 * the Marvell hdrparser tool complains if its unaligned.
2069 * After the image data is stored 4-byte checksum.
2070 * Final UART image must be aligned to 128 bytes.
2071 * Final SPI and NAND images must be aligned to 256 bytes.
2072 * Final SATA and SDIO images must be aligned to 512 bytes.
2074 if (bootfrom == IBR_HDR_SPI_ID || bootfrom == IBR_HDR_NAND_ID)
2075 return 4 + (256 - (alloc_len + s.st_size + 4) % 256) % 256;
2076 else if (bootfrom == IBR_HDR_SATA_ID || bootfrom == IBR_HDR_SDIO_ID)
2077 return 4 + (512 - (alloc_len + s.st_size + 4) % 512) % 512;
2078 else if (bootfrom == IBR_HDR_UART_ID)
2079 return 4 + (128 - (alloc_len + s.st_size + 4) % 128) % 128;
2081 return 4 + (4 - s.st_size % 4) % 4;
2084 static int kwbimage_extract_subimage(void *ptr, struct image_tool_params *params)
2086 struct main_hdr_v1 *mhdr = (struct main_hdr_v1 *)ptr;
2087 size_t header_size = kwbheader_size(ptr);
2088 struct opt_hdr_v1 *ohdr;
2089 int idx = params->pflag;
2095 for_each_opt_hdr_v1 (ohdr, ptr) {
2096 if (ohdr->headertype != OPT_HDR_V1_BINARY_TYPE)
2099 if (idx == cur_idx) {
2100 image = (ulong)&ohdr->data[4 + 4 * ohdr->data[0]];
2101 size = opt_hdr_v1_size(ohdr) - 12 - 4 * ohdr->data[0];
2108 if (idx != cur_idx) {
2109 printf("Image %d is not present\n", idx);
2113 offset = le32_to_cpu(mhdr->srcaddr);
2115 if (mhdr->blockid == IBR_HDR_SATA_ID) {
2120 if (mhdr->blockid == IBR_HDR_SDIO_ID)
2123 if (mhdr->blockid == IBR_HDR_PEX_ID && offset == 0xFFFFFFFF)
2124 offset = header_size;
2126 image = (ulong)((uint8_t *)ptr + offset);
2127 size = le32_to_cpu(mhdr->blocksize) - 4;
2130 return imagetool_save_subimage(params->outfile, image, size);
2134 * Report Error if xflag is set in addition to default
2136 static int kwbimage_check_params(struct image_tool_params *params)
2138 if (!params->iflag && (!params->imagename || !strlen(params->imagename))) {
2139 char *msg = "Configuration file for kwbimage creation omitted";
2141 fprintf(stderr, "Error:%s - %s\n", params->cmdname, msg);
2145 return (params->dflag && (params->fflag || params->lflag)) ||
2146 (params->fflag && (params->dflag || params->lflag)) ||
2147 (params->lflag && (params->dflag || params->fflag)) ||
2152 * kwbimage type parameters definition
2156 "Marvell MVEBU Boot Image support",
2159 kwbimage_check_params,
2160 kwbimage_verify_header,
2161 kwbimage_print_header,
2162 kwbimage_set_header,
2163 kwbimage_extract_subimage,
2164 kwbimage_check_image_types,