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)
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
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.
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
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
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 */
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 */
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 */
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 */
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
)
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);
137 logerror("%s: %s\n", label
, libusb_error_name(status
));
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
)
151 uint8_t data
= doRun
? 0x00 : 0x01;
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,
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";
165 logerror("%s: %s\n", mesg
, libusb_error_name(status
));
167 logerror("%s\n", mesg
);
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;
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).
219 cp
= fgets(buf
, sizeof(buf
), image
);
221 logerror("EOF without EOF record!\n");
225 /* EXTENSION: "# comment-till-end-of-line", for copyrights etc */
230 logerror("not an ihex record: %s", buf
);
234 /* ignore any newline */
235 cp
= strchr(buf
, '\n');
240 logerror("** LINE: %s\n", buf
);
242 /* Read the length field (up to 16 bytes) */
245 len
= strtoul(buf
+1, NULL
, 16);
248 /* Read the target offset (address up to 64KB) */
251 off
= strtoul(buf
+3, NULL
, 16);
254 /* Initialize data_addr */
260 /* Read the record type */
263 type
= (char)strtoul(buf
+7, NULL
, 16);
266 /* If this is an EOF record, then make it so. */
269 logerror("EOF on hexfile\n");
274 logerror("unsupported record type: %u\n", type
);
278 if ((len
* 2) + 11 > strlen(buf
)) {
279 logerror("record too short?\n");
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.
291 && (off
!= (data_addr
+ data_len
)
293 || (data_len
+ len
) > sizeof(data
))) {
295 external
= is_external(data_addr
, data_len
);
296 rc
= poke(context
, data_addr
, external
, data
, data_len
);
303 /* append to saved data, flush later */
304 for (idx
= 0, cp
= buf
+9 ; idx
< len
; idx
+= 1, cp
+= 2) {
307 data
[data_len
+ idx
] = (uint8_t)strtoul(cp
, NULL
, 16);
314 /* flush any data remaining */
317 external
= is_external(data_addr
, data_len
);
318 rc
= poke(context
, data_addr
, external
, data
, data_len
);
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
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;
348 bool external
= false;
351 data_len
= fread(data
, 1, 4096, image
);
355 external
= is_external(data_addr
, data_len
);
356 rc
= poke(context
, data_addr
, external
, data
, data_len
);
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];
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
);
394 /* Ignore the trailing reset IIC data (5 bytes) */
395 if (ftell(image
) >= (file_size
- 5))
397 if (fread(&block_header
, 1, sizeof(block_header
), image
) != 4) {
398 logerror("unable to read IIC block header\n");
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");
408 read_len
= fread(data
, 1, data_len
, image
);
409 if (read_len
!= data_len
) {
410 logerror("read error\n");
414 external
= is_external(data_addr
, data_len
);
415 rc
= poke(context
, data_addr
, external
, data
, data_len
);
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
435 internal_only
, /* hardware first-stage loader */
436 skip_internal
, /* first phase, second-stage loader */
437 skip_external
/* second phase, second-stage loader */
440 struct ram_poke_context
{
441 libusb_device_handle
*device
;
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
;
456 case internal_only
: /* CPU should be stopped */
458 logerror("can't write %u bytes external memory at 0x%08x\n",
459 (unsigned)len
, addr
);
463 case skip_internal
: /* CPU must be running */
466 logerror("SKIP on-chip RAM, %u bytes at 0x%08x\n",
467 (unsigned)len
, addr
);
472 case skip_external
: /* CPU should be stopped */
475 logerror("SKIP external RAM, %u bytes at 0x%08x\n",
476 (unsigned)len
, addr
);
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
)
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
)
523 bool (*is_external
)(uint32_t off
, size_t len
);
524 struct ram_poke_context ctx
;
526 uint8_t iic_header
[8] = { 0 };
528 image
= fopen(path
, "rb");
530 logerror("%s: unable to open for input.\n", path
);
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");
545 /* EZ-USB original/FX and FX2 devices differ, apart from the 8051 core */
549 is_external
= fx2lp_is_external
;
553 is_external
= fx2_is_external
;
557 is_external
= fx_is_external
;
561 /* use only first stage loader? */
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))
569 /* 2nd stage, first part? loader was already uploaded */
571 ctx
.mode
= skip_internal
;
573 /* let CPU run; overwrite the 2nd stage loader later */
575 logerror("2nd stage: write external memory\n");
578 /* scan the image, first (maybe only) time */
580 ctx
.total
= ctx
.count
= 0;
581 status
= parse
[img_type
](image
, &ctx
, is_external
, ram_poke
);
583 logerror("unable to upload %s\n", path
);
587 /* second part of 2nd stage: rescan */
588 // TODO: what should we do for non HEX images there?
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))
596 /* at least write the interrupt vectors (at 0x0000) for reset! */
599 logerror("2nd stage: write on-chip memory\n");
600 status
= parse_ihex(image
, &ctx
, is_external
, ram_poke
);
602 logerror("unable to completely upload %s\n", path
);
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))