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