Samples: Fix compiler warnings in fxload
[libusbx.git] / examples / ezusb.c
blobce0eb8320631471e2a90016dcf3be2710e4bab4c
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)
7 * This source code is free software; you can redistribute it
8 * and/or modify it in source code form under the terms of the GNU
9 * General Public License as published by the Free Software
10 * Foundation; either version 2 of the License, or (at your option)
11 * any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
22 #include <stdio.h>
23 #include <errno.h>
24 #include <stdlib.h>
25 #include <string.h>
26 #include <stdint.h>
28 #include <libusb.h>
29 #include "ezusb.h"
31 extern void logerror(const char *format, ...)
32 __attribute__ ((format(printf, 1, 2)));
35 * This file contains functions for uploading firmware into Cypress
36 * EZ-USB microcontrollers. These chips use control endpoint 0 and vendor
37 * specific commands to support writing into the on-chip SRAM. They also
38 * support writing into the CPUCS register, which is how we reset the
39 * processor after loading firmware (including the reset vector).
41 * These Cypress devices are 8-bit 8051 based microcontrollers with
42 * special support for USB I/O. They come in several packages, and
43 * some can be set up with external memory when device costs allow.
44 * Note that the design was originally by AnchorChips, so you may find
45 * references to that vendor (which was later merged into Cypress).
46 * The Cypress FX parts are largely compatible with the Anchorhip ones.
49 int verbose;
52 * return true if [addr,addr+len] includes external RAM
53 * for Anchorchips EZ-USB or Cypress EZ-USB FX
55 static bool fx_is_external(uint32_t addr, size_t len)
57 /* with 8KB RAM, 0x0000-0x1b3f can be written
58 * we can't tell if it's a 4KB device here
60 if (addr <= 0x1b3f)
61 return ((addr + len) > 0x1b40);
63 /* there may be more RAM; unclear if we can write it.
64 * some bulk buffers may be unused, 0x1b3f-0x1f3f
65 * firmware can set ISODISAB for 2KB at 0x2000-0x27ff
67 return true;
71 * return true if [addr,addr+len] includes external RAM
72 * for Cypress EZ-USB FX2
74 static bool fx2_is_external(uint32_t addr, size_t len)
76 /* 1st 8KB for data/code, 0x0000-0x1fff */
77 if (addr <= 0x1fff)
78 return ((addr + len) > 0x2000);
80 /* and 512 for data, 0xe000-0xe1ff */
81 else if (addr >= 0xe000 && addr <= 0xe1ff)
82 return ((addr + len) > 0xe200);
84 /* otherwise, it's certainly external */
85 else
86 return true;
90 * return true if [addr,addr+len] includes external RAM
91 * for Cypress EZ-USB FX2LP
93 static bool fx2lp_is_external(uint32_t addr, size_t len)
95 /* 1st 16KB for data/code, 0x0000-0x3fff */
96 if (addr <= 0x3fff)
97 return ((addr + len) > 0x4000);
99 /* and 512 for data, 0xe000-0xe1ff */
100 else if (addr >= 0xe000 && addr <= 0xe1ff)
101 return ((addr + len) > 0xe200);
103 /* otherwise, it's certainly external */
104 else
105 return true;
109 /*****************************************************************************/
112 * These are the requests (bRequest) that the bootstrap loader is expected
113 * to recognize. The codes are reserved by Cypress, and these values match
114 * what EZ-USB hardware, or "Vend_Ax" firmware (2nd stage loader) uses.
115 * Cypress' "a3load" is nice because it supports both FX and FX2, although
116 * it doesn't have the EEPROM support (subset of "Vend_Ax").
118 #define RW_INTERNAL 0xA0 /* hardware implements this one */
119 #define RW_MEMORY 0xA3
122 * Issues the specified vendor-specific write request.
124 static int ezusb_write(libusb_device_handle *device, const char *label,
125 uint8_t opcode, uint32_t addr, const unsigned char *data, size_t len)
127 int status;
129 if (verbose)
130 logerror("%s, addr 0x%08x len %4u (0x%04x)\n", label, addr, (unsigned)len, (unsigned)len);
131 status = libusb_control_transfer(device,
132 LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
133 opcode, addr & 0xFFFF, addr >> 16,
134 (unsigned char*)data, (uint16_t)len, 1000);
135 if (status != len) {
136 if (status < 0)
137 logerror("%s: %s\n", label, libusb_error_name(status));
138 else
139 logerror("%s ==> %d\n", label, status);
141 return (status < 0) ? -EIO : 0;
145 * Modifies the CPUCS register to stop or reset the CPU.
146 * Returns false on error.
148 static bool ezusb_cpucs(libusb_device_handle *device, uint32_t addr, bool doRun)
150 int status;
151 uint8_t data = doRun ? 0x00 : 0x01;
153 if (verbose)
154 logerror("%s\n", data ? "stop CPU" : "reset CPU");
155 status = libusb_control_transfer(device,
156 LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE,
157 RW_INTERNAL, addr & 0xFFFF, addr >> 16,
158 &data, 1, 1000);
159 if ((status != 1) &&
160 /* We may get an I/O error from libusbx as the device disappears */
161 ((!doRun) || (status != LIBUSB_ERROR_IO)))
163 const char *mesg = "can't modify CPUCS";
164 if (status < 0)
165 logerror("%s: %s\n", mesg, libusb_error_name(status));
166 else
167 logerror("%s\n", mesg);
168 return false;
169 } else
170 return true;
173 /*****************************************************************************/
176 * Parse an Intel HEX image file and invoke the poke() function on the
177 * various segments to implement policies such as writing to RAM (with
178 * a one or two stage loader setup, depending on the firmware) or to
179 * EEPROM (two stages required).
181 * image - the hex image file
182 * context - for use by poke()
183 * is_external - if non-null, used to check which segments go into
184 * external memory (writable only by software loader)
185 * poke - called with each memory segment; errors indicated
186 * by returning negative values.
188 * Caller is responsible for halting CPU as needed, such as when
189 * overwriting a second stage loader.
191 static int parse_ihex(FILE *image, void *context,
192 bool (*is_external)(uint32_t addr, size_t len),
193 int (*poke) (void *context, uint32_t addr, bool external,
194 const unsigned char *data, size_t len))
196 unsigned char data[1023];
197 uint32_t data_addr = 0;
198 size_t data_len = 0;
199 int rc;
200 int first_line = 1;
201 bool external = false;
203 /* Read the input file as an IHEX file, and report the memory segments
204 * as we go. Each line holds a max of 16 bytes, but uploading is
205 * faster (and EEPROM space smaller) if we merge those lines into larger
206 * chunks. Most hex files keep memory segments together, which makes
207 * such merging all but free. (But it may still be worth sorting the
208 * hex files to make up for undesirable behavior from tools.)
210 * Note that EEPROM segments max out at 1023 bytes; the upload protocol
211 * allows segments of up to 64 KBytes (more than a loader could handle).
213 for (;;) {
214 char buf[512], *cp;
215 char tmp, type;
216 size_t len;
217 unsigned idx, off;
219 cp = fgets(buf, sizeof(buf), image);
220 if (cp == NULL) {
221 logerror("EOF without EOF record!\n");
222 break;
225 /* EXTENSION: "# comment-till-end-of-line", for copyrights etc */
226 if (buf[0] == '#')
227 continue;
229 if (buf[0] != ':') {
230 logerror("not an ihex record: %s", buf);
231 return -2;
234 /* ignore any newline */
235 cp = strchr(buf, '\n');
236 if (cp)
237 *cp = 0;
239 if (verbose >= 3)
240 logerror("** LINE: %s\n", buf);
242 /* Read the length field (up to 16 bytes) */
243 tmp = buf[3];
244 buf[3] = 0;
245 len = strtoul(buf+1, NULL, 16);
246 buf[3] = tmp;
248 /* Read the target offset (address up to 64KB) */
249 tmp = buf[7];
250 buf[7] = 0;
251 off = strtoul(buf+3, NULL, 16);
252 buf[7] = tmp;
254 /* Initialize data_addr */
255 if (first_line) {
256 data_addr = off;
257 first_line = 0;
260 /* Read the record type */
261 tmp = buf[9];
262 buf[9] = 0;
263 type = (char)strtoul(buf+7, NULL, 16);
264 buf[9] = tmp;
266 /* If this is an EOF record, then make it so. */
267 if (type == 1) {
268 if (verbose >= 2)
269 logerror("EOF on hexfile\n");
270 break;
273 if (type != 0) {
274 logerror("unsupported record type: %u\n", type);
275 return -3;
278 if ((len * 2) + 11 > strlen(buf)) {
279 logerror("record too short?\n");
280 return -4;
283 /* FIXME check for _physically_ contiguous not just virtually
284 * e.g. on FX2 0x1f00-0x2100 includes both on-chip and external
285 * memory so it's not really contiguous */
287 /* flush the saved data if it's not contiguous,
288 * or when we've buffered as much as we can.
290 if (data_len != 0
291 && (off != (data_addr + data_len)
292 /* || !merge */
293 || (data_len + len) > sizeof(data))) {
294 if (is_external)
295 external = is_external(data_addr, data_len);
296 rc = poke(context, data_addr, external, data, data_len);
297 if (rc < 0)
298 return -1;
299 data_addr = off;
300 data_len = 0;
303 /* append to saved data, flush later */
304 for (idx = 0, cp = buf+9 ; idx < len ; idx += 1, cp += 2) {
305 tmp = cp[2];
306 cp[2] = 0;
307 data[data_len + idx] = (uint8_t)strtoul(cp, NULL, 16);
308 cp[2] = tmp;
310 data_len += len;
314 /* flush any data remaining */
315 if (data_len != 0) {
316 if (is_external)
317 external = is_external(data_addr, data_len);
318 rc = poke(context, data_addr, external, data, data_len);
319 if (rc < 0)
320 return -1;
322 return 0;
326 * Parse a binary image file and write it as is to the target.
327 * Applies to Cypress BIX images for RAM or Cypress IIC images
328 * for EEPROM.
330 * image - the BIX image file
331 * context - for use by poke()
332 * is_external - if non-null, used to check which segments go into
333 * external memory (writable only by software loader)
334 * poke - called with each memory segment; errors indicated
335 * by returning negative values.
337 * Caller is responsible for halting CPU as needed, such as when
338 * overwriting a second stage loader.
340 static int parse_bin(FILE *image, void *context,
341 bool (*is_external)(uint32_t addr, size_t len), int (*poke)(void *context,
342 uint32_t addr, bool external, const unsigned char *data, size_t len))
344 unsigned char data[4096];
345 uint32_t data_addr = 0;
346 size_t data_len = 0;
347 int rc;
348 bool external = false;
350 for (;;) {
351 data_len = fread(data, 1, 4096, image);
352 if (data_len == 0)
353 break;
354 if (is_external)
355 external = is_external(data_addr, data_len);
356 rc = poke(context, data_addr, external, data, data_len);
357 if (rc < 0)
358 return -1;
359 data_addr += (uint32_t)data_len;
361 return feof(image)?0:-1;
365 * Parse a Cypress IIC image file and invoke the poke() function on the
366 * various segments for writing to RAM
368 * image - the IIC image file
369 * context - for use by poke()
370 * is_external - if non-null, used to check which segments go into
371 * external memory (writable only by software loader)
372 * poke - called with each memory segment; errors indicated
373 * by returning negative values.
375 * Caller is responsible for halting CPU as needed, such as when
376 * overwriting a second stage loader.
378 static int parse_iic(FILE *image, void *context,
379 bool (*is_external)(uint32_t addr, size_t len),
380 int (*poke)(void *context, uint32_t addr, bool external, const unsigned char *data, size_t len))
382 unsigned char data[4096];
383 uint32_t data_addr = 0;
384 size_t data_len = 0, read_len;
385 uint8_t block_header[4];
386 int rc;
387 bool external = false;
388 long file_size, initial_pos = ftell(image);
390 fseek(image, 0L, SEEK_END);
391 file_size = ftell(image);
392 fseek(image, initial_pos, SEEK_SET);
393 for (;;) {
394 /* Ignore the trailing reset IIC data (5 bytes) */
395 if (ftell(image) >= (file_size - 5))
396 break;
397 if (fread(&block_header, 1, sizeof(block_header), image) != 4) {
398 logerror("unable to read IIC block header\n");
399 return -1;
401 data_len = (block_header[0] << 8) + block_header[1];
402 data_addr = (block_header[2] << 8) + block_header[3];
403 if (data_len > sizeof(data)) {
404 /* If this is ever reported as an error, switch to using malloc/realloc */
405 logerror("IIC data block too small - please report this error to libusbx.org\n");
406 return -1;
408 read_len = fread(data, 1, data_len, image);
409 if (read_len != data_len) {
410 logerror("read error\n");
411 return -1;
413 if (is_external)
414 external = is_external(data_addr, data_len);
415 rc = poke(context, data_addr, external, data, data_len);
416 if (rc < 0)
417 return -1;
419 return 0;
422 /* the parse call will be selected according to the image type */
423 int (*parse[IMG_TYPE_MAX])(FILE *image, void *context, bool (*is_external)(uint32_t addr, size_t len),
424 int (*poke)(void *context, uint32_t addr, bool external, const unsigned char *data, size_t len))
425 = { parse_ihex, parse_iic, parse_bin };
427 /*****************************************************************************/
430 * For writing to RAM using a first (hardware) or second (software)
431 * stage loader and 0xA0 or 0xA3 vendor requests
433 typedef enum {
434 _undef = 0,
435 internal_only, /* hardware first-stage loader */
436 skip_internal, /* first phase, second-stage loader */
437 skip_external /* second phase, second-stage loader */
438 } ram_mode;
440 struct ram_poke_context {
441 libusb_device_handle *device;
442 ram_mode mode;
443 size_t total, count;
446 #define RETRY_LIMIT 5
448 static int ram_poke(void *context, uint32_t addr, bool external,
449 const unsigned char *data, size_t len)
451 struct ram_poke_context *ctx = (struct ram_poke_context*)context;
452 int rc;
453 unsigned retry = 0;
455 switch (ctx->mode) {
456 case internal_only: /* CPU should be stopped */
457 if (external) {
458 logerror("can't write %u bytes external memory at 0x%08x\n",
459 (unsigned)len, addr);
460 return -EINVAL;
462 break;
463 case skip_internal: /* CPU must be running */
464 if (!external) {
465 if (verbose >= 2) {
466 logerror("SKIP on-chip RAM, %u bytes at 0x%08x\n",
467 (unsigned)len, addr);
469 return 0;
471 break;
472 case skip_external: /* CPU should be stopped */
473 if (external) {
474 if (verbose >= 2) {
475 logerror("SKIP external RAM, %u bytes at 0x%08x\n",
476 (unsigned)len, addr);
478 return 0;
480 break;
481 case _undef:
482 default:
483 logerror("bug\n");
484 return -EDOM;
487 ctx->total += len;
488 ctx->count++;
490 /* Retry this till we get a real error. Control messages are not
491 * NAKed (just dropped) so time out means is a real problem.
493 while ((rc = ezusb_write(ctx->device,
494 external ? "write external" : "write on-chip",
495 external ? RW_MEMORY : RW_INTERNAL,
496 addr, data, len)) < 0
497 && retry < RETRY_LIMIT) {
498 if (rc != LIBUSB_ERROR_TIMEOUT)
499 break;
500 retry += 1;
502 return rc;
506 * Load a firmware file into target RAM. device is the open libusbx
507 * device, and the path is the name of the source file. Open the file,
508 * parse the bytes, and write them in one or two phases.
510 * If stage == 0, this uses the first stage loader, built into EZ-USB
511 * hardware but limited to writing on-chip memory or CPUCS. Everything
512 * is written during one stage, unless there's an error such as the image
513 * holding data that needs to be written to external memory.
515 * Otherwise, things are written in two stages. First the external
516 * memory is written, expecting a second stage loader to have already
517 * been loaded. Then file is re-parsed and on-chip memory is written.
519 int ezusb_load_ram(libusb_device_handle *device, const char *path, int fx_type, int img_type, int stage)
521 FILE *image;
522 uint32_t cpucs_addr;
523 bool (*is_external)(uint32_t off, size_t len);
524 struct ram_poke_context ctx;
525 int status;
526 uint8_t iic_header[8] = { 0 };
528 image = fopen(path, "rb");
529 if (image == NULL) {
530 logerror("%s: unable to open for input.\n", path);
531 return -2;
532 } else if (verbose)
533 logerror("open firmware image %s for RAM upload\n", path);
535 if (img_type == IMG_TYPE_IIC) {
536 if ( (fread(iic_header, 1, sizeof(iic_header), image) != sizeof(iic_header))
537 || (((fx_type == FX_TYPE_FX2LP) || (fx_type == FX_TYPE_FX2)) && (iic_header[0] != 0xC2))
538 || ((fx_type == FX_TYPE_AN21) && (iic_header[0] != 0xB2))
539 || ((fx_type == FX_TYPE_FX1) && (iic_header[0] != 0xB6)) ) {
540 logerror("IIC image does not contain executable code - cannot load to RAM.\n");
541 return -1;
545 /* EZ-USB original/FX and FX2 devices differ, apart from the 8051 core */
546 switch(fx_type) {
547 case FX_TYPE_FX2LP:
548 cpucs_addr = 0xe600;
549 is_external = fx2lp_is_external;
550 break;
551 case FX_TYPE_FX2:
552 cpucs_addr = 0xe600;
553 is_external = fx2_is_external;
554 break;
555 default:
556 cpucs_addr = 0x7f92;
557 is_external = fx_is_external;
558 break;
561 /* use only first stage loader? */
562 if (stage == 0) {
563 ctx.mode = internal_only;
565 /* if required, halt the CPU while we overwrite its code/data */
566 if (cpucs_addr && !ezusb_cpucs(device, cpucs_addr, false))
567 return -1;
569 /* 2nd stage, first part? loader was already uploaded */
570 } else {
571 ctx.mode = skip_internal;
573 /* let CPU run; overwrite the 2nd stage loader later */
574 if (verbose)
575 logerror("2nd stage: write external memory\n");
578 /* scan the image, first (maybe only) time */
579 ctx.device = device;
580 ctx.total = ctx.count = 0;
581 status = parse[img_type](image, &ctx, is_external, ram_poke);
582 if (status < 0) {
583 logerror("unable to upload %s\n", path);
584 return status;
587 /* second part of 2nd stage: rescan */
588 // TODO: what should we do for non HEX images there?
589 if (stage) {
590 ctx.mode = skip_external;
592 /* if needed, halt the CPU while we overwrite the 1st stage loader */
593 if (cpucs_addr && !ezusb_cpucs(device, cpucs_addr, false))
594 return -1;
596 /* at least write the interrupt vectors (at 0x0000) for reset! */
597 rewind(image);
598 if (verbose)
599 logerror("2nd stage: write on-chip memory\n");
600 status = parse_ihex(image, &ctx, is_external, ram_poke);
601 if (status < 0) {
602 logerror("unable to completely upload %s\n", path);
603 return status;
607 if (verbose)
608 logerror("... WROTE: %d bytes, %d segments, avg %d\n",
609 (int)ctx.total, (int)ctx.count, (int)(ctx.total/ctx.count));
611 /* if required, reset the CPU so it runs what we just uploaded */
612 if (cpucs_addr && !ezusb_cpucs(device, cpucs_addr, true))
613 return -1;
615 return 0;