ezusb.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841
  1. /*
  2. * Copyright © 2001 Stephen Williams (steve@icarus.com)
  3. * Copyright © 2001-2002 David Brownell (dbrownell@users.sourceforge.net)
  4. * Copyright © 2008 Roger Williams (rawqux@users.sourceforge.net)
  5. * Copyright © 2012 Pete Batard (pete@akeo.ie)
  6. * Copyright © 2013 Federico Manzan (f.manzan@gmail.com)
  7. *
  8. * This source code is free software; you can redistribute it
  9. * and/or modify it in source code form under the terms of the GNU
  10. * General Public License as published by the Free Software
  11. * Foundation; either version 2 of the License, or (at your option)
  12. * any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program; if not, write to the Free Software
  21. * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
  22. */
  23. #include <config.h>
  24. #include <stdio.h>
  25. #include <errno.h>
  26. #include <stdlib.h>
  27. #include <string.h>
  28. #include <stdint.h>
  29. #include "libusb.h"
  30. #include "ezusb.h"
  31. /*
  32. * This file contains functions for uploading firmware into Cypress
  33. * EZ-USB microcontrollers. These chips use control endpoint 0 and vendor
  34. * specific commands to support writing into the on-chip SRAM. They also
  35. * support writing into the CPUCS register, which is how we reset the
  36. * processor after loading firmware (including the reset vector).
  37. *
  38. * These Cypress devices are 8-bit 8051 based microcontrollers with
  39. * special support for USB I/O. They come in several packages, and
  40. * some can be set up with external memory when device costs allow.
  41. * Note that the design was originally by AnchorChips, so you may find
  42. * references to that vendor (which was later merged into Cypress).
  43. * The Cypress FX parts are largely compatible with the Anchorhip ones.
  44. */
  45. int verbose = 1;
  46. /*
  47. * return true if [addr,addr+len] includes external RAM
  48. * for Anchorchips EZ-USB or Cypress EZ-USB FX
  49. */
  50. static bool fx_is_external(uint32_t addr, size_t len)
  51. {
  52. /* with 8KB RAM, 0x0000-0x1b3f can be written
  53. * we can't tell if it's a 4KB device here
  54. */
  55. if (addr <= 0x1b3f)
  56. return ((addr + len) > 0x1b40);
  57. /* there may be more RAM; unclear if we can write it.
  58. * some bulk buffers may be unused, 0x1b3f-0x1f3f
  59. * firmware can set ISODISAB for 2KB at 0x2000-0x27ff
  60. */
  61. return true;
  62. }
  63. /*
  64. * return true if [addr,addr+len] includes external RAM
  65. * for Cypress EZ-USB FX2
  66. */
  67. static bool fx2_is_external(uint32_t addr, size_t len)
  68. {
  69. /* 1st 8KB for data/code, 0x0000-0x1fff */
  70. if (addr <= 0x1fff)
  71. return ((addr + len) > 0x2000);
  72. /* and 512 for data, 0xe000-0xe1ff */
  73. else if (addr >= 0xe000 && addr <= 0xe1ff)
  74. return ((addr + len) > 0xe200);
  75. /* otherwise, it's certainly external */
  76. else
  77. return true;
  78. }
  79. /*
  80. * return true if [addr,addr+len] includes external RAM
  81. * for Cypress EZ-USB FX2LP
  82. */
  83. static bool fx2lp_is_external(uint32_t addr, size_t len)
  84. {
  85. /* 1st 16KB for data/code, 0x0000-0x3fff */
  86. if (addr <= 0x3fff)
  87. return ((addr + len) > 0x4000);
  88. /* and 512 for data, 0xe000-0xe1ff */
  89. else if (addr >= 0xe000 && addr <= 0xe1ff)
  90. return ((addr + len) > 0xe200);
  91. /* otherwise, it's certainly external */
  92. else
  93. return true;
  94. }
  95. /*****************************************************************************/
  96. /*
  97. * These are the requests (bRequest) that the bootstrap loader is expected
  98. * to recognize. The codes are reserved by Cypress, and these values match
  99. * what EZ-USB hardware, or "Vend_Ax" firmware (2nd stage loader) uses.
  100. * Cypress' "a3load" is nice because it supports both FX and FX2, although
  101. * it doesn't have the EEPROM support (subset of "Vend_Ax").
  102. */
  103. #define RW_INTERNAL 0xA0 /* hardware implements this one */
  104. #define RW_MEMORY 0xA3
  105. /*
  106. * Issues the specified vendor-specific write request.
  107. */
  108. static int ezusb_write(libusb_device_handle *device, const char *label,
  109. uint8_t opcode, uint32_t addr, const unsigned char *data, size_t len)
  110. {
  111. int status;
  112. if (verbose > 1)
  113. logerror("%s, addr 0x%08x len %4u (0x%04x)\n", label, addr, (unsigned)len, (unsigned)len);
  114. status = libusb_control_transfer(device,
  115. LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
  116. opcode, addr & 0xFFFF, addr >> 16,
  117. (unsigned char*)data, (uint16_t)len, 1000);
  118. if (status != (signed)len) {
  119. if (status < 0)
  120. logerror("%s: %s\n", label, libusb_error_name(status));
  121. else
  122. logerror("%s ==> %d\n", label, status);
  123. }
  124. if (status < 0) {
  125. errno = EIO;
  126. return -1;
  127. }
  128. return 0;
  129. }
  130. /*
  131. * Issues the specified vendor-specific read request.
  132. */
  133. static int ezusb_read(libusb_device_handle *device, const char *label,
  134. uint8_t opcode, uint32_t addr, const unsigned char *data, size_t len)
  135. {
  136. int status;
  137. if (verbose > 1)
  138. logerror("%s, addr 0x%08x len %4u (0x%04x)\n", label, addr, (unsigned)len, (unsigned)len);
  139. status = libusb_control_transfer(device,
  140. LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
  141. opcode, addr & 0xFFFF, addr >> 16,
  142. (unsigned char*)data, (uint16_t)len, 1000);
  143. if (status != (signed)len) {
  144. if (status < 0)
  145. logerror("%s: %s\n", label, libusb_error_name(status));
  146. else
  147. logerror("%s ==> %d\n", label, status);
  148. }
  149. if (status < 0) {
  150. errno = EIO;
  151. return -1;
  152. }
  153. return 0;
  154. }
  155. /*
  156. * Modifies the CPUCS register to stop or reset the CPU.
  157. * Returns false on error.
  158. */
  159. static bool ezusb_cpucs(libusb_device_handle *device, uint32_t addr, bool doRun)
  160. {
  161. int status;
  162. uint8_t data = doRun ? 0x00 : 0x01;
  163. if (verbose)
  164. logerror("%s\n", data ? "stop CPU" : "reset CPU");
  165. status = libusb_control_transfer(device,
  166. LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
  167. RW_INTERNAL, addr & 0xFFFF, addr >> 16,
  168. &data, 1, 1000);
  169. if ((status != 1) &&
  170. /* We may get an I/O error from libusb as the device disappears */
  171. ((!doRun) || (status != LIBUSB_ERROR_IO)))
  172. {
  173. const char *mesg = "can't modify CPUCS";
  174. if (status < 0)
  175. logerror("%s: %s\n", mesg, libusb_error_name(status));
  176. else
  177. logerror("%s\n", mesg);
  178. return false;
  179. } else
  180. return true;
  181. }
  182. /*
  183. * Send an FX3 jump to address command
  184. * Returns false on error.
  185. */
  186. static bool ezusb_fx3_jump(libusb_device_handle *device, uint32_t addr)
  187. {
  188. int status;
  189. if (verbose)
  190. logerror("transfer execution to Program Entry at 0x%08x\n", addr);
  191. status = libusb_control_transfer(device,
  192. LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
  193. RW_INTERNAL, addr & 0xFFFF, addr >> 16,
  194. NULL, 0, 1000);
  195. /* We may get an I/O error from libusb as the device disappears */
  196. if ((status != 0) && (status != LIBUSB_ERROR_IO))
  197. {
  198. const char *mesg = "failed to send jump command";
  199. if (status < 0)
  200. logerror("%s: %s\n", mesg, libusb_error_name(status));
  201. else
  202. logerror("%s\n", mesg);
  203. return false;
  204. } else
  205. return true;
  206. }
  207. /*****************************************************************************/
  208. /*
  209. * Parse an Intel HEX image file and invoke the poke() function on the
  210. * various segments to implement policies such as writing to RAM (with
  211. * a one or two stage loader setup, depending on the firmware) or to
  212. * EEPROM (two stages required).
  213. *
  214. * image - the hex image file
  215. * context - for use by poke()
  216. * is_external - if non-null, used to check which segments go into
  217. * external memory (writable only by software loader)
  218. * poke - called with each memory segment; errors indicated
  219. * by returning negative values.
  220. *
  221. * Caller is responsible for halting CPU as needed, such as when
  222. * overwriting a second stage loader.
  223. */
  224. static int parse_ihex(FILE *image, void *context,
  225. bool (*is_external)(uint32_t addr, size_t len),
  226. int (*poke) (void *context, uint32_t addr, bool external,
  227. const unsigned char *data, size_t len))
  228. {
  229. unsigned char data[1023];
  230. uint32_t data_addr = 0;
  231. size_t data_len = 0;
  232. int rc;
  233. int first_line = 1;
  234. bool external = false;
  235. /* Read the input file as an IHEX file, and report the memory segments
  236. * as we go. Each line holds a max of 16 bytes, but uploading is
  237. * faster (and EEPROM space smaller) if we merge those lines into larger
  238. * chunks. Most hex files keep memory segments together, which makes
  239. * such merging all but free. (But it may still be worth sorting the
  240. * hex files to make up for undesirable behavior from tools.)
  241. *
  242. * Note that EEPROM segments max out at 1023 bytes; the upload protocol
  243. * allows segments of up to 64 KBytes (more than a loader could handle).
  244. */
  245. for (;;) {
  246. char buf[512], *cp;
  247. char tmp, type;
  248. size_t len;
  249. unsigned idx, off;
  250. cp = fgets(buf, sizeof(buf), image);
  251. if (cp == NULL) {
  252. logerror("EOF without EOF record!\n");
  253. break;
  254. }
  255. /* EXTENSION: "# comment-till-end-of-line", for copyrights etc */
  256. if (buf[0] == '#')
  257. continue;
  258. if (buf[0] != ':') {
  259. logerror("not an ihex record: %s", buf);
  260. return -2;
  261. }
  262. /* ignore any newline */
  263. cp = strchr(buf, '\n');
  264. if (cp)
  265. *cp = 0;
  266. if (verbose >= 3)
  267. logerror("** LINE: %s\n", buf);
  268. /* Read the length field (up to 16 bytes) */
  269. tmp = buf[3];
  270. buf[3] = 0;
  271. len = strtoul(buf+1, NULL, 16);
  272. buf[3] = tmp;
  273. /* Read the target offset (address up to 64KB) */
  274. tmp = buf[7];
  275. buf[7] = 0;
  276. off = (unsigned int)strtoul(buf+3, NULL, 16);
  277. buf[7] = tmp;
  278. /* Initialize data_addr */
  279. if (first_line) {
  280. data_addr = off;
  281. first_line = 0;
  282. }
  283. /* Read the record type */
  284. tmp = buf[9];
  285. buf[9] = 0;
  286. type = (char)strtoul(buf+7, NULL, 16);
  287. buf[9] = tmp;
  288. /* If this is an EOF record, then make it so. */
  289. if (type == 1) {
  290. if (verbose >= 2)
  291. logerror("EOF on hexfile\n");
  292. break;
  293. }
  294. if (type != 0) {
  295. logerror("unsupported record type: %u\n", type);
  296. return -3;
  297. }
  298. if ((len * 2) + 11 > strlen(buf)) {
  299. logerror("record too short?\n");
  300. return -4;
  301. }
  302. /* FIXME check for _physically_ contiguous not just virtually
  303. * e.g. on FX2 0x1f00-0x2100 includes both on-chip and external
  304. * memory so it's not really contiguous */
  305. /* flush the saved data if it's not contiguous,
  306. * or when we've buffered as much as we can.
  307. */
  308. if (data_len != 0
  309. && (off != (data_addr + data_len)
  310. /* || !merge */
  311. || (data_len + len) > sizeof(data))) {
  312. if (is_external)
  313. external = is_external(data_addr, data_len);
  314. rc = poke(context, data_addr, external, data, data_len);
  315. if (rc < 0)
  316. return -1;
  317. data_addr = off;
  318. data_len = 0;
  319. }
  320. /* append to saved data, flush later */
  321. for (idx = 0, cp = buf+9 ; idx < len ; idx += 1, cp += 2) {
  322. tmp = cp[2];
  323. cp[2] = 0;
  324. data[data_len + idx] = (uint8_t)strtoul(cp, NULL, 16);
  325. cp[2] = tmp;
  326. }
  327. data_len += len;
  328. }
  329. /* flush any data remaining */
  330. if (data_len != 0) {
  331. if (is_external)
  332. external = is_external(data_addr, data_len);
  333. rc = poke(context, data_addr, external, data, data_len);
  334. if (rc < 0)
  335. return -1;
  336. }
  337. return 0;
  338. }
  339. /*
  340. * Parse a binary image file and write it as is to the target.
  341. * Applies to Cypress BIX images for RAM or Cypress IIC images
  342. * for EEPROM.
  343. *
  344. * image - the BIX image file
  345. * context - for use by poke()
  346. * is_external - if non-null, used to check which segments go into
  347. * external memory (writable only by software loader)
  348. * poke - called with each memory segment; errors indicated
  349. * by returning negative values.
  350. *
  351. * Caller is responsible for halting CPU as needed, such as when
  352. * overwriting a second stage loader.
  353. */
  354. static int parse_bin(FILE *image, void *context,
  355. bool (*is_external)(uint32_t addr, size_t len), int (*poke)(void *context,
  356. uint32_t addr, bool external, const unsigned char *data, size_t len))
  357. {
  358. unsigned char data[4096];
  359. uint32_t data_addr = 0;
  360. size_t data_len = 0;
  361. int rc;
  362. bool external = false;
  363. for (;;) {
  364. data_len = fread(data, 1, 4096, image);
  365. if (data_len == 0)
  366. break;
  367. if (is_external)
  368. external = is_external(data_addr, data_len);
  369. rc = poke(context, data_addr, external, data, data_len);
  370. if (rc < 0)
  371. return -1;
  372. data_addr += (uint32_t)data_len;
  373. }
  374. return feof(image)?0:-1;
  375. }
  376. /*
  377. * Parse a Cypress IIC image file and invoke the poke() function on the
  378. * various segments for writing to RAM
  379. *
  380. * image - the IIC image file
  381. * context - for use by poke()
  382. * is_external - if non-null, used to check which segments go into
  383. * external memory (writable only by software loader)
  384. * poke - called with each memory segment; errors indicated
  385. * by returning negative values.
  386. *
  387. * Caller is responsible for halting CPU as needed, such as when
  388. * overwriting a second stage loader.
  389. */
  390. static int parse_iic(FILE *image, void *context,
  391. bool (*is_external)(uint32_t addr, size_t len),
  392. int (*poke)(void *context, uint32_t addr, bool external, const unsigned char *data, size_t len))
  393. {
  394. unsigned char data[4096];
  395. uint32_t data_addr = 0;
  396. size_t data_len = 0, read_len;
  397. uint8_t block_header[4];
  398. int rc;
  399. bool external = false;
  400. long file_size, initial_pos;
  401. initial_pos = ftell(image);
  402. if (initial_pos < 0)
  403. return -1;
  404. if (fseek(image, 0L, SEEK_END) != 0)
  405. return -1;
  406. file_size = ftell(image);
  407. if (fseek(image, initial_pos, SEEK_SET) != 0)
  408. return -1;
  409. for (;;) {
  410. /* Ignore the trailing reset IIC data (5 bytes) */
  411. if (ftell(image) >= (file_size - 5))
  412. break;
  413. if (fread(&block_header, 1, sizeof(block_header), image) != 4) {
  414. logerror("unable to read IIC block header\n");
  415. return -1;
  416. }
  417. data_len = (block_header[0] << 8) + block_header[1];
  418. data_addr = (block_header[2] << 8) + block_header[3];
  419. if (data_len > sizeof(data)) {
  420. /* If this is ever reported as an error, switch to using malloc/realloc */
  421. logerror("IIC data block too small - please report this error to libusb.info\n");
  422. return -1;
  423. }
  424. read_len = fread(data, 1, data_len, image);
  425. if (read_len != data_len) {
  426. logerror("read error\n");
  427. return -1;
  428. }
  429. if (is_external)
  430. external = is_external(data_addr, data_len);
  431. rc = poke(context, data_addr, external, data, data_len);
  432. if (rc < 0)
  433. return -1;
  434. }
  435. return 0;
  436. }
  437. /* the parse call will be selected according to the image type */
  438. static int (*parse[IMG_TYPE_MAX])(FILE *image, void *context, bool (*is_external)(uint32_t addr, size_t len),
  439. int (*poke)(void *context, uint32_t addr, bool external, const unsigned char *data, size_t len))
  440. = { parse_ihex, parse_iic, parse_bin };
  441. /*****************************************************************************/
  442. /*
  443. * For writing to RAM using a first (hardware) or second (software)
  444. * stage loader and 0xA0 or 0xA3 vendor requests
  445. */
  446. typedef enum {
  447. _undef = 0,
  448. internal_only, /* hardware first-stage loader */
  449. skip_internal, /* first phase, second-stage loader */
  450. skip_external /* second phase, second-stage loader */
  451. } ram_mode;
  452. struct ram_poke_context {
  453. libusb_device_handle *device;
  454. ram_mode mode;
  455. size_t total, count;
  456. };
  457. #define RETRY_LIMIT 5
  458. static int ram_poke(void *context, uint32_t addr, bool external,
  459. const unsigned char *data, size_t len)
  460. {
  461. struct ram_poke_context *ctx = (struct ram_poke_context*)context;
  462. int rc;
  463. unsigned retry = 0;
  464. switch (ctx->mode) {
  465. case internal_only: /* CPU should be stopped */
  466. if (external) {
  467. logerror("can't write %u bytes external memory at 0x%08x\n",
  468. (unsigned)len, addr);
  469. errno = EINVAL;
  470. return -1;
  471. }
  472. break;
  473. case skip_internal: /* CPU must be running */
  474. if (!external) {
  475. if (verbose >= 2) {
  476. logerror("SKIP on-chip RAM, %u bytes at 0x%08x\n",
  477. (unsigned)len, addr);
  478. }
  479. return 0;
  480. }
  481. break;
  482. case skip_external: /* CPU should be stopped */
  483. if (external) {
  484. if (verbose >= 2) {
  485. logerror("SKIP external RAM, %u bytes at 0x%08x\n",
  486. (unsigned)len, addr);
  487. }
  488. return 0;
  489. }
  490. break;
  491. case _undef:
  492. default:
  493. logerror("bug\n");
  494. errno = EDOM;
  495. return -1;
  496. }
  497. ctx->total += len;
  498. ctx->count++;
  499. /* Retry this till we get a real error. Control messages are not
  500. * NAKed (just dropped) so time out means is a real problem.
  501. */
  502. while ((rc = ezusb_write(ctx->device,
  503. external ? "write external" : "write on-chip",
  504. external ? RW_MEMORY : RW_INTERNAL,
  505. addr, data, len)) < 0
  506. && retry < RETRY_LIMIT) {
  507. if (rc != LIBUSB_ERROR_TIMEOUT)
  508. break;
  509. retry += 1;
  510. }
  511. return rc;
  512. }
  513. /*
  514. * Load a Cypress Image file into target RAM.
  515. * See http://www.cypress.com/?docID=41351 (AN76405 PDF) for more info.
  516. */
  517. static int fx3_load_ram(libusb_device_handle *device, const char *path)
  518. {
  519. uint32_t dCheckSum, dExpectedCheckSum, dAddress, i, dLen, dLength;
  520. uint32_t* dImageBuf;
  521. unsigned char *bBuf, hBuf[4], blBuf[4], rBuf[4096];
  522. FILE *image;
  523. int ret = 0;
  524. image = fopen(path, "rb");
  525. if (image == NULL) {
  526. logerror("unable to open '%s' for input\n", path);
  527. return -2;
  528. } else if (verbose)
  529. logerror("open firmware image %s for RAM upload\n", path);
  530. // Read header
  531. if (fread(hBuf, sizeof(char), sizeof(hBuf), image) != sizeof(hBuf)) {
  532. logerror("could not read image header");
  533. ret = -3;
  534. goto exit;
  535. }
  536. // check "CY" signature byte and format
  537. if ((hBuf[0] != 'C') || (hBuf[1] != 'Y')) {
  538. logerror("image doesn't have a CYpress signature\n");
  539. ret = -3;
  540. goto exit;
  541. }
  542. // Check bImageType
  543. switch(hBuf[3]) {
  544. case 0xB0:
  545. if (verbose)
  546. logerror("normal FW binary %s image with checksum\n", (hBuf[2]&0x01)?"data":"executable");
  547. break;
  548. case 0xB1:
  549. logerror("security binary image is not currently supported\n");
  550. ret = -3;
  551. goto exit;
  552. case 0xB2:
  553. logerror("VID:PID image is not currently supported\n");
  554. ret = -3;
  555. goto exit;
  556. default:
  557. logerror("invalid image type 0x%02X\n", hBuf[3]);
  558. ret = -3;
  559. goto exit;
  560. }
  561. // Read the bootloader version
  562. if (verbose) {
  563. if ((ezusb_read(device, "read bootloader version", RW_INTERNAL, 0xFFFF0020, blBuf, 4) < 0)) {
  564. logerror("Could not read bootloader version\n");
  565. ret = -8;
  566. goto exit;
  567. }
  568. logerror("FX3 bootloader version: 0x%02X%02X%02X%02X\n", blBuf[3], blBuf[2], blBuf[1], blBuf[0]);
  569. }
  570. dCheckSum = 0;
  571. if (verbose)
  572. logerror("writing image...\n");
  573. while (1) {
  574. if ((fread(&dLength, sizeof(uint32_t), 1, image) != 1) || // read dLength
  575. (fread(&dAddress, sizeof(uint32_t), 1, image) != 1)) { // read dAddress
  576. logerror("could not read image");
  577. ret = -3;
  578. goto exit;
  579. }
  580. if (dLength == 0)
  581. break; // done
  582. // coverity[tainted_data]
  583. dImageBuf = (uint32_t*)calloc(dLength, sizeof(uint32_t));
  584. if (dImageBuf == NULL) {
  585. logerror("could not allocate buffer for image chunk\n");
  586. ret = -4;
  587. goto exit;
  588. }
  589. // read sections
  590. if (fread(dImageBuf, sizeof(uint32_t), dLength, image) != dLength) {
  591. logerror("could not read image");
  592. free(dImageBuf);
  593. ret = -3;
  594. goto exit;
  595. }
  596. for (i = 0; i < dLength; i++)
  597. dCheckSum += dImageBuf[i];
  598. dLength <<= 2; // convert to Byte length
  599. bBuf = (unsigned char*) dImageBuf;
  600. while (dLength > 0) {
  601. dLen = 4096; // 4K max
  602. if (dLen > dLength)
  603. dLen = dLength;
  604. if ((ezusb_write(device, "write firmware", RW_INTERNAL, dAddress, bBuf, dLen) < 0) ||
  605. (ezusb_read(device, "read firmware", RW_INTERNAL, dAddress, rBuf, dLen) < 0)) {
  606. logerror("R/W error\n");
  607. free(dImageBuf);
  608. ret = -5;
  609. goto exit;
  610. }
  611. // Verify data: rBuf with bBuf
  612. for (i = 0; i < dLen; i++) {
  613. if (rBuf[i] != bBuf[i]) {
  614. logerror("verify error");
  615. free(dImageBuf);
  616. ret = -6;
  617. goto exit;
  618. }
  619. }
  620. dLength -= dLen;
  621. bBuf += dLen;
  622. dAddress += dLen;
  623. }
  624. free(dImageBuf);
  625. }
  626. // read pre-computed checksum data
  627. if ((fread(&dExpectedCheckSum, sizeof(uint32_t), 1, image) != 1) ||
  628. (dCheckSum != dExpectedCheckSum)) {
  629. logerror("checksum error\n");
  630. ret = -7;
  631. goto exit;
  632. }
  633. // transfer execution to Program Entry
  634. if (!ezusb_fx3_jump(device, dAddress)) {
  635. ret = -6;
  636. }
  637. exit:
  638. fclose(image);
  639. return ret;
  640. }
  641. /*
  642. * Load a firmware file into target RAM. device is the open libusb
  643. * device, and the path is the name of the source file. Open the file,
  644. * parse the bytes, and write them in one or two phases.
  645. *
  646. * If stage == 0, this uses the first stage loader, built into EZ-USB
  647. * hardware but limited to writing on-chip memory or CPUCS. Everything
  648. * is written during one stage, unless there's an error such as the image
  649. * holding data that needs to be written to external memory.
  650. *
  651. * Otherwise, things are written in two stages. First the external
  652. * memory is written, expecting a second stage loader to have already
  653. * been loaded. Then file is re-parsed and on-chip memory is written.
  654. */
  655. int ezusb_load_ram(libusb_device_handle *device, const char *path, int fx_type, int img_type, int stage)
  656. {
  657. FILE *image;
  658. uint32_t cpucs_addr;
  659. bool (*is_external)(uint32_t off, size_t len);
  660. struct ram_poke_context ctx;
  661. int status;
  662. uint8_t iic_header[8] = { 0 };
  663. int ret = 0;
  664. if (fx_type == FX_TYPE_FX3)
  665. return fx3_load_ram(device, path);
  666. image = fopen(path, "rb");
  667. if (image == NULL) {
  668. logerror("%s: unable to open for input.\n", path);
  669. return -2;
  670. } else if (verbose > 1)
  671. logerror("open firmware image %s for RAM upload\n", path);
  672. if (img_type == IMG_TYPE_IIC) {
  673. if ( (fread(iic_header, 1, sizeof(iic_header), image) != sizeof(iic_header))
  674. || (((fx_type == FX_TYPE_FX2LP) || (fx_type == FX_TYPE_FX2)) && (iic_header[0] != 0xC2))
  675. || ((fx_type == FX_TYPE_AN21) && (iic_header[0] != 0xB2))
  676. || ((fx_type == FX_TYPE_FX1) && (iic_header[0] != 0xB6)) ) {
  677. logerror("IIC image does not contain executable code - cannot load to RAM.\n");
  678. ret = -1;
  679. goto exit;
  680. }
  681. }
  682. /* EZ-USB original/FX and FX2 devices differ, apart from the 8051 core */
  683. switch(fx_type) {
  684. case FX_TYPE_FX2LP:
  685. cpucs_addr = 0xe600;
  686. is_external = fx2lp_is_external;
  687. break;
  688. case FX_TYPE_FX2:
  689. cpucs_addr = 0xe600;
  690. is_external = fx2_is_external;
  691. break;
  692. default:
  693. cpucs_addr = 0x7f92;
  694. is_external = fx_is_external;
  695. break;
  696. }
  697. /* use only first stage loader? */
  698. if (stage == 0) {
  699. ctx.mode = internal_only;
  700. /* if required, halt the CPU while we overwrite its code/data */
  701. if (cpucs_addr && !ezusb_cpucs(device, cpucs_addr, false))
  702. {
  703. ret = -1;
  704. goto exit;
  705. }
  706. /* 2nd stage, first part? loader was already uploaded */
  707. } else {
  708. ctx.mode = skip_internal;
  709. /* let CPU run; overwrite the 2nd stage loader later */
  710. if (verbose)
  711. logerror("2nd stage: write external memory\n");
  712. }
  713. /* scan the image, first (maybe only) time */
  714. ctx.device = device;
  715. ctx.total = ctx.count = 0;
  716. status = parse[img_type](image, &ctx, is_external, ram_poke);
  717. if (status < 0) {
  718. logerror("unable to upload %s\n", path);
  719. ret = status;
  720. goto exit;
  721. }
  722. /* second part of 2nd stage: rescan */
  723. // TODO: what should we do for non HEX images there?
  724. if (stage) {
  725. ctx.mode = skip_external;
  726. /* if needed, halt the CPU while we overwrite the 1st stage loader */
  727. if (cpucs_addr && !ezusb_cpucs(device, cpucs_addr, false))
  728. {
  729. ret = -1;
  730. goto exit;
  731. }
  732. /* at least write the interrupt vectors (at 0x0000) for reset! */
  733. rewind(image);
  734. if (verbose)
  735. logerror("2nd stage: write on-chip memory\n");
  736. status = parse_ihex(image, &ctx, is_external, ram_poke);
  737. if (status < 0) {
  738. logerror("unable to completely upload %s\n", path);
  739. ret = status;
  740. goto exit;
  741. }
  742. }
  743. if (verbose && (ctx.count != 0)) {
  744. logerror("... WROTE: %d bytes, %d segments, avg %d\n",
  745. (int)ctx.total, (int)ctx.count, (int)(ctx.total/ctx.count));
  746. }
  747. /* if required, reset the CPU so it runs what we just uploaded */
  748. if (cpucs_addr && !ezusb_cpucs(device, cpucs_addr, true))
  749. ret = -1;
  750. exit:
  751. fclose(image);
  752. return ret;
  753. }