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)
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)
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.
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
32 extern void logerror(const char *format
, ...)
33 __attribute__ ((format(printf
, 1, 2)));
36 * This file contains functions for uploading firmware into Cypress
37 * EZ-USB microcontrollers. These chips use control endpoint 0 and vendor
38 * specific commands to support writing into the on-chip SRAM. They also
39 * support writing into the CPUCS register, which is how we reset the
40 * processor after loading firmware (including the reset vector).
42 * These Cypress devices are 8-bit 8051 based microcontrollers with
43 * special support for USB I/O. They come in several packages, and
44 * some can be set up with external memory when device costs allow.
45 * Note that the design was originally by AnchorChips, so you may find
46 * references to that vendor (which was later merged into Cypress).
47 * The Cypress FX parts are largely compatible with the Anchorhip ones.
53 * return true if [addr,addr+len] includes external RAM
54 * for Anchorchips EZ-USB or Cypress EZ-USB FX
56 static bool fx_is_external(uint32_t addr
, size_t len
)
58 /* with 8KB RAM, 0x0000-0x1b3f can be written
59 * we can't tell if it's a 4KB device here
62 return ((addr
+ len
) > 0x1b40);
64 /* there may be more RAM; unclear if we can write it.
65 * some bulk buffers may be unused, 0x1b3f-0x1f3f
66 * firmware can set ISODISAB for 2KB at 0x2000-0x27ff
72 * return true if [addr,addr+len] includes external RAM
73 * for Cypress EZ-USB FX2
75 static bool fx2_is_external(uint32_t addr
, size_t len
)
77 /* 1st 8KB for data/code, 0x0000-0x1fff */
79 return ((addr
+ len
) > 0x2000);
81 /* and 512 for data, 0xe000-0xe1ff */
82 else if (addr
>= 0xe000 && addr
<= 0xe1ff)
83 return ((addr
+ len
) > 0xe200);
85 /* otherwise, it's certainly external */
91 * return true if [addr,addr+len] includes external RAM
92 * for Cypress EZ-USB FX2LP
94 static bool fx2lp_is_external(uint32_t addr
, size_t len
)
96 /* 1st 16KB for data/code, 0x0000-0x3fff */
98 return ((addr
+ len
) > 0x4000);
100 /* and 512 for data, 0xe000-0xe1ff */
101 else if (addr
>= 0xe000 && addr
<= 0xe1ff)
102 return ((addr
+ len
) > 0xe200);
104 /* otherwise, it's certainly external */
110 /*****************************************************************************/
113 * These are the requests (bRequest) that the bootstrap loader is expected
114 * to recognize. The codes are reserved by Cypress, and these values match
115 * what EZ-USB hardware, or "Vend_Ax" firmware (2nd stage loader) uses.
116 * Cypress' "a3load" is nice because it supports both FX and FX2, although
117 * it doesn't have the EEPROM support (subset of "Vend_Ax").
119 #define RW_INTERNAL 0xA0 /* hardware implements this one */
120 #define RW_MEMORY 0xA3
123 * Issues the specified vendor-specific write request.
125 static int ezusb_write(libusb_device_handle
*device
, const char *label
,
126 uint8_t opcode
, uint32_t addr
, const unsigned char *data
, size_t len
)
131 logerror("%s, addr 0x%08x len %4u (0x%04x)\n", label
, addr
, (unsigned)len
, (unsigned)len
);
132 status
= libusb_control_transfer(device
,
133 LIBUSB_ENDPOINT_OUT
| LIBUSB_REQUEST_TYPE_VENDOR
| LIBUSB_RECIPIENT_DEVICE
,
134 opcode
, addr
& 0xFFFF, addr
>> 16,
135 (unsigned char*)data
, (uint16_t)len
, 1000);
138 logerror("%s: %s\n", label
, libusb_error_name(status
));
140 logerror("%s ==> %d\n", label
, status
);
142 return (status
< 0) ? -EIO
: 0;
146 * Issues the specified vendor-specific read request.
148 static int ezusb_read(libusb_device_handle
*device
, const char *label
,
149 uint8_t opcode
, uint32_t addr
, const unsigned char *data
, size_t len
)
154 logerror("%s, addr 0x%08x len %4u (0x%04x)\n", label
, addr
, (unsigned)len
, (unsigned)len
);
155 status
= libusb_control_transfer(device
,
156 LIBUSB_ENDPOINT_IN
| LIBUSB_REQUEST_TYPE_VENDOR
| LIBUSB_RECIPIENT_DEVICE
,
157 opcode
, addr
& 0xFFFF, addr
>> 16,
158 (unsigned char*)data
, (uint16_t)len
, 1000);
161 logerror("%s: %s\n", label
, libusb_error_name(status
));
163 logerror("%s ==> %d\n", label
, status
);
165 return (status
< 0) ? -EIO
: 0;
169 * Modifies the CPUCS register to stop or reset the CPU.
170 * Returns false on error.
172 static bool ezusb_cpucs(libusb_device_handle
*device
, uint32_t addr
, bool doRun
)
175 uint8_t data
= doRun
? 0x00 : 0x01;
178 logerror("%s\n", data
? "stop CPU" : "reset CPU");
179 status
= libusb_control_transfer(device
,
180 LIBUSB_ENDPOINT_OUT
| LIBUSB_REQUEST_TYPE_VENDOR
| LIBUSB_RECIPIENT_DEVICE
,
181 RW_INTERNAL
, addr
& 0xFFFF, addr
>> 16,
184 /* We may get an I/O error from libusbx as the device disappears */
185 ((!doRun
) || (status
!= LIBUSB_ERROR_IO
)))
187 const char *mesg
= "can't modify CPUCS";
189 logerror("%s: %s\n", mesg
, libusb_error_name(status
));
191 logerror("%s\n", mesg
);
197 /*****************************************************************************/
200 * Parse an Intel HEX image file and invoke the poke() function on the
201 * various segments to implement policies such as writing to RAM (with
202 * a one or two stage loader setup, depending on the firmware) or to
203 * EEPROM (two stages required).
205 * image - the hex image file
206 * context - for use by poke()
207 * is_external - if non-null, used to check which segments go into
208 * external memory (writable only by software loader)
209 * poke - called with each memory segment; errors indicated
210 * by returning negative values.
212 * Caller is responsible for halting CPU as needed, such as when
213 * overwriting a second stage loader.
215 static int parse_ihex(FILE *image
, void *context
,
216 bool (*is_external
)(uint32_t addr
, size_t len
),
217 int (*poke
) (void *context
, uint32_t addr
, bool external
,
218 const unsigned char *data
, size_t len
))
220 unsigned char data
[1023];
221 uint32_t data_addr
= 0;
225 bool external
= false;
227 /* Read the input file as an IHEX file, and report the memory segments
228 * as we go. Each line holds a max of 16 bytes, but uploading is
229 * faster (and EEPROM space smaller) if we merge those lines into larger
230 * chunks. Most hex files keep memory segments together, which makes
231 * such merging all but free. (But it may still be worth sorting the
232 * hex files to make up for undesirable behavior from tools.)
234 * Note that EEPROM segments max out at 1023 bytes; the upload protocol
235 * allows segments of up to 64 KBytes (more than a loader could handle).
243 cp
= fgets(buf
, sizeof(buf
), image
);
245 logerror("EOF without EOF record!\n");
249 /* EXTENSION: "# comment-till-end-of-line", for copyrights etc */
254 logerror("not an ihex record: %s", buf
);
258 /* ignore any newline */
259 cp
= strchr(buf
, '\n');
264 logerror("** LINE: %s\n", buf
);
266 /* Read the length field (up to 16 bytes) */
269 len
= strtoul(buf
+1, NULL
, 16);
272 /* Read the target offset (address up to 64KB) */
275 off
= (int)strtoul(buf
+3, NULL
, 16);
278 /* Initialize data_addr */
284 /* Read the record type */
287 type
= (char)strtoul(buf
+7, NULL
, 16);
290 /* If this is an EOF record, then make it so. */
293 logerror("EOF on hexfile\n");
298 logerror("unsupported record type: %u\n", type
);
302 if ((len
* 2) + 11 > strlen(buf
)) {
303 logerror("record too short?\n");
307 /* FIXME check for _physically_ contiguous not just virtually
308 * e.g. on FX2 0x1f00-0x2100 includes both on-chip and external
309 * memory so it's not really contiguous */
311 /* flush the saved data if it's not contiguous,
312 * or when we've buffered as much as we can.
315 && (off
!= (data_addr
+ data_len
)
317 || (data_len
+ len
) > sizeof(data
))) {
319 external
= is_external(data_addr
, data_len
);
320 rc
= poke(context
, data_addr
, external
, data
, data_len
);
327 /* append to saved data, flush later */
328 for (idx
= 0, cp
= buf
+9 ; idx
< len
; idx
+= 1, cp
+= 2) {
331 data
[data_len
+ idx
] = (uint8_t)strtoul(cp
, NULL
, 16);
338 /* flush any data remaining */
341 external
= is_external(data_addr
, data_len
);
342 rc
= poke(context
, data_addr
, external
, data
, data_len
);
350 * Parse a binary image file and write it as is to the target.
351 * Applies to Cypress BIX images for RAM or Cypress IIC images
354 * image - the BIX image file
355 * context - for use by poke()
356 * is_external - if non-null, used to check which segments go into
357 * external memory (writable only by software loader)
358 * poke - called with each memory segment; errors indicated
359 * by returning negative values.
361 * Caller is responsible for halting CPU as needed, such as when
362 * overwriting a second stage loader.
364 static int parse_bin(FILE *image
, void *context
,
365 bool (*is_external
)(uint32_t addr
, size_t len
), int (*poke
)(void *context
,
366 uint32_t addr
, bool external
, const unsigned char *data
, size_t len
))
368 unsigned char data
[4096];
369 uint32_t data_addr
= 0;
372 bool external
= false;
375 data_len
= fread(data
, 1, 4096, image
);
379 external
= is_external(data_addr
, data_len
);
380 rc
= poke(context
, data_addr
, external
, data
, data_len
);
383 data_addr
+= (uint32_t)data_len
;
385 return feof(image
)?0:-1;
389 * Parse a Cypress IIC image file and invoke the poke() function on the
390 * various segments for writing to RAM
392 * image - the IIC image file
393 * context - for use by poke()
394 * is_external - if non-null, used to check which segments go into
395 * external memory (writable only by software loader)
396 * poke - called with each memory segment; errors indicated
397 * by returning negative values.
399 * Caller is responsible for halting CPU as needed, such as when
400 * overwriting a second stage loader.
402 static int parse_iic(FILE *image
, void *context
,
403 bool (*is_external
)(uint32_t addr
, size_t len
),
404 int (*poke
)(void *context
, uint32_t addr
, bool external
, const unsigned char *data
, size_t len
))
406 unsigned char data
[4096];
407 uint32_t data_addr
= 0;
408 size_t data_len
= 0, read_len
;
409 uint8_t block_header
[4];
411 bool external
= false;
412 long file_size
, initial_pos
= ftell(image
);
414 fseek(image
, 0L, SEEK_END
);
415 file_size
= ftell(image
);
416 fseek(image
, initial_pos
, SEEK_SET
);
418 /* Ignore the trailing reset IIC data (5 bytes) */
419 if (ftell(image
) >= (file_size
- 5))
421 if (fread(&block_header
, 1, sizeof(block_header
), image
) != 4) {
422 logerror("unable to read IIC block header\n");
425 data_len
= (block_header
[0] << 8) + block_header
[1];
426 data_addr
= (block_header
[2] << 8) + block_header
[3];
427 if (data_len
> sizeof(data
)) {
428 /* If this is ever reported as an error, switch to using malloc/realloc */
429 logerror("IIC data block too small - please report this error to libusbx.org\n");
432 read_len
= fread(data
, 1, data_len
, image
);
433 if (read_len
!= data_len
) {
434 logerror("read error\n");
438 external
= is_external(data_addr
, data_len
);
439 rc
= poke(context
, data_addr
, external
, data
, data_len
);
446 /* the parse call will be selected according to the image type */
447 int (*parse
[IMG_TYPE_MAX
])(FILE *image
, void *context
, bool (*is_external
)(uint32_t addr
, size_t len
),
448 int (*poke
)(void *context
, uint32_t addr
, bool external
, const unsigned char *data
, size_t len
))
449 = { parse_ihex
, parse_iic
, parse_bin
};
451 /*****************************************************************************/
454 * For writing to RAM using a first (hardware) or second (software)
455 * stage loader and 0xA0 or 0xA3 vendor requests
459 internal_only
, /* hardware first-stage loader */
460 skip_internal
, /* first phase, second-stage loader */
461 skip_external
/* second phase, second-stage loader */
464 struct ram_poke_context
{
465 libusb_device_handle
*device
;
470 #define RETRY_LIMIT 5
472 static int ram_poke(void *context
, uint32_t addr
, bool external
,
473 const unsigned char *data
, size_t len
)
475 struct ram_poke_context
*ctx
= (struct ram_poke_context
*)context
;
480 case internal_only
: /* CPU should be stopped */
482 logerror("can't write %u bytes external memory at 0x%08x\n",
483 (unsigned)len
, addr
);
487 case skip_internal
: /* CPU must be running */
490 logerror("SKIP on-chip RAM, %u bytes at 0x%08x\n",
491 (unsigned)len
, addr
);
496 case skip_external
: /* CPU should be stopped */
499 logerror("SKIP external RAM, %u bytes at 0x%08x\n",
500 (unsigned)len
, addr
);
514 /* Retry this till we get a real error. Control messages are not
515 * NAKed (just dropped) so time out means is a real problem.
517 while ((rc
= ezusb_write(ctx
->device
,
518 external
? "write external" : "write on-chip",
519 external
? RW_MEMORY
: RW_INTERNAL
,
520 addr
, data
, len
)) < 0
521 && retry
< RETRY_LIMIT
) {
522 if (rc
!= LIBUSB_ERROR_TIMEOUT
)
530 * Load an Cypress Image file into target RAM.
531 * The file is assumed to be in Cypress IMG format.
533 int fx3_load_ram(libusb_device_handle
*device
, const char *path
)
535 unsigned int dCheckSum
, dExpectedCheckSum
, dAddress
, i
, dLen
, dLength
;
536 unsigned short wSignature
;
537 unsigned int dImageBuf
[512 * 1024];
538 unsigned char *bBuf
, rBuf
[4096];
541 image
= fopen(path
, "rb");
543 logerror("%s: unable to open for input.\n", path
);
546 logerror("open firmware image %s for RAM upload\n", path
);
548 fread(&wSignature
, 1, 2, image
); // read signature bytes
549 if (wSignature
!= 0x5943) { // check CY signature byte
550 logerror("Invalid image");
553 fread(&i
, 2, 1, image
); // skip 2 dummy bytes
557 fread(&dLength
, 4, 1, image
); // read dLength
558 fread(&dAddress
, 4, 1, image
); // read dAddress
563 fread(dImageBuf
, 4, dLength
, image
);
564 for (i
= 0; i
< dLength
; i
++)
565 dCheckSum
+= dImageBuf
[i
];
566 dLength
<<= 2; // convert to Byte length
567 bBuf
= (unsigned char*) dImageBuf
;
569 while (dLength
> 0) {
570 dLen
= 4096; // 4K max
573 ezusb_write(device
, "Write firmware", RW_INTERNAL
, dAddress
, bBuf
, dLen
);
574 ezusb_read(device
, "Read firmware", RW_INTERNAL
, dAddress
, rBuf
, dLen
);
575 // Verify data: rBuf with bBuf
576 for (i
= 0; i
< dLen
; i
++) {
577 if (rBuf
[i
] != bBuf
[i
]) {
578 logerror("Fail to verify image");
589 // read pre-computed checksum data
590 fread(&dExpectedCheckSum
, 4, 1, image
);
591 if (dCheckSum
!= dExpectedCheckSum
) {
592 logerror("Fail to boot due to checksum error\n");
596 // transfer execution to Program Entry
597 ezusb_write(device
, "Jump command", RW_INTERNAL
, dAddress
, NULL
, 0);
604 * Load a firmware file into target RAM. device is the open libusbx
605 * device, and the path is the name of the source file. Open the file,
606 * parse the bytes, and write them in one or two phases.
608 * If stage == 0, this uses the first stage loader, built into EZ-USB
609 * hardware but limited to writing on-chip memory or CPUCS. Everything
610 * is written during one stage, unless there's an error such as the image
611 * holding data that needs to be written to external memory.
613 * Otherwise, things are written in two stages. First the external
614 * memory is written, expecting a second stage loader to have already
615 * been loaded. Then file is re-parsed and on-chip memory is written.
617 int ezusb_load_ram(libusb_device_handle
*device
, const char *path
, int fx_type
, int img_type
, int stage
)
621 bool (*is_external
)(uint32_t off
, size_t len
);
622 struct ram_poke_context ctx
;
624 uint8_t iic_header
[8] = { 0 };
626 if (fx_type
== FX_TYPE_FX3
)
627 return fx3_load_ram(device
, path
);
629 image
= fopen(path
, "rb");
631 logerror("%s: unable to open for input.\n", path
);
634 logerror("open firmware image %s for RAM upload\n", path
);
636 if (img_type
== IMG_TYPE_IIC
) {
637 if ( (fread(iic_header
, 1, sizeof(iic_header
), image
) != sizeof(iic_header
))
638 || (((fx_type
== FX_TYPE_FX2LP
) || (fx_type
== FX_TYPE_FX2
)) && (iic_header
[0] != 0xC2))
639 || ((fx_type
== FX_TYPE_AN21
) && (iic_header
[0] != 0xB2))
640 || ((fx_type
== FX_TYPE_FX1
) && (iic_header
[0] != 0xB6)) ) {
641 logerror("IIC image does not contain executable code - cannot load to RAM.\n");
646 /* EZ-USB original/FX and FX2 devices differ, apart from the 8051 core */
650 is_external
= fx2lp_is_external
;
654 is_external
= fx2_is_external
;
658 is_external
= fx_is_external
;
662 /* use only first stage loader? */
664 ctx
.mode
= internal_only
;
666 /* if required, halt the CPU while we overwrite its code/data */
667 if (cpucs_addr
&& !ezusb_cpucs(device
, cpucs_addr
, false))
670 /* 2nd stage, first part? loader was already uploaded */
672 ctx
.mode
= skip_internal
;
674 /* let CPU run; overwrite the 2nd stage loader later */
676 logerror("2nd stage: write external memory\n");
679 /* scan the image, first (maybe only) time */
681 ctx
.total
= ctx
.count
= 0;
682 status
= parse
[img_type
](image
, &ctx
, is_external
, ram_poke
);
684 logerror("unable to upload %s\n", path
);
688 /* second part of 2nd stage: rescan */
689 // TODO: what should we do for non HEX images there?
691 ctx
.mode
= skip_external
;
693 /* if needed, halt the CPU while we overwrite the 1st stage loader */
694 if (cpucs_addr
&& !ezusb_cpucs(device
, cpucs_addr
, false))
697 /* at least write the interrupt vectors (at 0x0000) for reset! */
700 logerror("2nd stage: write on-chip memory\n");
701 status
= parse_ihex(image
, &ctx
, is_external
, ram_poke
);
703 logerror("unable to completely upload %s\n", path
);
709 logerror("... WROTE: %d bytes, %d segments, avg %d\n",
710 (int)ctx
.total
, (int)ctx
.count
, (int)(ctx
.total
/ctx
.count
));
712 /* if required, reset the CPU so it runs what we just uploaded */
713 if (cpucs_addr
&& !ezusb_cpucs(device
, cpucs_addr
, true))