kwbimage.c 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017
  1. // SPDX-License-Identifier: GPL-2.0+
  2. /*
  3. * Image manipulator for Marvell SoCs
  4. * supports Kirkwood, Dove, Armada 370, Armada XP, Armada 375, Armada 38x and
  5. * Armada 39x
  6. *
  7. * (C) Copyright 2013 Thomas Petazzoni
  8. * <thomas.petazzoni@free-electrons.com>
  9. */
  10. #define OPENSSL_API_COMPAT 0x10101000L
  11. #include "imagetool.h"
  12. #include <limits.h>
  13. #include <image.h>
  14. #include <stdarg.h>
  15. #include <stdint.h>
  16. #include "kwbimage.h"
  17. #include <openssl/bn.h>
  18. #include <openssl/rsa.h>
  19. #include <openssl/pem.h>
  20. #include <openssl/err.h>
  21. #include <openssl/evp.h>
  22. #if OPENSSL_VERSION_NUMBER < 0x10100000L || \
  23. (defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER < 0x2070000fL)
  24. static void RSA_get0_key(const RSA *r,
  25. const BIGNUM **n, const BIGNUM **e, const BIGNUM **d)
  26. {
  27. if (n != NULL)
  28. *n = r->n;
  29. if (e != NULL)
  30. *e = r->e;
  31. if (d != NULL)
  32. *d = r->d;
  33. }
  34. #elif !defined(LIBRESSL_VERSION_NUMBER)
  35. void EVP_MD_CTX_cleanup(EVP_MD_CTX *ctx)
  36. {
  37. EVP_MD_CTX_reset(ctx);
  38. }
  39. #endif
  40. static struct image_cfg_element *image_cfg;
  41. static int cfgn;
  42. static int verbose_mode;
  43. struct boot_mode {
  44. unsigned int id;
  45. const char *name;
  46. };
  47. /*
  48. * SHA2-256 hash
  49. */
  50. struct hash_v1 {
  51. uint8_t hash[32];
  52. };
  53. struct boot_mode boot_modes[] = {
  54. { IBR_HDR_I2C_ID, "i2c" },
  55. { IBR_HDR_SPI_ID, "spi" },
  56. { IBR_HDR_NAND_ID, "nand" },
  57. { IBR_HDR_SATA_ID, "sata" },
  58. { IBR_HDR_PEX_ID, "pex" },
  59. { IBR_HDR_UART_ID, "uart" },
  60. { IBR_HDR_SDIO_ID, "sdio" },
  61. {},
  62. };
  63. struct nand_ecc_mode {
  64. unsigned int id;
  65. const char *name;
  66. };
  67. struct nand_ecc_mode nand_ecc_modes[] = {
  68. { IBR_HDR_ECC_DEFAULT, "default" },
  69. { IBR_HDR_ECC_FORCED_HAMMING, "hamming" },
  70. { IBR_HDR_ECC_FORCED_RS, "rs" },
  71. { IBR_HDR_ECC_DISABLED, "disabled" },
  72. {},
  73. };
  74. /* Used to identify an undefined execution or destination address */
  75. #define ADDR_INVALID ((uint32_t)-1)
  76. #define BINARY_MAX_ARGS 255
  77. /* In-memory representation of a line of the configuration file */
  78. enum image_cfg_type {
  79. IMAGE_CFG_VERSION = 0x1,
  80. IMAGE_CFG_BOOT_FROM,
  81. IMAGE_CFG_DEST_ADDR,
  82. IMAGE_CFG_EXEC_ADDR,
  83. IMAGE_CFG_NAND_BLKSZ,
  84. IMAGE_CFG_NAND_BADBLK_LOCATION,
  85. IMAGE_CFG_NAND_ECC_MODE,
  86. IMAGE_CFG_NAND_PAGESZ,
  87. IMAGE_CFG_BINARY,
  88. IMAGE_CFG_DATA,
  89. IMAGE_CFG_DATA_DELAY,
  90. IMAGE_CFG_BAUDRATE,
  91. IMAGE_CFG_UART_PORT,
  92. IMAGE_CFG_UART_MPP,
  93. IMAGE_CFG_DEBUG,
  94. IMAGE_CFG_KAK,
  95. IMAGE_CFG_CSK,
  96. IMAGE_CFG_CSK_INDEX,
  97. IMAGE_CFG_JTAG_DELAY,
  98. IMAGE_CFG_BOX_ID,
  99. IMAGE_CFG_FLASH_ID,
  100. IMAGE_CFG_SEC_COMMON_IMG,
  101. IMAGE_CFG_SEC_SPECIALIZED_IMG,
  102. IMAGE_CFG_SEC_BOOT_DEV,
  103. IMAGE_CFG_SEC_FUSE_DUMP,
  104. IMAGE_CFG_COUNT
  105. } type;
  106. static const char * const id_strs[] = {
  107. [IMAGE_CFG_VERSION] = "VERSION",
  108. [IMAGE_CFG_BOOT_FROM] = "BOOT_FROM",
  109. [IMAGE_CFG_DEST_ADDR] = "DEST_ADDR",
  110. [IMAGE_CFG_EXEC_ADDR] = "EXEC_ADDR",
  111. [IMAGE_CFG_NAND_BLKSZ] = "NAND_BLKSZ",
  112. [IMAGE_CFG_NAND_BADBLK_LOCATION] = "NAND_BADBLK_LOCATION",
  113. [IMAGE_CFG_NAND_ECC_MODE] = "NAND_ECC_MODE",
  114. [IMAGE_CFG_NAND_PAGESZ] = "NAND_PAGE_SIZE",
  115. [IMAGE_CFG_BINARY] = "BINARY",
  116. [IMAGE_CFG_DATA] = "DATA",
  117. [IMAGE_CFG_DATA_DELAY] = "DATA_DELAY",
  118. [IMAGE_CFG_BAUDRATE] = "BAUDRATE",
  119. [IMAGE_CFG_UART_PORT] = "UART_PORT",
  120. [IMAGE_CFG_UART_MPP] = "UART_MPP",
  121. [IMAGE_CFG_DEBUG] = "DEBUG",
  122. [IMAGE_CFG_KAK] = "KAK",
  123. [IMAGE_CFG_CSK] = "CSK",
  124. [IMAGE_CFG_CSK_INDEX] = "CSK_INDEX",
  125. [IMAGE_CFG_JTAG_DELAY] = "JTAG_DELAY",
  126. [IMAGE_CFG_BOX_ID] = "BOX_ID",
  127. [IMAGE_CFG_FLASH_ID] = "FLASH_ID",
  128. [IMAGE_CFG_SEC_COMMON_IMG] = "SEC_COMMON_IMG",
  129. [IMAGE_CFG_SEC_SPECIALIZED_IMG] = "SEC_SPECIALIZED_IMG",
  130. [IMAGE_CFG_SEC_BOOT_DEV] = "SEC_BOOT_DEV",
  131. [IMAGE_CFG_SEC_FUSE_DUMP] = "SEC_FUSE_DUMP"
  132. };
  133. struct image_cfg_element {
  134. enum image_cfg_type type;
  135. union {
  136. unsigned int version;
  137. unsigned int bootfrom;
  138. struct {
  139. const char *file;
  140. unsigned int args[BINARY_MAX_ARGS];
  141. unsigned int nargs;
  142. } binary;
  143. unsigned int dstaddr;
  144. unsigned int execaddr;
  145. unsigned int nandblksz;
  146. unsigned int nandbadblklocation;
  147. unsigned int nandeccmode;
  148. unsigned int nandpagesz;
  149. struct ext_hdr_v0_reg regdata;
  150. unsigned int regdata_delay;
  151. unsigned int baudrate;
  152. unsigned int uart_port;
  153. unsigned int uart_mpp;
  154. unsigned int debug;
  155. const char *key_name;
  156. int csk_idx;
  157. uint8_t jtag_delay;
  158. uint32_t boxid;
  159. uint32_t flashid;
  160. bool sec_specialized_img;
  161. unsigned int sec_boot_dev;
  162. const char *name;
  163. };
  164. };
  165. #define IMAGE_CFG_ELEMENT_MAX 256
  166. /*
  167. * Utility functions to manipulate boot mode and ecc modes (convert
  168. * them back and forth between description strings and the
  169. * corresponding numerical identifiers).
  170. */
  171. static const char *image_boot_mode_name(unsigned int id)
  172. {
  173. int i;
  174. for (i = 0; boot_modes[i].name; i++)
  175. if (boot_modes[i].id == id)
  176. return boot_modes[i].name;
  177. return NULL;
  178. }
  179. int image_boot_mode_id(const char *boot_mode_name)
  180. {
  181. int i;
  182. for (i = 0; boot_modes[i].name; i++)
  183. if (!strcmp(boot_modes[i].name, boot_mode_name))
  184. return boot_modes[i].id;
  185. return -1;
  186. }
  187. int image_nand_ecc_mode_id(const char *nand_ecc_mode_name)
  188. {
  189. int i;
  190. for (i = 0; nand_ecc_modes[i].name; i++)
  191. if (!strcmp(nand_ecc_modes[i].name, nand_ecc_mode_name))
  192. return nand_ecc_modes[i].id;
  193. return -1;
  194. }
  195. static struct image_cfg_element *
  196. image_find_option(unsigned int optiontype)
  197. {
  198. int i;
  199. for (i = 0; i < cfgn; i++) {
  200. if (image_cfg[i].type == optiontype)
  201. return &image_cfg[i];
  202. }
  203. return NULL;
  204. }
  205. static unsigned int
  206. image_count_options(unsigned int optiontype)
  207. {
  208. int i;
  209. unsigned int count = 0;
  210. for (i = 0; i < cfgn; i++)
  211. if (image_cfg[i].type == optiontype)
  212. count++;
  213. return count;
  214. }
  215. static int image_get_csk_index(void)
  216. {
  217. struct image_cfg_element *e;
  218. e = image_find_option(IMAGE_CFG_CSK_INDEX);
  219. if (!e)
  220. return -1;
  221. return e->csk_idx;
  222. }
  223. static bool image_get_spezialized_img(void)
  224. {
  225. struct image_cfg_element *e;
  226. e = image_find_option(IMAGE_CFG_SEC_SPECIALIZED_IMG);
  227. if (!e)
  228. return false;
  229. return e->sec_specialized_img;
  230. }
  231. static int image_get_bootfrom(void)
  232. {
  233. struct image_cfg_element *e;
  234. e = image_find_option(IMAGE_CFG_BOOT_FROM);
  235. if (!e)
  236. /* fallback to SPI if no BOOT_FROM is not provided */
  237. return IBR_HDR_SPI_ID;
  238. return e->bootfrom;
  239. }
  240. /*
  241. * Compute a 8-bit checksum of a memory area. This algorithm follows
  242. * the requirements of the Marvell SoC BootROM specifications.
  243. */
  244. static uint8_t image_checksum8(void *start, uint32_t len)
  245. {
  246. uint8_t csum = 0;
  247. uint8_t *p = start;
  248. /* check len and return zero checksum if invalid */
  249. if (!len)
  250. return 0;
  251. do {
  252. csum += *p;
  253. p++;
  254. } while (--len);
  255. return csum;
  256. }
  257. /*
  258. * Verify checksum over a complete header that includes the checksum field.
  259. * Return 1 when OK, otherwise 0.
  260. */
  261. static int main_hdr_checksum_ok(void *hdr)
  262. {
  263. /* Offsets of checksum in v0 and v1 headers are the same */
  264. struct main_hdr_v0 *main_hdr = (struct main_hdr_v0 *)hdr;
  265. uint8_t checksum;
  266. checksum = image_checksum8(hdr, kwbheader_size_for_csum(hdr));
  267. /* Calculated checksum includes the header checksum field. Compensate
  268. * for that.
  269. */
  270. checksum -= main_hdr->checksum;
  271. return checksum == main_hdr->checksum;
  272. }
  273. static uint32_t image_checksum32(void *start, uint32_t len)
  274. {
  275. uint32_t csum = 0;
  276. uint32_t *p = start;
  277. /* check len and return zero checksum if invalid */
  278. if (!len)
  279. return 0;
  280. if (len % sizeof(uint32_t)) {
  281. fprintf(stderr, "Length %d is not in multiple of %zu\n",
  282. len, sizeof(uint32_t));
  283. return 0;
  284. }
  285. do {
  286. csum += *p;
  287. p++;
  288. len -= sizeof(uint32_t);
  289. } while (len > 0);
  290. return csum;
  291. }
  292. static uint8_t baudrate_to_option(unsigned int baudrate)
  293. {
  294. switch (baudrate) {
  295. case 2400:
  296. return MAIN_HDR_V1_OPT_BAUD_2400;
  297. case 4800:
  298. return MAIN_HDR_V1_OPT_BAUD_4800;
  299. case 9600:
  300. return MAIN_HDR_V1_OPT_BAUD_9600;
  301. case 19200:
  302. return MAIN_HDR_V1_OPT_BAUD_19200;
  303. case 38400:
  304. return MAIN_HDR_V1_OPT_BAUD_38400;
  305. case 57600:
  306. return MAIN_HDR_V1_OPT_BAUD_57600;
  307. case 115200:
  308. return MAIN_HDR_V1_OPT_BAUD_115200;
  309. default:
  310. return MAIN_HDR_V1_OPT_BAUD_DEFAULT;
  311. }
  312. }
  313. static void kwb_msg(const char *fmt, ...)
  314. {
  315. if (verbose_mode) {
  316. va_list ap;
  317. va_start(ap, fmt);
  318. vfprintf(stdout, fmt, ap);
  319. va_end(ap);
  320. }
  321. }
  322. static int openssl_err(const char *msg)
  323. {
  324. unsigned long ssl_err = ERR_get_error();
  325. fprintf(stderr, "%s", msg);
  326. fprintf(stderr, ": %s\n",
  327. ERR_error_string(ssl_err, 0));
  328. return -1;
  329. }
  330. static int kwb_load_rsa_key(const char *keydir, const char *name, RSA **p_rsa)
  331. {
  332. char path[PATH_MAX];
  333. RSA *rsa;
  334. FILE *f;
  335. if (!keydir)
  336. keydir = ".";
  337. snprintf(path, sizeof(path), "%s/%s.key", keydir, name);
  338. f = fopen(path, "r");
  339. if (!f) {
  340. fprintf(stderr, "Couldn't open RSA private key: '%s': %s\n",
  341. path, strerror(errno));
  342. return -ENOENT;
  343. }
  344. rsa = PEM_read_RSAPrivateKey(f, 0, NULL, "");
  345. if (!rsa) {
  346. openssl_err("Failure reading private key");
  347. fclose(f);
  348. return -EPROTO;
  349. }
  350. fclose(f);
  351. *p_rsa = rsa;
  352. return 0;
  353. }
  354. static int kwb_load_cfg_key(struct image_tool_params *params,
  355. unsigned int cfg_option, const char *key_name,
  356. RSA **p_key)
  357. {
  358. struct image_cfg_element *e_key;
  359. RSA *key;
  360. int res;
  361. *p_key = NULL;
  362. e_key = image_find_option(cfg_option);
  363. if (!e_key) {
  364. fprintf(stderr, "%s not configured\n", key_name);
  365. return -ENOENT;
  366. }
  367. res = kwb_load_rsa_key(params->keydir, e_key->key_name, &key);
  368. if (res < 0) {
  369. fprintf(stderr, "Failed to load %s\n", key_name);
  370. return -ENOENT;
  371. }
  372. *p_key = key;
  373. return 0;
  374. }
  375. static int kwb_load_kak(struct image_tool_params *params, RSA **p_kak)
  376. {
  377. return kwb_load_cfg_key(params, IMAGE_CFG_KAK, "KAK", p_kak);
  378. }
  379. static int kwb_load_csk(struct image_tool_params *params, RSA **p_csk)
  380. {
  381. return kwb_load_cfg_key(params, IMAGE_CFG_CSK, "CSK", p_csk);
  382. }
  383. static int kwb_compute_pubkey_hash(struct pubkey_der_v1 *pk,
  384. struct hash_v1 *hash)
  385. {
  386. EVP_MD_CTX *ctx;
  387. unsigned int key_size;
  388. unsigned int hash_size;
  389. int ret = 0;
  390. if (!pk || !hash || pk->key[0] != 0x30 || pk->key[1] != 0x82)
  391. return -EINVAL;
  392. key_size = (pk->key[2] << 8) + pk->key[3] + 4;
  393. ctx = EVP_MD_CTX_create();
  394. if (!ctx)
  395. return openssl_err("EVP context creation failed");
  396. EVP_MD_CTX_init(ctx);
  397. if (!EVP_DigestInit(ctx, EVP_sha256())) {
  398. ret = openssl_err("Digest setup failed");
  399. goto hash_err_ctx;
  400. }
  401. if (!EVP_DigestUpdate(ctx, pk->key, key_size)) {
  402. ret = openssl_err("Hashing data failed");
  403. goto hash_err_ctx;
  404. }
  405. if (!EVP_DigestFinal(ctx, hash->hash, &hash_size)) {
  406. ret = openssl_err("Could not obtain hash");
  407. goto hash_err_ctx;
  408. }
  409. EVP_MD_CTX_cleanup(ctx);
  410. hash_err_ctx:
  411. EVP_MD_CTX_destroy(ctx);
  412. return ret;
  413. }
  414. static int kwb_import_pubkey(RSA **key, struct pubkey_der_v1 *src, char *keyname)
  415. {
  416. RSA *rsa;
  417. const unsigned char *ptr;
  418. if (!key || !src)
  419. goto fail;
  420. ptr = src->key;
  421. rsa = d2i_RSAPublicKey(key, &ptr, sizeof(src->key));
  422. if (!rsa) {
  423. openssl_err("error decoding public key");
  424. goto fail;
  425. }
  426. return 0;
  427. fail:
  428. fprintf(stderr, "Failed to decode %s pubkey\n", keyname);
  429. return -EINVAL;
  430. }
  431. static int kwb_export_pubkey(RSA *key, struct pubkey_der_v1 *dst, FILE *hashf,
  432. char *keyname)
  433. {
  434. int size_exp, size_mod, size_seq;
  435. const BIGNUM *key_e, *key_n;
  436. uint8_t *cur;
  437. char *errmsg = "Failed to encode %s\n";
  438. RSA_get0_key(key, NULL, &key_e, NULL);
  439. RSA_get0_key(key, &key_n, NULL, NULL);
  440. if (!key || !key_e || !key_n || !dst) {
  441. fprintf(stderr, "export pk failed: (%p, %p, %p, %p)",
  442. key, key_e, key_n, dst);
  443. fprintf(stderr, errmsg, keyname);
  444. return -EINVAL;
  445. }
  446. /*
  447. * According to the specs, the key should be PKCS#1 DER encoded.
  448. * But unfortunately the really required encoding seems to be different;
  449. * it violates DER...! (But it still conformes to BER.)
  450. * (Length always in long form w/ 2 byte length code; no leading zero
  451. * when MSB of first byte is set...)
  452. * So we cannot use the encoding func provided by OpenSSL and have to
  453. * do the encoding manually.
  454. */
  455. size_exp = BN_num_bytes(key_e);
  456. size_mod = BN_num_bytes(key_n);
  457. size_seq = 4 + size_mod + 4 + size_exp;
  458. if (size_mod > 256) {
  459. fprintf(stderr, "export pk failed: wrong mod size: %d\n",
  460. size_mod);
  461. fprintf(stderr, errmsg, keyname);
  462. return -EINVAL;
  463. }
  464. if (4 + size_seq > sizeof(dst->key)) {
  465. fprintf(stderr, "export pk failed: seq too large (%d, %zu)\n",
  466. 4 + size_seq, sizeof(dst->key));
  467. fprintf(stderr, errmsg, keyname);
  468. return -ENOBUFS;
  469. }
  470. cur = dst->key;
  471. /* PKCS#1 (RFC3447) RSAPublicKey structure */
  472. *cur++ = 0x30; /* SEQUENCE */
  473. *cur++ = 0x82;
  474. *cur++ = (size_seq >> 8) & 0xFF;
  475. *cur++ = size_seq & 0xFF;
  476. /* Modulus */
  477. *cur++ = 0x02; /* INTEGER */
  478. *cur++ = 0x82;
  479. *cur++ = (size_mod >> 8) & 0xFF;
  480. *cur++ = size_mod & 0xFF;
  481. BN_bn2bin(key_n, cur);
  482. cur += size_mod;
  483. /* Exponent */
  484. *cur++ = 0x02; /* INTEGER */
  485. *cur++ = 0x82;
  486. *cur++ = (size_exp >> 8) & 0xFF;
  487. *cur++ = size_exp & 0xFF;
  488. BN_bn2bin(key_e, cur);
  489. if (hashf) {
  490. struct hash_v1 pk_hash;
  491. int i;
  492. int ret = 0;
  493. ret = kwb_compute_pubkey_hash(dst, &pk_hash);
  494. if (ret < 0) {
  495. fprintf(stderr, errmsg, keyname);
  496. return ret;
  497. }
  498. fprintf(hashf, "SHA256 = ");
  499. for (i = 0 ; i < sizeof(pk_hash.hash); ++i)
  500. fprintf(hashf, "%02X", pk_hash.hash[i]);
  501. fprintf(hashf, "\n");
  502. }
  503. return 0;
  504. }
  505. int kwb_sign(RSA *key, void *data, int datasz, struct sig_v1 *sig, char *signame)
  506. {
  507. EVP_PKEY *evp_key;
  508. EVP_MD_CTX *ctx;
  509. unsigned int sig_size;
  510. int size;
  511. int ret = 0;
  512. evp_key = EVP_PKEY_new();
  513. if (!evp_key)
  514. return openssl_err("EVP_PKEY object creation failed");
  515. if (!EVP_PKEY_set1_RSA(evp_key, key)) {
  516. ret = openssl_err("EVP key setup failed");
  517. goto err_key;
  518. }
  519. size = EVP_PKEY_size(evp_key);
  520. if (size > sizeof(sig->sig)) {
  521. fprintf(stderr, "Buffer to small for signature (%d bytes)\n",
  522. size);
  523. ret = -ENOBUFS;
  524. goto err_key;
  525. }
  526. ctx = EVP_MD_CTX_create();
  527. if (!ctx) {
  528. ret = openssl_err("EVP context creation failed");
  529. goto err_key;
  530. }
  531. EVP_MD_CTX_init(ctx);
  532. if (!EVP_SignInit(ctx, EVP_sha256())) {
  533. ret = openssl_err("Signer setup failed");
  534. goto err_ctx;
  535. }
  536. if (!EVP_SignUpdate(ctx, data, datasz)) {
  537. ret = openssl_err("Signing data failed");
  538. goto err_ctx;
  539. }
  540. if (!EVP_SignFinal(ctx, sig->sig, &sig_size, evp_key)) {
  541. ret = openssl_err("Could not obtain signature");
  542. goto err_ctx;
  543. }
  544. EVP_MD_CTX_cleanup(ctx);
  545. EVP_MD_CTX_destroy(ctx);
  546. EVP_PKEY_free(evp_key);
  547. return 0;
  548. err_ctx:
  549. EVP_MD_CTX_destroy(ctx);
  550. err_key:
  551. EVP_PKEY_free(evp_key);
  552. fprintf(stderr, "Failed to create %s signature\n", signame);
  553. return ret;
  554. }
  555. int kwb_verify(RSA *key, void *data, int datasz, struct sig_v1 *sig,
  556. char *signame)
  557. {
  558. EVP_PKEY *evp_key;
  559. EVP_MD_CTX *ctx;
  560. int size;
  561. int ret = 0;
  562. evp_key = EVP_PKEY_new();
  563. if (!evp_key)
  564. return openssl_err("EVP_PKEY object creation failed");
  565. if (!EVP_PKEY_set1_RSA(evp_key, key)) {
  566. ret = openssl_err("EVP key setup failed");
  567. goto err_key;
  568. }
  569. size = EVP_PKEY_size(evp_key);
  570. if (size > sizeof(sig->sig)) {
  571. fprintf(stderr, "Invalid signature size (%d bytes)\n",
  572. size);
  573. ret = -EINVAL;
  574. goto err_key;
  575. }
  576. ctx = EVP_MD_CTX_create();
  577. if (!ctx) {
  578. ret = openssl_err("EVP context creation failed");
  579. goto err_key;
  580. }
  581. EVP_MD_CTX_init(ctx);
  582. if (!EVP_VerifyInit(ctx, EVP_sha256())) {
  583. ret = openssl_err("Verifier setup failed");
  584. goto err_ctx;
  585. }
  586. if (!EVP_VerifyUpdate(ctx, data, datasz)) {
  587. ret = openssl_err("Hashing data failed");
  588. goto err_ctx;
  589. }
  590. if (EVP_VerifyFinal(ctx, sig->sig, sizeof(sig->sig), evp_key) != 1) {
  591. ret = openssl_err("Could not verify signature");
  592. goto err_ctx;
  593. }
  594. EVP_MD_CTX_cleanup(ctx);
  595. EVP_MD_CTX_destroy(ctx);
  596. EVP_PKEY_free(evp_key);
  597. return 0;
  598. err_ctx:
  599. EVP_MD_CTX_destroy(ctx);
  600. err_key:
  601. EVP_PKEY_free(evp_key);
  602. fprintf(stderr, "Failed to verify %s signature\n", signame);
  603. return ret;
  604. }
  605. int kwb_sign_and_verify(RSA *key, void *data, int datasz, struct sig_v1 *sig,
  606. char *signame)
  607. {
  608. if (kwb_sign(key, data, datasz, sig, signame) < 0)
  609. return -1;
  610. if (kwb_verify(key, data, datasz, sig, signame) < 0)
  611. return -1;
  612. return 0;
  613. }
  614. int kwb_dump_fuse_cmds_38x(FILE *out, struct secure_hdr_v1 *sec_hdr)
  615. {
  616. struct hash_v1 kak_pub_hash;
  617. struct image_cfg_element *e;
  618. unsigned int fuse_line;
  619. int i, idx;
  620. uint8_t *ptr;
  621. uint32_t val;
  622. int ret = 0;
  623. if (!out || !sec_hdr)
  624. return -EINVAL;
  625. ret = kwb_compute_pubkey_hash(&sec_hdr->kak, &kak_pub_hash);
  626. if (ret < 0)
  627. goto done;
  628. fprintf(out, "# burn KAK pub key hash\n");
  629. ptr = kak_pub_hash.hash;
  630. for (fuse_line = 26; fuse_line <= 30; ++fuse_line) {
  631. fprintf(out, "fuse prog -y %u 0 ", fuse_line);
  632. for (i = 4; i-- > 0;)
  633. fprintf(out, "%02hx", (ushort)ptr[i]);
  634. ptr += 4;
  635. fprintf(out, " 00");
  636. if (fuse_line < 30) {
  637. for (i = 3; i-- > 0;)
  638. fprintf(out, "%02hx", (ushort)ptr[i]);
  639. ptr += 3;
  640. } else {
  641. fprintf(out, "000000");
  642. }
  643. fprintf(out, " 1\n");
  644. }
  645. fprintf(out, "# burn CSK selection\n");
  646. idx = image_get_csk_index();
  647. if (idx < 0 || idx > 15) {
  648. ret = -EINVAL;
  649. goto done;
  650. }
  651. if (idx > 0) {
  652. for (fuse_line = 31; fuse_line < 31 + idx; ++fuse_line)
  653. fprintf(out, "fuse prog -y %u 0 00000001 00000000 1\n",
  654. fuse_line);
  655. } else {
  656. fprintf(out, "# CSK index is 0; no mods needed\n");
  657. }
  658. e = image_find_option(IMAGE_CFG_BOX_ID);
  659. if (e) {
  660. fprintf(out, "# set box ID\n");
  661. fprintf(out, "fuse prog -y 48 0 %08x 00000000 1\n", e->boxid);
  662. }
  663. e = image_find_option(IMAGE_CFG_FLASH_ID);
  664. if (e) {
  665. fprintf(out, "# set flash ID\n");
  666. fprintf(out, "fuse prog -y 47 0 %08x 00000000 1\n", e->flashid);
  667. }
  668. fprintf(out, "# enable secure mode ");
  669. fprintf(out, "(must be the last fuse line written)\n");
  670. val = 1;
  671. e = image_find_option(IMAGE_CFG_SEC_BOOT_DEV);
  672. if (!e) {
  673. fprintf(stderr, "ERROR: secured mode boot device not given\n");
  674. ret = -EINVAL;
  675. goto done;
  676. }
  677. if (e->sec_boot_dev > 0xff) {
  678. fprintf(stderr, "ERROR: secured mode boot device invalid\n");
  679. ret = -EINVAL;
  680. goto done;
  681. }
  682. val |= (e->sec_boot_dev << 8);
  683. fprintf(out, "fuse prog -y 24 0 %08x 0103e0a9 1\n", val);
  684. fprintf(out, "# lock (unused) fuse lines (0-23)s\n");
  685. for (fuse_line = 0; fuse_line < 24; ++fuse_line)
  686. fprintf(out, "fuse prog -y %u 2 1\n", fuse_line);
  687. fprintf(out, "# OK, that's all :-)\n");
  688. done:
  689. return ret;
  690. }
  691. static int kwb_dump_fuse_cmds(struct secure_hdr_v1 *sec_hdr)
  692. {
  693. int ret = 0;
  694. struct image_cfg_element *e;
  695. e = image_find_option(IMAGE_CFG_SEC_FUSE_DUMP);
  696. if (!e)
  697. return 0;
  698. if (!strcmp(e->name, "a38x")) {
  699. FILE *out = fopen("kwb_fuses_a38x.txt", "w+");
  700. if (!out) {
  701. fprintf(stderr, "Couldn't open eFuse settings: '%s': %s\n",
  702. "kwb_fuses_a38x.txt", strerror(errno));
  703. return -ENOENT;
  704. }
  705. kwb_dump_fuse_cmds_38x(out, sec_hdr);
  706. fclose(out);
  707. goto done;
  708. }
  709. ret = -ENOSYS;
  710. done:
  711. return ret;
  712. }
  713. static size_t image_headersz_align(size_t headersz, uint8_t blockid)
  714. {
  715. /*
  716. * Header needs to be 4-byte aligned, which is already ensured by code
  717. * above. Moreover UART images must have header aligned to 128 bytes
  718. * (xmodem block size), NAND images to 256 bytes (ECC calculation),
  719. * and SATA and SDIO images to 512 bytes (storage block size).
  720. * Note that SPI images do not have to have header size aligned
  721. * to 256 bytes because it is possible to read from SPI storage from
  722. * any offset (read offset does not have to be aligned to block size).
  723. */
  724. if (blockid == IBR_HDR_UART_ID)
  725. return ALIGN(headersz, 128);
  726. else if (blockid == IBR_HDR_NAND_ID)
  727. return ALIGN(headersz, 256);
  728. else if (blockid == IBR_HDR_SATA_ID || blockid == IBR_HDR_SDIO_ID)
  729. return ALIGN(headersz, 512);
  730. else
  731. return headersz;
  732. }
  733. static size_t image_headersz_v0(int *hasext)
  734. {
  735. size_t headersz;
  736. headersz = sizeof(struct main_hdr_v0);
  737. if (image_count_options(IMAGE_CFG_DATA) > 0) {
  738. headersz += sizeof(struct ext_hdr_v0);
  739. if (hasext)
  740. *hasext = 1;
  741. }
  742. return image_headersz_align(headersz, image_get_bootfrom());
  743. }
  744. static void *image_create_v0(size_t *imagesz, struct image_tool_params *params,
  745. int payloadsz)
  746. {
  747. struct image_cfg_element *e;
  748. size_t headersz;
  749. struct main_hdr_v0 *main_hdr;
  750. uint8_t *image;
  751. int has_ext = 0;
  752. /*
  753. * Calculate the size of the header and the size of the
  754. * payload
  755. */
  756. headersz = image_headersz_v0(&has_ext);
  757. image = malloc(headersz);
  758. if (!image) {
  759. fprintf(stderr, "Cannot allocate memory for image\n");
  760. return NULL;
  761. }
  762. memset(image, 0, headersz);
  763. main_hdr = (struct main_hdr_v0 *)image;
  764. /* Fill in the main header */
  765. main_hdr->blocksize =
  766. cpu_to_le32(payloadsz);
  767. main_hdr->srcaddr = cpu_to_le32(headersz);
  768. main_hdr->ext = has_ext;
  769. main_hdr->version = 0;
  770. main_hdr->destaddr = cpu_to_le32(params->addr);
  771. main_hdr->execaddr = cpu_to_le32(params->ep);
  772. main_hdr->blockid = image_get_bootfrom();
  773. e = image_find_option(IMAGE_CFG_NAND_ECC_MODE);
  774. if (e)
  775. main_hdr->nandeccmode = e->nandeccmode;
  776. e = image_find_option(IMAGE_CFG_NAND_PAGESZ);
  777. if (e)
  778. main_hdr->nandpagesize = cpu_to_le16(e->nandpagesz);
  779. main_hdr->checksum = image_checksum8(image,
  780. sizeof(struct main_hdr_v0));
  781. /*
  782. * For SATA srcaddr is specified in number of sectors starting from
  783. * sector 0. The main header is stored at sector number 1.
  784. * This expects the sector size to be 512 bytes.
  785. * Header size is already aligned.
  786. */
  787. if (main_hdr->blockid == IBR_HDR_SATA_ID)
  788. main_hdr->srcaddr = cpu_to_le32(headersz / 512 + 1);
  789. /*
  790. * For SDIO srcaddr is specified in number of sectors starting from
  791. * sector 0. The main header is stored at sector number 0.
  792. * This expects sector size to be 512 bytes.
  793. * Header size is already aligned.
  794. */
  795. if (main_hdr->blockid == IBR_HDR_SDIO_ID)
  796. main_hdr->srcaddr = cpu_to_le32(headersz / 512);
  797. /* For PCIe srcaddr is not used and must be set to 0xFFFFFFFF. */
  798. if (main_hdr->blockid == IBR_HDR_PEX_ID)
  799. main_hdr->srcaddr = cpu_to_le32(0xFFFFFFFF);
  800. /* Generate the ext header */
  801. if (has_ext) {
  802. struct ext_hdr_v0 *ext_hdr;
  803. int cfgi, datai;
  804. ext_hdr = (struct ext_hdr_v0 *)
  805. (image + sizeof(struct main_hdr_v0));
  806. ext_hdr->offset = cpu_to_le32(0x40);
  807. for (cfgi = 0, datai = 0; cfgi < cfgn; cfgi++) {
  808. e = &image_cfg[cfgi];
  809. if (e->type != IMAGE_CFG_DATA)
  810. continue;
  811. ext_hdr->rcfg[datai].raddr =
  812. cpu_to_le32(e->regdata.raddr);
  813. ext_hdr->rcfg[datai].rdata =
  814. cpu_to_le32(e->regdata.rdata);
  815. datai++;
  816. }
  817. ext_hdr->checksum = image_checksum8(ext_hdr,
  818. sizeof(struct ext_hdr_v0));
  819. }
  820. *imagesz = headersz;
  821. return image;
  822. }
  823. static size_t image_headersz_v1(int *hasext)
  824. {
  825. struct image_cfg_element *binarye;
  826. unsigned int count;
  827. size_t headersz;
  828. int cfgi;
  829. /*
  830. * Calculate the size of the header and the size of the
  831. * payload
  832. */
  833. headersz = sizeof(struct main_hdr_v1);
  834. if (image_get_csk_index() >= 0) {
  835. headersz += sizeof(struct secure_hdr_v1);
  836. if (hasext)
  837. *hasext = 1;
  838. }
  839. count = image_count_options(IMAGE_CFG_DATA);
  840. if (count > 0)
  841. headersz += sizeof(struct register_set_hdr_v1) + 8 * count + 4;
  842. for (cfgi = 0; cfgi < cfgn; cfgi++) {
  843. int ret;
  844. struct stat s;
  845. binarye = &image_cfg[cfgi];
  846. if (binarye->type != IMAGE_CFG_BINARY)
  847. continue;
  848. ret = stat(binarye->binary.file, &s);
  849. if (ret < 0) {
  850. char cwd[PATH_MAX];
  851. char *dir = cwd;
  852. memset(cwd, 0, sizeof(cwd));
  853. if (!getcwd(cwd, sizeof(cwd))) {
  854. dir = "current working directory";
  855. perror("getcwd() failed");
  856. }
  857. fprintf(stderr,
  858. "Didn't find the file '%s' in '%s' which is mandatory to generate the image\n"
  859. "This file generally contains the DDR3 training code, and should be extracted from an existing bootable\n"
  860. "image for your board. Use 'dumpimage -T kwbimage -p 0' to extract it from an existing image.\n",
  861. binarye->binary.file, dir);
  862. return 0;
  863. }
  864. headersz += sizeof(struct opt_hdr_v1) + sizeof(uint32_t) +
  865. (binarye->binary.nargs) * sizeof(uint32_t);
  866. headersz = ALIGN(headersz, 16);
  867. headersz += ALIGN(s.st_size, 4) + sizeof(uint32_t);
  868. if (hasext)
  869. *hasext = 1;
  870. }
  871. return image_headersz_align(headersz, image_get_bootfrom());
  872. }
  873. int add_binary_header_v1(uint8_t **cur, uint8_t **next_ext,
  874. struct image_cfg_element *binarye,
  875. struct main_hdr_v1 *main_hdr)
  876. {
  877. struct opt_hdr_v1 *hdr = (struct opt_hdr_v1 *)*cur;
  878. uint32_t add_args;
  879. uint32_t offset;
  880. uint32_t *args;
  881. size_t binhdrsz;
  882. struct stat s;
  883. int argi;
  884. FILE *bin;
  885. int ret;
  886. hdr->headertype = OPT_HDR_V1_BINARY_TYPE;
  887. bin = fopen(binarye->binary.file, "r");
  888. if (!bin) {
  889. fprintf(stderr, "Cannot open binary file %s\n",
  890. binarye->binary.file);
  891. return -1;
  892. }
  893. if (fstat(fileno(bin), &s)) {
  894. fprintf(stderr, "Cannot stat binary file %s\n",
  895. binarye->binary.file);
  896. goto err_close;
  897. }
  898. *cur += sizeof(struct opt_hdr_v1);
  899. args = (uint32_t *)*cur;
  900. *args = cpu_to_le32(binarye->binary.nargs);
  901. args++;
  902. for (argi = 0; argi < binarye->binary.nargs; argi++)
  903. args[argi] = cpu_to_le32(binarye->binary.args[argi]);
  904. *cur += (binarye->binary.nargs + 1) * sizeof(uint32_t);
  905. /*
  906. * ARM executable code inside the BIN header on some mvebu platforms
  907. * (e.g. A370, AXP) must always be aligned with the 128-bit boundary.
  908. * This requirement can be met by inserting dummy arguments into
  909. * BIN header, if needed.
  910. */
  911. offset = *cur - (uint8_t *)main_hdr;
  912. add_args = ((16 - offset % 16) % 16) / sizeof(uint32_t);
  913. if (add_args) {
  914. *(args - 1) = cpu_to_le32(binarye->binary.nargs + add_args);
  915. *cur += add_args * sizeof(uint32_t);
  916. }
  917. ret = fread(*cur, s.st_size, 1, bin);
  918. if (ret != 1) {
  919. fprintf(stderr,
  920. "Could not read binary image %s\n",
  921. binarye->binary.file);
  922. goto err_close;
  923. }
  924. fclose(bin);
  925. *cur += ALIGN(s.st_size, 4);
  926. *((uint32_t *)*cur) = 0x00000000;
  927. **next_ext = 1;
  928. *next_ext = *cur;
  929. *cur += sizeof(uint32_t);
  930. binhdrsz = sizeof(struct opt_hdr_v1) +
  931. (binarye->binary.nargs + add_args + 2) * sizeof(uint32_t) +
  932. ALIGN(s.st_size, 4);
  933. hdr->headersz_lsb = cpu_to_le16(binhdrsz & 0xFFFF);
  934. hdr->headersz_msb = (binhdrsz & 0xFFFF0000) >> 16;
  935. return 0;
  936. err_close:
  937. fclose(bin);
  938. return -1;
  939. }
  940. int export_pub_kak_hash(RSA *kak, struct secure_hdr_v1 *secure_hdr)
  941. {
  942. FILE *hashf;
  943. int res;
  944. hashf = fopen("pub_kak_hash.txt", "w");
  945. if (!hashf) {
  946. fprintf(stderr, "Couldn't open hash file: '%s': %s\n",
  947. "pub_kak_hash.txt", strerror(errno));
  948. return 1;
  949. }
  950. res = kwb_export_pubkey(kak, &secure_hdr->kak, hashf, "KAK");
  951. fclose(hashf);
  952. return res < 0 ? 1 : 0;
  953. }
  954. int kwb_sign_csk_with_kak(struct image_tool_params *params,
  955. struct secure_hdr_v1 *secure_hdr, RSA *csk)
  956. {
  957. RSA *kak = NULL;
  958. RSA *kak_pub = NULL;
  959. int csk_idx = image_get_csk_index();
  960. struct sig_v1 tmp_sig;
  961. if (csk_idx < 0 || csk_idx > 15) {
  962. fprintf(stderr, "Invalid CSK index %d\n", csk_idx);
  963. return 1;
  964. }
  965. if (kwb_load_kak(params, &kak) < 0)
  966. return 1;
  967. if (export_pub_kak_hash(kak, secure_hdr))
  968. return 1;
  969. if (kwb_import_pubkey(&kak_pub, &secure_hdr->kak, "KAK") < 0)
  970. return 1;
  971. if (kwb_export_pubkey(csk, &secure_hdr->csk[csk_idx], NULL, "CSK") < 0)
  972. return 1;
  973. if (kwb_sign_and_verify(kak, &secure_hdr->csk,
  974. sizeof(secure_hdr->csk) +
  975. sizeof(secure_hdr->csksig),
  976. &tmp_sig, "CSK") < 0)
  977. return 1;
  978. if (kwb_verify(kak_pub, &secure_hdr->csk,
  979. sizeof(secure_hdr->csk) +
  980. sizeof(secure_hdr->csksig),
  981. &tmp_sig, "CSK (2)") < 0)
  982. return 1;
  983. secure_hdr->csksig = tmp_sig;
  984. return 0;
  985. }
  986. int add_secure_header_v1(struct image_tool_params *params, uint8_t *ptr,
  987. int payloadsz, size_t headersz, uint8_t *image,
  988. struct secure_hdr_v1 *secure_hdr)
  989. {
  990. struct image_cfg_element *e_jtagdelay;
  991. struct image_cfg_element *e_boxid;
  992. struct image_cfg_element *e_flashid;
  993. RSA *csk = NULL;
  994. unsigned char *image_ptr;
  995. size_t image_size;
  996. struct sig_v1 tmp_sig;
  997. bool specialized_img = image_get_spezialized_img();
  998. kwb_msg("Create secure header content\n");
  999. e_jtagdelay = image_find_option(IMAGE_CFG_JTAG_DELAY);
  1000. e_boxid = image_find_option(IMAGE_CFG_BOX_ID);
  1001. e_flashid = image_find_option(IMAGE_CFG_FLASH_ID);
  1002. if (kwb_load_csk(params, &csk) < 0)
  1003. return 1;
  1004. secure_hdr->headertype = OPT_HDR_V1_SECURE_TYPE;
  1005. secure_hdr->headersz_msb = 0;
  1006. secure_hdr->headersz_lsb = cpu_to_le16(sizeof(struct secure_hdr_v1));
  1007. if (e_jtagdelay)
  1008. secure_hdr->jtag_delay = e_jtagdelay->jtag_delay;
  1009. if (e_boxid && specialized_img)
  1010. secure_hdr->boxid = cpu_to_le32(e_boxid->boxid);
  1011. if (e_flashid && specialized_img)
  1012. secure_hdr->flashid = cpu_to_le32(e_flashid->flashid);
  1013. if (kwb_sign_csk_with_kak(params, secure_hdr, csk))
  1014. return 1;
  1015. image_ptr = ptr + headersz;
  1016. image_size = payloadsz - headersz;
  1017. if (kwb_sign_and_verify(csk, image_ptr, image_size,
  1018. &secure_hdr->imgsig, "image") < 0)
  1019. return 1;
  1020. if (kwb_sign_and_verify(csk, image, headersz, &tmp_sig, "header") < 0)
  1021. return 1;
  1022. secure_hdr->hdrsig = tmp_sig;
  1023. kwb_dump_fuse_cmds(secure_hdr);
  1024. return 0;
  1025. }
  1026. static void *image_create_v1(size_t *imagesz, struct image_tool_params *params,
  1027. uint8_t *ptr, int payloadsz)
  1028. {
  1029. struct image_cfg_element *e;
  1030. struct main_hdr_v1 *main_hdr;
  1031. struct opt_hdr_v1 *ohdr;
  1032. struct register_set_hdr_v1 *register_set_hdr;
  1033. struct secure_hdr_v1 *secure_hdr = NULL;
  1034. size_t headersz;
  1035. uint8_t *image, *cur;
  1036. int hasext = 0;
  1037. uint8_t *next_ext = NULL;
  1038. int cfgi, datai, size;
  1039. /*
  1040. * Calculate the size of the header and the size of the
  1041. * payload
  1042. */
  1043. headersz = image_headersz_v1(&hasext);
  1044. if (headersz == 0)
  1045. return NULL;
  1046. image = malloc(headersz);
  1047. if (!image) {
  1048. fprintf(stderr, "Cannot allocate memory for image\n");
  1049. return NULL;
  1050. }
  1051. memset(image, 0, headersz);
  1052. main_hdr = (struct main_hdr_v1 *)image;
  1053. cur = image;
  1054. cur += sizeof(struct main_hdr_v1);
  1055. next_ext = &main_hdr->ext;
  1056. /* Fill the main header */
  1057. main_hdr->blocksize =
  1058. cpu_to_le32(payloadsz);
  1059. main_hdr->headersz_lsb = cpu_to_le16(headersz & 0xFFFF);
  1060. main_hdr->headersz_msb = (headersz & 0xFFFF0000) >> 16;
  1061. main_hdr->destaddr = cpu_to_le32(params->addr);
  1062. main_hdr->execaddr = cpu_to_le32(params->ep);
  1063. main_hdr->srcaddr = cpu_to_le32(headersz);
  1064. main_hdr->ext = hasext;
  1065. main_hdr->version = 1;
  1066. main_hdr->blockid = image_get_bootfrom();
  1067. e = image_find_option(IMAGE_CFG_NAND_BLKSZ);
  1068. if (e)
  1069. main_hdr->nandblocksize = e->nandblksz / (64 * 1024);
  1070. e = image_find_option(IMAGE_CFG_NAND_PAGESZ);
  1071. if (e)
  1072. main_hdr->nandpagesize = cpu_to_le16(e->nandpagesz);
  1073. e = image_find_option(IMAGE_CFG_NAND_BADBLK_LOCATION);
  1074. if (e)
  1075. main_hdr->nandbadblklocation = e->nandbadblklocation;
  1076. e = image_find_option(IMAGE_CFG_BAUDRATE);
  1077. if (e)
  1078. main_hdr->options |= baudrate_to_option(e->baudrate);
  1079. e = image_find_option(IMAGE_CFG_UART_PORT);
  1080. if (e)
  1081. main_hdr->options |= (e->uart_port & 3) << 3;
  1082. e = image_find_option(IMAGE_CFG_UART_MPP);
  1083. if (e)
  1084. main_hdr->options |= (e->uart_mpp & 7) << 5;
  1085. e = image_find_option(IMAGE_CFG_DEBUG);
  1086. if (e)
  1087. main_hdr->flags = e->debug ? 0x1 : 0;
  1088. /*
  1089. * For SATA srcaddr is specified in number of sectors starting from
  1090. * sector 0. The main header is stored at sector number 1.
  1091. * This expects the sector size to be 512 bytes.
  1092. * Header size is already aligned.
  1093. */
  1094. if (main_hdr->blockid == IBR_HDR_SATA_ID)
  1095. main_hdr->srcaddr = cpu_to_le32(headersz / 512 + 1);
  1096. /*
  1097. * For SDIO srcaddr is specified in number of sectors starting from
  1098. * sector 0. The main header is stored at sector number 0.
  1099. * This expects sector size to be 512 bytes.
  1100. * Header size is already aligned.
  1101. */
  1102. if (main_hdr->blockid == IBR_HDR_SDIO_ID)
  1103. main_hdr->srcaddr = cpu_to_le32(headersz / 512);
  1104. /* For PCIe srcaddr is not used and must be set to 0xFFFFFFFF. */
  1105. if (main_hdr->blockid == IBR_HDR_PEX_ID)
  1106. main_hdr->srcaddr = cpu_to_le32(0xFFFFFFFF);
  1107. if (image_get_csk_index() >= 0) {
  1108. /*
  1109. * only reserve the space here; we fill the header later since
  1110. * we need the header to be complete to compute the signatures
  1111. */
  1112. secure_hdr = (struct secure_hdr_v1 *)cur;
  1113. cur += sizeof(struct secure_hdr_v1);
  1114. *next_ext = 1;
  1115. next_ext = &secure_hdr->next;
  1116. }
  1117. datai = 0;
  1118. register_set_hdr = (struct register_set_hdr_v1 *)cur;
  1119. for (cfgi = 0; cfgi < cfgn; cfgi++) {
  1120. e = &image_cfg[cfgi];
  1121. if (e->type != IMAGE_CFG_DATA &&
  1122. e->type != IMAGE_CFG_DATA_DELAY)
  1123. continue;
  1124. if (e->type == IMAGE_CFG_DATA_DELAY) {
  1125. size = sizeof(struct register_set_hdr_v1) + 8 * datai + 4;
  1126. register_set_hdr->headertype = OPT_HDR_V1_REGISTER_TYPE;
  1127. register_set_hdr->headersz_lsb = cpu_to_le16(size & 0xFFFF);
  1128. register_set_hdr->headersz_msb = size >> 16;
  1129. register_set_hdr->data[datai].last_entry.delay = e->regdata_delay;
  1130. cur += size;
  1131. *next_ext = 1;
  1132. next_ext = &register_set_hdr->data[datai].last_entry.next;
  1133. datai = 0;
  1134. continue;
  1135. }
  1136. register_set_hdr->data[datai].entry.address =
  1137. cpu_to_le32(e->regdata.raddr);
  1138. register_set_hdr->data[datai].entry.value =
  1139. cpu_to_le32(e->regdata.rdata);
  1140. datai++;
  1141. }
  1142. if (datai != 0) {
  1143. size = sizeof(struct register_set_hdr_v1) + 8 * datai + 4;
  1144. register_set_hdr->headertype = OPT_HDR_V1_REGISTER_TYPE;
  1145. register_set_hdr->headersz_lsb = cpu_to_le16(size & 0xFFFF);
  1146. register_set_hdr->headersz_msb = size >> 16;
  1147. /* Set delay to the smallest possible value 1ms. */
  1148. register_set_hdr->data[datai].last_entry.delay = 1;
  1149. cur += size;
  1150. *next_ext = 1;
  1151. next_ext = &register_set_hdr->data[datai].last_entry.next;
  1152. }
  1153. for (cfgi = 0; cfgi < cfgn; cfgi++) {
  1154. e = &image_cfg[cfgi];
  1155. if (e->type != IMAGE_CFG_BINARY)
  1156. continue;
  1157. if (add_binary_header_v1(&cur, &next_ext, e, main_hdr))
  1158. return NULL;
  1159. }
  1160. if (secure_hdr && add_secure_header_v1(params, ptr, payloadsz + headersz,
  1161. headersz, image, secure_hdr))
  1162. return NULL;
  1163. /* Calculate and set the header checksum */
  1164. main_hdr->checksum = image_checksum8(main_hdr, headersz);
  1165. *imagesz = headersz;
  1166. /* Fill the real header size without padding into the main header */
  1167. headersz = sizeof(*main_hdr);
  1168. for_each_opt_hdr_v1 (ohdr, main_hdr)
  1169. headersz += opt_hdr_v1_size(ohdr);
  1170. main_hdr->headersz_lsb = cpu_to_le16(headersz & 0xFFFF);
  1171. main_hdr->headersz_msb = (headersz & 0xFFFF0000) >> 16;
  1172. return image;
  1173. }
  1174. int recognize_keyword(char *keyword)
  1175. {
  1176. int kw_id;
  1177. for (kw_id = 1; kw_id < IMAGE_CFG_COUNT; ++kw_id)
  1178. if (!strcmp(keyword, id_strs[kw_id]))
  1179. return kw_id;
  1180. return 0;
  1181. }
  1182. static int image_create_config_parse_oneline(char *line,
  1183. struct image_cfg_element *el)
  1184. {
  1185. char *keyword, *saveptr, *value1, *value2;
  1186. char delimiters[] = " \t";
  1187. int keyword_id, ret, argi;
  1188. char *unknown_msg = "Ignoring unknown line '%s'\n";
  1189. keyword = strtok_r(line, delimiters, &saveptr);
  1190. keyword_id = recognize_keyword(keyword);
  1191. if (!keyword_id) {
  1192. fprintf(stderr, unknown_msg, line);
  1193. return 0;
  1194. }
  1195. el->type = keyword_id;
  1196. value1 = strtok_r(NULL, delimiters, &saveptr);
  1197. if (!value1) {
  1198. fprintf(stderr, "Parameter missing in line '%s'\n", line);
  1199. return -1;
  1200. }
  1201. switch (keyword_id) {
  1202. case IMAGE_CFG_VERSION:
  1203. el->version = atoi(value1);
  1204. break;
  1205. case IMAGE_CFG_BOOT_FROM:
  1206. ret = image_boot_mode_id(value1);
  1207. if (ret < 0) {
  1208. fprintf(stderr, "Invalid boot media '%s'\n", value1);
  1209. return -1;
  1210. }
  1211. el->bootfrom = ret;
  1212. break;
  1213. case IMAGE_CFG_NAND_BLKSZ:
  1214. el->nandblksz = strtoul(value1, NULL, 16);
  1215. break;
  1216. case IMAGE_CFG_NAND_BADBLK_LOCATION:
  1217. el->nandbadblklocation = strtoul(value1, NULL, 16);
  1218. break;
  1219. case IMAGE_CFG_NAND_ECC_MODE:
  1220. ret = image_nand_ecc_mode_id(value1);
  1221. if (ret < 0) {
  1222. fprintf(stderr, "Invalid NAND ECC mode '%s'\n", value1);
  1223. return -1;
  1224. }
  1225. el->nandeccmode = ret;
  1226. break;
  1227. case IMAGE_CFG_NAND_PAGESZ:
  1228. el->nandpagesz = strtoul(value1, NULL, 16);
  1229. break;
  1230. case IMAGE_CFG_BINARY:
  1231. argi = 0;
  1232. el->binary.file = strdup(value1);
  1233. while (1) {
  1234. char *value = strtok_r(NULL, delimiters, &saveptr);
  1235. if (!value)
  1236. break;
  1237. el->binary.args[argi] = strtoul(value, NULL, 16);
  1238. argi++;
  1239. if (argi >= BINARY_MAX_ARGS) {
  1240. fprintf(stderr,
  1241. "Too many arguments for BINARY\n");
  1242. return -1;
  1243. }
  1244. }
  1245. el->binary.nargs = argi;
  1246. break;
  1247. case IMAGE_CFG_DATA:
  1248. value2 = strtok_r(NULL, delimiters, &saveptr);
  1249. if (!value1 || !value2) {
  1250. fprintf(stderr,
  1251. "Invalid number of arguments for DATA\n");
  1252. return -1;
  1253. }
  1254. el->regdata.raddr = strtoul(value1, NULL, 16);
  1255. el->regdata.rdata = strtoul(value2, NULL, 16);
  1256. break;
  1257. case IMAGE_CFG_DATA_DELAY:
  1258. if (!strcmp(value1, "SDRAM_SETUP"))
  1259. el->regdata_delay = REGISTER_SET_HDR_OPT_DELAY_SDRAM_SETUP;
  1260. else
  1261. el->regdata_delay = REGISTER_SET_HDR_OPT_DELAY_MS(strtoul(value1, NULL, 10));
  1262. break;
  1263. case IMAGE_CFG_BAUDRATE:
  1264. el->baudrate = strtoul(value1, NULL, 10);
  1265. break;
  1266. case IMAGE_CFG_UART_PORT:
  1267. el->uart_port = strtoul(value1, NULL, 16);
  1268. break;
  1269. case IMAGE_CFG_UART_MPP:
  1270. el->uart_mpp = strtoul(value1, NULL, 16);
  1271. break;
  1272. case IMAGE_CFG_DEBUG:
  1273. el->debug = strtoul(value1, NULL, 10);
  1274. break;
  1275. case IMAGE_CFG_KAK:
  1276. el->key_name = strdup(value1);
  1277. break;
  1278. case IMAGE_CFG_CSK:
  1279. el->key_name = strdup(value1);
  1280. break;
  1281. case IMAGE_CFG_CSK_INDEX:
  1282. el->csk_idx = strtol(value1, NULL, 0);
  1283. break;
  1284. case IMAGE_CFG_JTAG_DELAY:
  1285. el->jtag_delay = strtoul(value1, NULL, 0);
  1286. break;
  1287. case IMAGE_CFG_BOX_ID:
  1288. el->boxid = strtoul(value1, NULL, 0);
  1289. break;
  1290. case IMAGE_CFG_FLASH_ID:
  1291. el->flashid = strtoul(value1, NULL, 0);
  1292. break;
  1293. case IMAGE_CFG_SEC_SPECIALIZED_IMG:
  1294. el->sec_specialized_img = true;
  1295. break;
  1296. case IMAGE_CFG_SEC_COMMON_IMG:
  1297. el->sec_specialized_img = false;
  1298. break;
  1299. case IMAGE_CFG_SEC_BOOT_DEV:
  1300. el->sec_boot_dev = strtoul(value1, NULL, 0);
  1301. break;
  1302. case IMAGE_CFG_SEC_FUSE_DUMP:
  1303. el->name = strdup(value1);
  1304. break;
  1305. default:
  1306. fprintf(stderr, unknown_msg, line);
  1307. }
  1308. return 0;
  1309. }
  1310. /*
  1311. * Parse the configuration file 'fcfg' into the array of configuration
  1312. * elements 'image_cfg', and return the number of configuration
  1313. * elements in 'cfgn'.
  1314. */
  1315. static int image_create_config_parse(FILE *fcfg)
  1316. {
  1317. int ret;
  1318. int cfgi = 0;
  1319. /* Parse the configuration file */
  1320. while (!feof(fcfg)) {
  1321. char *line;
  1322. char buf[256];
  1323. /* Read the current line */
  1324. memset(buf, 0, sizeof(buf));
  1325. line = fgets(buf, sizeof(buf), fcfg);
  1326. if (!line)
  1327. break;
  1328. /* Ignore useless lines */
  1329. if (line[0] == '\n' || line[0] == '#')
  1330. continue;
  1331. /* Strip final newline */
  1332. if (line[strlen(line) - 1] == '\n')
  1333. line[strlen(line) - 1] = 0;
  1334. /* Parse the current line */
  1335. ret = image_create_config_parse_oneline(line,
  1336. &image_cfg[cfgi]);
  1337. if (ret)
  1338. return ret;
  1339. cfgi++;
  1340. if (cfgi >= IMAGE_CFG_ELEMENT_MAX) {
  1341. fprintf(stderr,
  1342. "Too many configuration elements in .cfg file\n");
  1343. return -1;
  1344. }
  1345. }
  1346. cfgn = cfgi;
  1347. return 0;
  1348. }
  1349. static int image_get_version(void)
  1350. {
  1351. struct image_cfg_element *e;
  1352. e = image_find_option(IMAGE_CFG_VERSION);
  1353. if (!e)
  1354. return -1;
  1355. return e->version;
  1356. }
  1357. static void kwbimage_set_header(void *ptr, struct stat *sbuf, int ifd,
  1358. struct image_tool_params *params)
  1359. {
  1360. FILE *fcfg;
  1361. void *image = NULL;
  1362. int version;
  1363. size_t headersz = 0;
  1364. size_t datasz;
  1365. uint32_t checksum;
  1366. struct stat s;
  1367. int ret;
  1368. /*
  1369. * Do not use sbuf->st_size as it contains size with padding.
  1370. * We need original image data size, so stat original file.
  1371. */
  1372. if (stat(params->datafile, &s)) {
  1373. fprintf(stderr, "Could not stat data file %s: %s\n",
  1374. params->datafile, strerror(errno));
  1375. exit(EXIT_FAILURE);
  1376. }
  1377. datasz = ALIGN(s.st_size, 4);
  1378. fcfg = fopen(params->imagename, "r");
  1379. if (!fcfg) {
  1380. fprintf(stderr, "Could not open input file %s\n",
  1381. params->imagename);
  1382. exit(EXIT_FAILURE);
  1383. }
  1384. image_cfg = malloc(IMAGE_CFG_ELEMENT_MAX *
  1385. sizeof(struct image_cfg_element));
  1386. if (!image_cfg) {
  1387. fprintf(stderr, "Cannot allocate memory\n");
  1388. fclose(fcfg);
  1389. exit(EXIT_FAILURE);
  1390. }
  1391. memset(image_cfg, 0,
  1392. IMAGE_CFG_ELEMENT_MAX * sizeof(struct image_cfg_element));
  1393. rewind(fcfg);
  1394. ret = image_create_config_parse(fcfg);
  1395. fclose(fcfg);
  1396. if (ret) {
  1397. free(image_cfg);
  1398. exit(EXIT_FAILURE);
  1399. }
  1400. version = image_get_version();
  1401. switch (version) {
  1402. /*
  1403. * Fallback to version 0 if no version is provided in the
  1404. * cfg file
  1405. */
  1406. case -1:
  1407. case 0:
  1408. image = image_create_v0(&headersz, params, datasz + 4);
  1409. break;
  1410. case 1:
  1411. image = image_create_v1(&headersz, params, ptr, datasz + 4);
  1412. break;
  1413. default:
  1414. fprintf(stderr, "Unsupported version %d\n", version);
  1415. free(image_cfg);
  1416. exit(EXIT_FAILURE);
  1417. }
  1418. if (!image) {
  1419. fprintf(stderr, "Could not create image\n");
  1420. free(image_cfg);
  1421. exit(EXIT_FAILURE);
  1422. }
  1423. free(image_cfg);
  1424. /* Build and add image data checksum */
  1425. checksum = cpu_to_le32(image_checksum32((uint8_t *)ptr + headersz,
  1426. datasz));
  1427. memcpy((uint8_t *)ptr + headersz + datasz, &checksum, sizeof(uint32_t));
  1428. /* Finally copy the header into the image area */
  1429. memcpy(ptr, image, headersz);
  1430. free(image);
  1431. }
  1432. static void kwbimage_print_header(const void *ptr)
  1433. {
  1434. struct main_hdr_v0 *mhdr = (struct main_hdr_v0 *)ptr;
  1435. struct opt_hdr_v1 *ohdr;
  1436. printf("Image Type: MVEBU Boot from %s Image\n",
  1437. image_boot_mode_name(mhdr->blockid));
  1438. printf("Image version:%d\n", kwbimage_version(ptr));
  1439. for_each_opt_hdr_v1 (ohdr, mhdr) {
  1440. if (ohdr->headertype == OPT_HDR_V1_BINARY_TYPE) {
  1441. printf("BIN Hdr Size: ");
  1442. genimg_print_size(opt_hdr_v1_size(ohdr) - 12 -
  1443. 4 * ohdr->data[0]);
  1444. }
  1445. }
  1446. printf("Data Size: ");
  1447. genimg_print_size(mhdr->blocksize - sizeof(uint32_t));
  1448. printf("Load Address: %08x\n", mhdr->destaddr);
  1449. printf("Entry Point: %08x\n", mhdr->execaddr);
  1450. }
  1451. static int kwbimage_check_image_types(uint8_t type)
  1452. {
  1453. if (type == IH_TYPE_KWBIMAGE)
  1454. return EXIT_SUCCESS;
  1455. return EXIT_FAILURE;
  1456. }
  1457. static int kwbimage_verify_header(unsigned char *ptr, int image_size,
  1458. struct image_tool_params *params)
  1459. {
  1460. size_t header_size = kwbheader_size(ptr);
  1461. uint8_t blockid;
  1462. uint32_t offset;
  1463. uint32_t size;
  1464. uint8_t csum;
  1465. if (header_size > image_size)
  1466. return -FDT_ERR_BADSTRUCTURE;
  1467. if (!main_hdr_checksum_ok(ptr))
  1468. return -FDT_ERR_BADSTRUCTURE;
  1469. /* Only version 0 extended header has checksum */
  1470. if (kwbimage_version(ptr) == 0) {
  1471. struct main_hdr_v0 *mhdr = (struct main_hdr_v0 *)ptr;
  1472. if (mhdr->ext & 0x1) {
  1473. struct ext_hdr_v0 *ext_hdr = (void *)(mhdr + 1);
  1474. csum = image_checksum8(ext_hdr, sizeof(*ext_hdr) - 1);
  1475. if (csum != ext_hdr->checksum)
  1476. return -FDT_ERR_BADSTRUCTURE;
  1477. }
  1478. blockid = mhdr->blockid;
  1479. offset = le32_to_cpu(mhdr->srcaddr);
  1480. size = le32_to_cpu(mhdr->blocksize);
  1481. } else if (kwbimage_version(ptr) == 1) {
  1482. struct main_hdr_v1 *mhdr = (struct main_hdr_v1 *)ptr;
  1483. const uint8_t *mhdr_end;
  1484. struct opt_hdr_v1 *ohdr;
  1485. mhdr_end = (uint8_t *)mhdr + header_size;
  1486. for_each_opt_hdr_v1 (ohdr, ptr)
  1487. if (!opt_hdr_v1_valid_size(ohdr, mhdr_end))
  1488. return -FDT_ERR_BADSTRUCTURE;
  1489. blockid = mhdr->blockid;
  1490. offset = le32_to_cpu(mhdr->srcaddr);
  1491. size = le32_to_cpu(mhdr->blocksize);
  1492. } else {
  1493. return -FDT_ERR_BADSTRUCTURE;
  1494. }
  1495. /*
  1496. * For SATA srcaddr is specified in number of sectors.
  1497. * The main header is must be stored at sector number 1.
  1498. * This expects that sector size is 512 bytes and recalculates
  1499. * data offset to bytes relative to the main header.
  1500. */
  1501. if (blockid == IBR_HDR_SATA_ID) {
  1502. if (offset < 1)
  1503. return -FDT_ERR_BADSTRUCTURE;
  1504. offset -= 1;
  1505. offset *= 512;
  1506. }
  1507. /*
  1508. * For SDIO srcaddr is specified in number of sectors.
  1509. * This expects that sector size is 512 bytes and recalculates
  1510. * data offset to bytes.
  1511. */
  1512. if (blockid == IBR_HDR_SDIO_ID)
  1513. offset *= 512;
  1514. /*
  1515. * For PCIe srcaddr is always set to 0xFFFFFFFF.
  1516. * This expects that data starts after all headers.
  1517. */
  1518. if (blockid == IBR_HDR_PEX_ID && offset == 0xFFFFFFFF)
  1519. offset = header_size;
  1520. if (offset > image_size || offset % 4 != 0)
  1521. return -FDT_ERR_BADSTRUCTURE;
  1522. if (size < 4 || offset + size > image_size || size % 4 != 0)
  1523. return -FDT_ERR_BADSTRUCTURE;
  1524. if (image_checksum32(ptr + offset, size - 4) !=
  1525. *(uint32_t *)(ptr + offset + size - 4))
  1526. return -FDT_ERR_BADSTRUCTURE;
  1527. return 0;
  1528. }
  1529. static int kwbimage_generate(struct image_tool_params *params,
  1530. struct image_type_params *tparams)
  1531. {
  1532. FILE *fcfg;
  1533. struct stat s;
  1534. int alloc_len;
  1535. int bootfrom;
  1536. int version;
  1537. void *hdr;
  1538. int ret;
  1539. fcfg = fopen(params->imagename, "r");
  1540. if (!fcfg) {
  1541. fprintf(stderr, "Could not open input file %s\n",
  1542. params->imagename);
  1543. exit(EXIT_FAILURE);
  1544. }
  1545. if (stat(params->datafile, &s)) {
  1546. fprintf(stderr, "Could not stat data file %s: %s\n",
  1547. params->datafile, strerror(errno));
  1548. exit(EXIT_FAILURE);
  1549. }
  1550. image_cfg = malloc(IMAGE_CFG_ELEMENT_MAX *
  1551. sizeof(struct image_cfg_element));
  1552. if (!image_cfg) {
  1553. fprintf(stderr, "Cannot allocate memory\n");
  1554. fclose(fcfg);
  1555. exit(EXIT_FAILURE);
  1556. }
  1557. memset(image_cfg, 0,
  1558. IMAGE_CFG_ELEMENT_MAX * sizeof(struct image_cfg_element));
  1559. rewind(fcfg);
  1560. ret = image_create_config_parse(fcfg);
  1561. fclose(fcfg);
  1562. if (ret) {
  1563. free(image_cfg);
  1564. exit(EXIT_FAILURE);
  1565. }
  1566. bootfrom = image_get_bootfrom();
  1567. version = image_get_version();
  1568. switch (version) {
  1569. /*
  1570. * Fallback to version 0 if no version is provided in the
  1571. * cfg file
  1572. */
  1573. case -1:
  1574. case 0:
  1575. alloc_len = image_headersz_v0(NULL);
  1576. break;
  1577. case 1:
  1578. alloc_len = image_headersz_v1(NULL);
  1579. break;
  1580. default:
  1581. fprintf(stderr, "Unsupported version %d\n", version);
  1582. free(image_cfg);
  1583. exit(EXIT_FAILURE);
  1584. }
  1585. free(image_cfg);
  1586. hdr = malloc(alloc_len);
  1587. if (!hdr) {
  1588. fprintf(stderr, "%s: malloc return failure: %s\n",
  1589. params->cmdname, strerror(errno));
  1590. exit(EXIT_FAILURE);
  1591. }
  1592. memset(hdr, 0, alloc_len);
  1593. tparams->header_size = alloc_len;
  1594. tparams->hdr = hdr;
  1595. /*
  1596. * The resulting image needs to be 4-byte aligned. At least
  1597. * the Marvell hdrparser tool complains if its unaligned.
  1598. * After the image data is stored 4-byte checksum.
  1599. * Final UART image must be aligned to 128 bytes.
  1600. * Final SPI and NAND images must be aligned to 256 bytes.
  1601. * Final SATA and SDIO images must be aligned to 512 bytes.
  1602. */
  1603. if (bootfrom == IBR_HDR_SPI_ID || bootfrom == IBR_HDR_NAND_ID)
  1604. return 4 + (256 - (alloc_len + s.st_size + 4) % 256) % 256;
  1605. else if (bootfrom == IBR_HDR_SATA_ID || bootfrom == IBR_HDR_SDIO_ID)
  1606. return 4 + (512 - (alloc_len + s.st_size + 4) % 512) % 512;
  1607. else if (bootfrom == IBR_HDR_UART_ID)
  1608. return 4 + (128 - (alloc_len + s.st_size + 4) % 128) % 128;
  1609. else
  1610. return 4 + (4 - s.st_size % 4) % 4;
  1611. }
  1612. static int kwbimage_extract_subimage(void *ptr, struct image_tool_params *params)
  1613. {
  1614. struct main_hdr_v1 *mhdr = (struct main_hdr_v1 *)ptr;
  1615. size_t header_size = kwbheader_size(ptr);
  1616. struct opt_hdr_v1 *ohdr;
  1617. int idx = params->pflag;
  1618. int cur_idx = 0;
  1619. uint32_t offset;
  1620. ulong image;
  1621. ulong size;
  1622. for_each_opt_hdr_v1 (ohdr, ptr) {
  1623. if (ohdr->headertype != OPT_HDR_V1_BINARY_TYPE)
  1624. continue;
  1625. if (idx == cur_idx) {
  1626. image = (ulong)&ohdr->data[4 + 4 * ohdr->data[0]];
  1627. size = opt_hdr_v1_size(ohdr) - 12 - 4 * ohdr->data[0];
  1628. goto extract;
  1629. }
  1630. ++cur_idx;
  1631. }
  1632. if (idx != cur_idx) {
  1633. printf("Image %d is not present\n", idx);
  1634. return -1;
  1635. }
  1636. offset = le32_to_cpu(mhdr->srcaddr);
  1637. if (mhdr->blockid == IBR_HDR_SATA_ID) {
  1638. offset -= 1;
  1639. offset *= 512;
  1640. }
  1641. if (mhdr->blockid == IBR_HDR_SDIO_ID)
  1642. offset *= 512;
  1643. if (mhdr->blockid == IBR_HDR_PEX_ID && offset == 0xFFFFFFFF)
  1644. offset = header_size;
  1645. image = (ulong)((uint8_t *)ptr + offset);
  1646. size = le32_to_cpu(mhdr->blocksize) - 4;
  1647. extract:
  1648. return imagetool_save_subimage(params->outfile, image, size);
  1649. }
  1650. /*
  1651. * Report Error if xflag is set in addition to default
  1652. */
  1653. static int kwbimage_check_params(struct image_tool_params *params)
  1654. {
  1655. if (!params->iflag && (!params->imagename || !strlen(params->imagename))) {
  1656. char *msg = "Configuration file for kwbimage creation omitted";
  1657. fprintf(stderr, "Error:%s - %s\n", params->cmdname, msg);
  1658. return 1;
  1659. }
  1660. return (params->dflag && (params->fflag || params->lflag)) ||
  1661. (params->fflag && (params->dflag || params->lflag)) ||
  1662. (params->lflag && (params->dflag || params->fflag)) ||
  1663. (params->xflag);
  1664. }
  1665. /*
  1666. * kwbimage type parameters definition
  1667. */
  1668. U_BOOT_IMAGE_TYPE(
  1669. kwbimage,
  1670. "Marvell MVEBU Boot Image support",
  1671. 0,
  1672. NULL,
  1673. kwbimage_check_params,
  1674. kwbimage_verify_header,
  1675. kwbimage_print_header,
  1676. kwbimage_set_header,
  1677. kwbimage_extract_subimage,
  1678. kwbimage_check_image_types,
  1679. NULL,
  1680. kwbimage_generate
  1681. );