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
, 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 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 int parse_ihex(FILE *image
, void *context
, bool (*is_external
)(uint32_t addr
, size_t len
),
192 int (*poke
) (void *context
, uint32_t addr
, bool external
, const unsigned char *data
, size_t len
))
194 unsigned char data
[1023];
195 uint32_t data_addr
= 0;
199 bool external
= false;
201 /* Read the input file as an IHEX file, and report the memory segments
202 * as we go. Each line holds a max of 16 bytes, but uploading is
203 * faster (and EEPROM space smaller) if we merge those lines into larger
204 * chunks. Most hex files keep memory segments together, which makes
205 * such merging all but free. (But it may still be worth sorting the
206 * hex files to make up for undesirable behavior from tools.)
208 * Note that EEPROM segments max out at 1023 bytes; the upload protocol
209 * allows segments of up to 64 KBytes (more than a loader could handle).
217 cp
= fgets(buf
, sizeof(buf
), image
);
219 logerror("EOF without EOF record!\n");
223 /* EXTENSION: "# comment-till-end-of-line", for copyrights etc */
228 logerror("not an ihex record: %s", buf
);
232 /* ignore any newline */
233 cp
= strchr(buf
, '\n');
238 logerror("** LINE: %s\n", buf
);
240 /* Read the length field (up to 16 bytes) */
243 len
= strtoul(buf
+1, NULL
, 16);
246 /* Read the target offset (address up to 64KB) */
249 off
= strtoul(buf
+3, NULL
, 16);
252 /* Initialize data_addr */
258 /* Read the record type */
261 type
= (char)strtoul(buf
+7, NULL
, 16);
264 /* If this is an EOF record, then make it so. */
267 logerror("EOF on hexfile\n");
272 logerror("unsupported record type: %u\n", type
);
276 if ((len
* 2) + 11 > strlen(buf
)) {
277 logerror("record too short?\n");
281 /* FIXME check for _physically_ contiguous not just virtually
282 * e.g. on FX2 0x1f00-0x2100 includes both on-chip and external
283 * memory so it's not really contiguous */
285 /* flush the saved data if it's not contiguous,
286 * or when we've buffered as much as we can.
289 && (off
!= (data_addr
+ data_len
)
291 || (data_len
+ len
) > sizeof(data
))) {
293 external
= is_external(data_addr
, data_len
);
294 rc
= poke(context
, data_addr
, external
, data
, data_len
);
301 /* append to saved data, flush later */
302 for (idx
= 0, cp
= buf
+9 ; idx
< len
; idx
+= 1, cp
+= 2) {
305 data
[data_len
+ idx
] = (uint8_t)strtoul(cp
, NULL
, 16);
312 /* flush any data remaining */
315 external
= is_external(data_addr
, data_len
);
316 rc
= poke(context
, data_addr
, external
, data
, data_len
);
324 * Parse a binary image file and write it as is to the target.
325 * Applies to Cypress BIX images for RAM or Cypress IIC images
328 * image - the BIX image file
329 * context - for use by poke()
330 * is_external - if non-null, used to check which segments go into
331 * external memory (writable only by software loader)
332 * poke - called with each memory segment; errors indicated
333 * by returning negative values.
335 * Caller is responsible for halting CPU as needed, such as when
336 * overwriting a second stage loader.
338 int parse_bin(FILE *image
, void *context
, bool (*is_external
)(uint32_t addr
, size_t len
),
339 int (*poke
)(void *context
, uint32_t addr
, bool external
, const unsigned char *data
, size_t len
))
341 unsigned char data
[4096];
342 uint32_t data_addr
= 0;
345 bool external
= false;
348 data_len
= fread(data
, 1, 4096, image
);
352 external
= is_external(data_addr
, data_len
);
353 rc
= poke(context
, data_addr
, external
, data
, data_len
);
356 data_addr
+= (uint32_t)data_len
;
358 return feof(image
)?0:-1;
362 * Parse a Cypress IIC image file and invoke the poke() function on the
363 * various segments for writing to RAM
365 * image - the IIC image file
366 * context - for use by poke()
367 * is_external - if non-null, used to check which segments go into
368 * external memory (writable only by software loader)
369 * poke - called with each memory segment; errors indicated
370 * by returning negative values.
372 * Caller is responsible for halting CPU as needed, such as when
373 * overwriting a second stage loader.
375 int parse_iic(FILE *image
, void *context
, bool (*is_external
)(uint32_t addr
, size_t len
),
376 int (*poke
)(void *context
, uint32_t addr
, bool external
, const unsigned char *data
, size_t len
))
378 unsigned char data
[4096];
379 uint32_t data_addr
= 0;
380 size_t data_len
= 0, read_len
;
381 uint8_t block_header
[4];
383 bool external
= false;
384 long file_size
, initial_pos
= ftell(image
);
386 fseek(image
, 0L, SEEK_END
);
387 file_size
= ftell(image
);
388 fseek(image
, initial_pos
, SEEK_SET
);
390 /* Ignore the trailing reset IIC data (5 bytes) */
391 if (ftell(image
) >= (file_size
- 5))
393 if (fread(&block_header
, 1, sizeof(block_header
), image
) != 4) {
394 logerror("unable to read IIC block header\n");
397 data_len
= (block_header
[0] << 8) + block_header
[1];
398 data_addr
= (block_header
[2] << 8) + block_header
[3];
399 if (data_len
> sizeof(data
)) {
400 /* If this is ever reported as an error, switch to using malloc/realloc */
401 logerror("IIC data block too small - please report this error to libusbx.org\n");
404 read_len
= fread(data
, 1, data_len
, image
);
405 if (read_len
!= data_len
) {
406 logerror("read error\n");
410 external
= is_external(data_addr
, data_len
);
411 rc
= poke(context
, data_addr
, external
, data
, data_len
);
418 /* the parse call will be selected according to the image type */
419 int (*parse
[IMG_TYPE_MAX
])(FILE *image
, void *context
, bool (*is_external
)(uint32_t addr
, size_t len
),
420 int (*poke
)(void *context
, uint32_t addr
, bool external
, const unsigned char *data
, size_t len
))
421 = { parse_ihex
, parse_iic
, parse_bin
};
423 /*****************************************************************************/
426 * For writing to RAM using a first (hardware) or second (software)
427 * stage loader and 0xA0 or 0xA3 vendor requests
431 internal_only
, /* hardware first-stage loader */
432 skip_internal
, /* first phase, second-stage loader */
433 skip_external
/* second phase, second-stage loader */
436 struct ram_poke_context
{
437 libusb_device_handle
*device
;
442 #define RETRY_LIMIT 5
444 static int ram_poke(void *context
, uint32_t addr
, bool external
,
445 const unsigned char *data
, size_t len
)
447 struct ram_poke_context
*ctx
= (struct ram_poke_context
*)context
;
452 case internal_only
: /* CPU should be stopped */
454 logerror("can't write %u bytes external memory at 0x%08x\n",
455 (unsigned)len
, addr
);
459 case skip_internal
: /* CPU must be running */
462 logerror("SKIP on-chip RAM, %u bytes at 0x%08x\n",
463 (unsigned)len
, addr
);
468 case skip_external
: /* CPU should be stopped */
471 logerror("SKIP external RAM, %u bytes at 0x%08x\n",
472 (unsigned)len
, addr
);
485 /* Retry this till we get a real error. Control messages are not
486 * NAKed (just dropped) so time out means is a real problem.
488 while ((rc
= ezusb_write(ctx
->device
,
489 external
? "write external" : "write on-chip",
490 external
? RW_MEMORY
: RW_INTERNAL
,
491 addr
, data
, len
)) < 0
492 && retry
< RETRY_LIMIT
) {
493 if (rc
!= LIBUSB_ERROR_TIMEOUT
)
501 * Load a firmware file into target RAM. device is the open libusbx
502 * device, and the path is the name of the source file. Open the file,
503 * parse the bytes, and write them in one or two phases.
505 * If stage == 0, this uses the first stage loader, built into EZ-USB
506 * hardware but limited to writing on-chip memory or CPUCS. Everything
507 * is written during one stage, unless there's an error such as the image
508 * holding data that needs to be written to external memory.
510 * Otherwise, things are written in two stages. First the external
511 * memory is written, expecting a second stage loader to have already
512 * been loaded. Then file is re-parsed and on-chip memory is written.
514 int ezusb_load_ram(libusb_device_handle
*device
, const char *path
, int fx_type
, int img_type
, int stage
)
518 bool (*is_external
)(uint32_t off
, size_t len
);
519 struct ram_poke_context ctx
;
521 uint8_t iic_header
[8] = { 0 };
523 image
= fopen(path
, "rb");
525 logerror("%s: unable to open for input.\n", path
);
528 logerror("open firmware image %s for RAM upload\n", path
);
530 if (img_type
== IMG_TYPE_IIC
) {
531 if ( (fread(iic_header
, 1, sizeof(iic_header
), image
) != sizeof(iic_header
))
532 || (((fx_type
== FX_TYPE_FX2LP
) || (fx_type
== FX_TYPE_FX2
)) && (iic_header
[0] != 0xC2))
533 || ((fx_type
== FX_TYPE_AN21
) && (iic_header
[0] != 0xB2))
534 || ((fx_type
== FX_TYPE_FX1
) && (iic_header
[0] != 0xB6)) ) {
535 logerror("IIC image does not contain executable code - cannot load to RAM.\n");
540 /* EZ-USB original/FX and FX2 devices differ, apart from the 8051 core */
544 is_external
= fx2lp_is_external
;
548 is_external
= fx2_is_external
;
552 is_external
= fx_is_external
;
556 /* use only first stage loader? */
558 ctx
.mode
= internal_only
;
560 /* if required, halt the CPU while we overwrite its code/data */
561 if (cpucs_addr
&& !ezusb_cpucs(device
, cpucs_addr
, false))
564 /* 2nd stage, first part? loader was already uploaded */
566 ctx
.mode
= skip_internal
;
568 /* let CPU run; overwrite the 2nd stage loader later */
570 logerror("2nd stage: write external memory\n");
573 /* scan the image, first (maybe only) time */
575 ctx
.total
= ctx
.count
= 0;
576 status
= parse
[img_type
](image
, &ctx
, is_external
, ram_poke
);
578 logerror("unable to upload %s\n", path
);
582 /* second part of 2nd stage: rescan */
583 // TODO: what should we do for non HEX images there?
585 ctx
.mode
= skip_external
;
587 /* if needed, halt the CPU while we overwrite the 1st stage loader */
588 if (cpucs_addr
&& !ezusb_cpucs(device
, cpucs_addr
, false))
591 /* at least write the interrupt vectors (at 0x0000) for reset! */
594 logerror("2nd stage: write on-chip memory\n");
595 status
= parse_ihex(image
, &ctx
, is_external
, ram_poke
);
597 logerror("unable to completely upload %s\n", path
);
603 logerror("... WROTE: %d bytes, %d segments, avg %d\n",
604 (int)ctx
.total
, (int)ctx
.count
, (int)(ctx
.total
/ctx
.count
));
606 /* if required, reset the CPU so it runs what we just uploaded */
607 if (cpucs_addr
&& !ezusb_cpucs(device
, cpucs_addr
, true))